Count the number of prime numbers less than a non-negative number, n
Test instructions: The number of all primes less than n.
Ideas:
1. Scope in the 1~n-1, the first to remove the multiples of 2, and then delete the multiples of 3, and then delete the multiples of 5 ... Each time you delete a multiple of the smallest element in the collection, the remaining elements are the prime number after multiple loops.
2. However, to save a 1~n-1 integer set, if n is large, then it is possible that the set will not fit, all attempts to solve with Bitset, the K-bit represents the integer k+1;
3. If the K-bit is 0, then the prime number is 1, and the non-prime number is indicated;
The code is as follows:
Public intCountPrimes (intN) {if(N < 3)return0; BitSet BS=NewBitSet (n-1); Bs.clear (1); Bs.set (0); intCount = N-2; for(intI=1; I<n-1; ) { for(intj=2*i+1; j<n-1; j=j+ (i+1)) { if(!Bs.get (j)) {Bs.set (j); Count--; }} I= Bs.nextclearbit (i+1); } returncount; }
LeetCode-204 Count Primes