Description:
Count the number of prime numbers less than a non-negative number, n
Click to show more hints.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
For all primes within N, previously seen a topic, by marking out all non-primes, and then finding the prime number, the code is as follows:
1 Public intCountPrimes (intN) {2 if(n = = 0 | | n = = 1 | | n = = 2)3 return0;4 int[] flag =New int[n];5 for(inti = 2; I < math.sqrt (flag.length); i++) {6 if(Flag[i] = = 0)7 for(intj = i; I * J < flag.length; J + +) {8Flag[i * j] = 1;9 }Ten } One intCount = 0; A for(inti = 2; i < flag.length; i++) -Count + =Flag[i]; -BitSet bs =NewBitSet (); the bs.ne - returnFlag.length-count-2; -}
It is worth noting that the outer loop only needs to be to the square root of N, because the inner loop begins with the i*j. In Leetcode, if no Gargan, it will overflow.
Java Prime Prime Numbers-leetcode 204