A Eratosthenes sieve method (the idea is very good is the complexity is a bit high) (O (Nlognlogn))
The multiple of the principle prime number is not a number of prime numbers, the number of which is not more than the multiples of his small (1) of the numbers is prime.
2 is the prime number 4,6,8,10 .... Not prime (marking)
3 are prime numbers (not marked), 6,9,.... Not prime (same marking)
4 are not prime numbers (marked)
5 are prime numbers (not marked) 5.10 ... not prime (Mark)
So you can get all the prime numbers by pushing them down.
Recommended to find all the prime numbers within 1e5 too big, the complexity is too high.
#include <bits/stdc++.h>using namespacestd;Const intmaxn=1e5+5;BOOLPRIME[MAXN];intP[maxn];vector<int>vs;voidFindprime () { for(inti =2; i < MAXN; i + +) prime[i] =true; for(inti =2; i < MAXN; i + +){ if(Prime[i]) {vs.push_back (i); for(intj = i*2; J < Maxn; J + =i) {prime[j]=false; } } }}intMain () {findprime (); cout<<vs.size () <<Endl;}
In fact, most of the time when looking for, for example, 10 in 2 when marked at 5 is also marked in fact 5 to mark the other number of time can start from 5*5 (note 1e5 when i*i will explode int)
#include <bits/stdc++.h>
#define INT Long Longusing namespacestd;Const intmaxn=1e5+5;BOOLPRIME[MAXN];intP[maxn];vector<int>vs;voidFindprime () { for(inti =2; i < MAXN; i + +) prime[i] =true; for(inti =2; i < MAXN; i + +){ if(Prime[i]) {vs.push_back (i); for(intj = i*i; J <maxn; J + =i) {prime[j]=false; } } }}int32_tMain () {findprime (); cout<<vs.size () <<Endl;}
Two linear sieve
#include <bits/stdc++.h>using namespacestd;Const intmaxn=1e5+5;BOOLPRIME[MAXN];intP[MAXN];intTot;vector<int>vs;voidFindprime () { for(inti =2; i < MAXN; i + +) prime[i] =true; for(inti =2; i < MAXN; i + +) { if(Prime[i]) p[++tot]=I,vs.push_back (i); for(intj=1; J<=tot && i*p[j]<maxn; J + +) {Prime[i*p[j]]=false; if(i%p[j]==0) Break; } }}intMain () {findprime (); cout<<vs.size () <<Endl;}
Screening of prime numbers (mainly introduction of sieve linear sieve) (there are good ways to follow up to be continued)