您的位置:首页 > 其它

The Sieve of Eratosthens(爱拉托逊斯筛选法)分析

2010-08-04 13:53 429 查看

The Sieve of Eratosthens
爱拉托逊斯筛选法

(原创链接:http://www.wutianqi.com/?p=264)memset(vis, 0, sizeof(vis));
2for(int i = 2; i <= 100; i++)
3 for(int j = i*2; j <= 100; j += i)
4 vis[j] = 1;

上面的代码效率已经很高了。
但还可以继续优化。
看一个改进的代码:
——————————————————
代码二:

1int m = sqrt(double(n+0.5));
2
3for(int i = 2; i <= m; i++)
4 if(!vis[i])
5//版本二
2//Author: Tanky Woo
3//Blog: www.wutianqi.com
4
5#include <stdio.h>
6#include <string.h>
7#include <math.h>
8int vis[100];
9int prime[100];
10int c = 0;
11int n;
12int main()
13 scanf("%d", &n);
15 int cnt = 1;
16
17 memset(vis, 0, sizeof(vis));
18 int m = sqrt(double(n+0.5));
19
20 for(int i = 2; i <= m; i++)
21 if(!vis[i])
22 prime[c++] = i;
24 for(int j = i*i; j <= n; j += i)
25 vis[j] = 1;
27 //printf("%d\n", j);
28 }
29 }
30
31 for(int i = 2; i < n; i++)
32 if(vis[i] == 0)
34 printf("%d ", i);
36 cnt++;
37 if(cnt % 10 == 0)
38 printf("\n");
39 }
40 }
41 printf("\ncnt = %d\n", cnt);
42 return 0;
43}

完毕。

欢迎大家和我交流。(我的博客:http://www.wutianqi.com/)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: