判断a是否为素数,求1——n的素数个数
考虑欧拉筛法————
//判断是否为素数;计算1到n的素数个数 #include<iostream> #include<cstring> #define MAX 10000000 using namespace std; bool b[MAX+1]; //b中0表示为质数,1表示为非质数 int c[MAX+1]; int sushu(int n){ memset(b, 0, n + 1); b[0]=1; b[1]=1; //1既非素数也非合数 int i, j, cnt = 0, t; for (i = 2; i <= n; i++){ if (!b[i]){ c[cnt++] = i; } for (j = 0; j<cnt; j++){ t = i*c[j]; //质数乘质数为合数,质数乘合数为合数,一个合数必可写成质数乘一个数的形式 if (t > n) break; b[t] = true; if (i%c[j] == 0) break; } } return cnt; } int main() { int T,a,n,c; cin>>T; while(T--) { cin>>a>>n; c=sushu(n); if(b[a]==0) cout<<"YES "<<c<<endl; else cout<<"NO "<<c<<endl; } return 0; }
看看别人的代码,10亿秒了,,
#include<iostream> #include<cstring> #include<cstdio> #include<ctime> #include<algorithm> using namespace std; int n=11000000; bool visit[11000000]; int prime[11000000]; void init_prim() { memset(visit, true, sizeof(visit)); visit[0] = visit[1] = false; int num = 0; for (int i = 2; i <= n; ++i) { if (visit[i] == true) { num++; prime[num] = i; } /*for (int j = 1; ((j <= num) && (i * prime[j] <= n)); ++j) { visit[i * prime[j]] = false; if (i % prime[j] == 0) break; }*/ for(int j = 2 ; i *j <=n; j++) { visit[i * j] = false; } } } int OutNum(int n) { int i; for(i=1;prime[i]<=n;i++); return i-1; } int main() { clock_t start, finish; double duration; start = clock(); init_prim(); int T; cin >> T; while(T--) { int x,n; cin >> x >> n; if(visit[x]) cout << "YES" << " "; else cout << "NO" << " "; cout << OutNum(n) << endl; } finish = clock(); duration = (double)(finish - start) / CLOCKS_PER_SEC*1000.0; printf( "%f ms\n", duration ); return 0; }
时间: 2024-10-17 06:21:19