筛素数

来源:互联网 发布:掌上大学无法连接网络 编辑:程序博客网 时间:2024/06/12 01:23

主要看程序:

空间 O (n)  时间 O (n) 常数大

10000000 跑了 0.858 秒 可以接受


#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespace std;const int N = 100000000;int n, tot, f[N], prime[N];void shaiprime(int n) {for(int i = 2; i <= n; i++) {if(!f[i]) prime[++tot] = i;for(int j = 1; j <= tot && i*prime[j] <= n; j++) {f[i*prime[j]] = 1;if(!i%prime[j]) break;}}}int main() {  freopen("shaiprime.in", "r", stdin); freopen("shaiprime.out", "w", stdout);scanf("%d\n", &n); shaiprime(n);printf("%d\n", tot);  fclose(stdin);  fclose(stdout);  return 0;}


0 0
原创粉丝点击