*204. Count Primes (siecing prime)

Count the number of prime numbers less than a non-negative number, n.

Example:

Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.

Solution2: ssieving: need a helping array with false initialization: false(prime) true(non- prime), inner loop: only set the multiple of prime.

class Solution {
    int res = 0;
    //solution 1: fun: check each unmber n * (n)
    //seieve solution: 2,3,5,7,11,13
    public int countPrimes(int n) {
        // 2: 1 3: 2 4: 2  ,5 :3 ....
        boolean[] aux = new boolean[n+1]; //all false (prime)
        for(int i = 2; i <n; i++){//i: number in n
            if(aux[i] == false) res++;
            if(aux[i] == true) continue; //pass the non -prime question: 2 and 4 have the same multiple??
            //sieving the number is multiple of this target nuber : aux[i]
            for(int j = 2; j*i <n; j++){
                aux[j*i] = true;
            } 
        }
        return res;
    }
    //time: i = 2 :n/2
    //      i = 3 : n/3 or smaller
    //    sum(n/i) : i is prime : n*sum(1/i) = n*(lg(lgn))
}

Solution 2:  is prime function

Count the number of prime numbers less than a non-negative number, n.

Example:

Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.

猜你喜欢

转载自www.cnblogs.com/stiles/p/leetcode204.html