[Leetcode] Count Primes 數素數

Count Primes

Description:數組

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

埃拉託斯特尼篩法 Sieve of Eratosthenes

複雜度

時間 O(NloglogN) 空間 O(N)code

思路

若是一個數是另外一個數的倍數,那這個數確定不是素數。利用這個性質,咱們能夠創建一個素數數組,從2開始將素數的倍數都標註爲不是素數。第一輪將四、六、8等表爲非素數,而後遍歷到3,發現3沒有被標記爲非素數,則將六、九、12等標記爲非素數,一直到N爲止,再數一遍素數數組中有多少素數。ip

代碼

public class Solution {
    public int countPrimes(int n) {
        boolean[] prime = new boolean[n];
        Arrays.fill(prime, true);
        for(int i = 2; i < n; i++){
            if(prime[i]){
                // 將i的2倍、3倍、4倍...都標記爲非素數
                for(int j = i * 2; j < n; j =  j + i){
                    prime[j] = false;
                }
            }
        }
        int count = 0;
        for(int i = 2; i < n; i++){
            if(prime[i]) count++;
        }
        return count;
    }
}
相關文章
相關標籤/搜索