Description:
Count the number of prime numbers less than a non-negative number, n
Click to show more hints.
References:
How many Primes is there?
Sieve of Eratosthenes
The above two references can be seen, the second gives a classic solution, in Java Core explained Bitset also mentioned the
However, the gap between the basic version and the continuously improved version time is very large:
First basic version [722MS]:
classSolution { Public: intCountPrimes (intN) {vector<BOOL> Filter (n +1,false); intCNT =0; for(intI=2; i<n; i++) { if(!Filter[i]) {CNT++; for(intJ=i+i; J < N; j+=i) {filter[j]=true; } } } returnCNT; }};
Here selected I+i as the starting point of J, in fact, the i+i is a multiple of 2 has been placed in front of the loop, the same as all of the number of less than a multiple is also set, and thus directly from the I*i, [619ms]
classSolution { Public: intCountPrimes (intN) {vector<BOOL> Filter (N,false); intCNT =0; intLMT =sqrt (n); for(intI=2; i<n; i++) { if(!Filter[i]) {CNT++; if(I > LMT)Continue; for(intJ=i*i; J < N; j+=i) {filter[j]=true; } } } returnCNT; }};
Because the prime number is necessarily not even, the outer loop can only consider odd-numbered cases, which reduces the calculation by half [224ms]
classSolution { Public: intCountPrimes (intN) {if(N <=2)return 0; Vector<BOOL> Filter (N,false); intCNT =1; intLMT =sqrt (n); for(intI=3; i<n; i+=2) { if(!Filter[i]) {CNT++; if(I > LMT)Continue; for(intJ=i*i; J < N; j+=i) {filter[j]=true; } } } returnCNT; }};
The corresponding inner loop can also be considered only odd, because the even condition must have been set at the time of i=2 [140ms]
classSolution { Public: intCountPrimes (intN) {if(N <=2)return 0; Vector<BOOL> Filter (N,false); intCNT =1; intLMT =sqrt (n); for(intI=3; i<n; i+=2) { if(!Filter[i]) {CNT++; if(I > LMT)Continue; for(intJ=i*i, step = i <<1; J < N; j+=Step) {Filter[j]=true; } } } returnCNT; }};
Changing vectors to arrays can also increase speed, [41ms]
classSolution { Public: intCountPrimes (intN) {if(N <=2)return 0; BOOL* Filter =New BOOL[n]; for(intI=0; i<n; i++) Filter[i] =false; intCNT =1; intLMT =sqrt (n); for(intI=3; i<n; i+=2) { if(!Filter[i]) {CNT++; if(I > LMT)Continue; for(intJ=i*i, step = i <<1; J < N; j+=Step) {Filter[j]=true; } } } Delete[] filter; returnCNT; }};
Leetcode Count Primes