1:3 Basic prime-number judgments
1: Exhaustive method: Suitable for when the data is small. Complexity of Time: O ()
intIsPrime (intN) { if(n==1|| n==0) return 0; intm = sqrt (n+0.5); for(inti =2; I <= m; i++) if(n%i==0) return 0; return 1;}
2: Elatosseni Sieve method to calculate the time complexity of prime number: O ()
#include <cmath>#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespacestd;Const intMAXN =1e6;intBOOK[MAXN];intPRIME[MAXN];intMainvoid){ intN; intnum; while(~SCANF ("%d",&N)) {num=0; for(inti =2; I <= N; i++) { if(book[i]==0) Prime[num++] =i; for(intj = i * I; J <= N; J + =i) {book[j]=1; } } for(inti =0; i < num; i++) cout<<prime[i]<<Endl; } return 0;}
3: Euler Sieve method
#include <cmath>#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespacestd;Const intMAXN =1e6;intPRIME[MAXN];intBOOK[MAXN];intMainvoid){ intN; intnum; while(~SCANF ("%d", &N)) {num=0; for(inti =2; I <= N; i++) { if(book[i]==0) Prime[num++] =i; for(intj =0; J < num; J + +) { if(I*prime[j] >N) Break;//jump out when you are too bigBOOK[I*PRIME[J]] =1; if((i%prime[j]) = =0)//If I is a composite, and I% prime[j] = = 0 Break; } } for(inti =0; i < num; i++) printf ("%d\n", Prime[i]); } return 0;}
Number theory-prime number