Description:
Count the number of prime numbers less than a non-negative number, n
Hint:the number n could is in the order of 100,000 to 5,000,000.
Click to show more hints.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Ernie Eratosthenes Sieve method. Starting from the first prime number to remove its multiples, then the next one is not removed must be a prime, repeat the above process. Specific can be seen.
But the submission has found a timeout! Time Out!!!! Isn't that a positive solution? So after a meal optimization, finally AC dropped.
1 classSolution {2 Public:3 intCountPrimes (intN) {4vector<BOOL> P (N,true);5 //Remove all even numbers outside of 26 for(inti =4; I < n; i + =2) P[i] =false; 7 //The previous step has removed even, so i + = 2,j + = 2 can be used here8 for(inti =3; I * i < n; i + =2) { 9 if(P[i]) for(intj =3; I * j < n; J + =2) {TenP[i * j] =false; One } A } - intCNT =0; - for(inti =2; I < n; ++i)if(P[i]) + +CNT; the returnCNT; - } -};
However, actually spent 890ms, probably using the vector bar, and then tried again with the array, sure enough:
1 classSolution {2 Public:3 intCountPrimes (intN) {4 BOOL*p =New BOOL[n];5Memset (P,true,sizeof(BOOL) *n);6 for(inti =2; I * i < n; ++i) {7 if(P[i]) for(intj =2; I * j < n; ++j) {8P[i * j] =false;9 }Ten } One intCNT =0; A for(inti =2; I < n; ++i)if(P[i]) + +CNT; - Delete []p; - returnCNT; the } -};
Without any optimization, it only took 400ms, optimized as long as 170ms. Therefore, the difference in efficiency between the vector and the original array is evident in this question.
[Leetcode] Count Primes