Count Primes
Prime number Count
Idea 1: Violence law. which determines whether each number n is a prime need to verify that any number less than n is not divisible by N, this step is O (n). So the overall complexity is O (n^2).
Idea 2: The optimized version of Idea 1. If a number n is not a prime, then n = p * Q. P <= Q, you can introduce p * p <= N, that is, p <=√n. So the idea of a only need to determine whether any less than or equal to √n can not divide n. The overall time complexity becomes O (n^1.5).
1 Public intCountPrimes (intN) {2 intCount = 0;3 for(inti = 1; I < n; i++) {4 if(IsPrime (i)) count++;5 }6 returncount;7 }8 9 Private BooleanIsPrime (intnum) {Ten if(Num <= 1)return false; One //Loop ' s ending condition is i * I <= num instead of i <= sqrt (num) A //To avoid repeatedly calling an expensive function sqrt (). - for(inti = 2; I * i <= num; i++) { - if(num% i = = 0)return false; the } - return true; -}View Code
Idea 3: Erato Screening method: For the current number I (I want to start from 2), put it in multiples of 2i,3i,4i ... Are marked as not prime, and then the next number of I that is not marked must be prime.
Optimization: (1) If a number has already been marked as not a prime, skip directly, since its multiples must have been already marked before, (2) for the number I, without starting from the 2i mark, directly starting from the I * I mark (also must have been marked before).
The spatial complexity of the algorithm is O (n) and the time complexity is O (n log log n). (Proof see wiki)
1 Public classSolution {2 Public intCountPrimes (intN) {3 Boolean[] Notprime =New Boolean[n];4 intCount = 0;5 for(inti = 2; I < n; i++) {6 if(Notprime[i] = =false) {7count++;8 for(Longj = i; I * j < n; J + +) {9notprime[(int) (I * j)] =true;Ten } One } A } - - returncount; the } -}View Code
Math Problem of algorithm