204. Count Primes

Description:

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

思路: 從前向後掃描,第一次遇到沒標記的應該是沒有因子的質數。然後把後面所有這個質數的倍數都標記了。

    public int countPrimes(int n) {
        if(n<2) return 0;
        boolean[] marked = new boolean[n];
        int count=0;
        for(int i=2; i<n; i++){
            //剪枝1:標記所有質數的倍數爲非質數,剩下沒標記的就是質數。
            if(!marked[i-1]) {
                count++;
                //剪枝2:小於當前數的倍數已經考慮過了
                int temp = n/i;
                for(int j=i; j<=temp; j++){
                    marked[i*j-1]=true;
                }
            }
        }
        return count;
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章