Description:
Count the number of prime numbers less than a non-negative number, n.
Find the number of characters less than N.
1, with the most simple algorithm is timed out.
Public classSolution { Public intCountPrimes (intN) {if(N < 2){ return0; } intresult = 0; for(inti = 2; I < n; i++){ if(Isprimes (i)) {result++; } } returnresult; } Public BooleanIsprimes (intnum) { for(inti = 2; I <= math.sqrt (num); i++){ if(num% i = = 0){ return false; } } return true; }}
2, Eratosthenes sieve method Sieve of Eratosthenes
We go from 2 to the square root N, find the first prime number 2, and then all of its multiples are marked out, then to the next prime number 3, mark all its multiples, once and so, until the square root of N, when the array is not marked with numbers is prime. We need a n-1-length bool array to record whether each number is marked, and the length is n-1 because the topic is said to be less than N of the mass number, not including N.
Public classSolution { Public intCountPrimes (intN) {Boolean[] IsPrime =New Boolean[n]; for(inti = 2; I < n; i++) {Isprime[i]=true; } for(inti = 2; I * i < n; i++) { if(!isprime[i])Continue; for(intj = i * I; J < N; J + =i) {isprime[j]=false; } } intCount = 0; for(inti = 2; I < n; i++) { if(Isprime[i]) count++; } returncount; } }
Leetcode 204. Count Primes Find the number of primes----------Java