Leetcode-204(Java) Count Primes

Description:

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

 

传送门:https://leetcode.com/problems/count-primes/

 

尽可能把查找次数缩小,直接用双重for会超时。

public class Solution {
    public int countPrimes(int n)
    {
        //默认全为false
        boolean res[] = new boolean[n];
        for(int i = 2; i * i < n; i++)
        {
            if(!res[i]){
                //直接找到相乘小与n的数,说明不是素数
                for(int j = i; i * j < n; j++){
                    res[i * j] = true;
                }
            }
        }
        int count = 0;
        for(int i = 2; i < n; i++)
            if(res[i] == false)
                count++;
        return count;
    }
}

 

posted @ 2015-08-05 09:54  zetrov  阅读(190)  评论(0编辑  收藏  举报