码迷,mamicode.com
首页 > 其他好文 > 详细

*204. Count Primes (siecing prime)

时间:2018-06-09 00:00:29      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:family   IV   top   tip   turn   amp   prim   pre   col   

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.

*204. Count Primes (siecing prime)

标签:family   IV   top   tip   turn   amp   prim   pre   col   

原文地址:https://www.cnblogs.com/stiles/p/leetcode204.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!