[LeetCode] 204. Count Primes 計數質數

Description:html

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

click to show more hints.python

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.oop

計數出小於非負整數n的質數數量。質數(prime number)又稱素數,有無限個。質數定義爲在大於1的天然數中,除了1和它自己之外再也不有其餘因數。this

解法:埃拉託斯特尼篩法 Sieve of Eratosthenesspa

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

Java:htm

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;
    }
}

Python:

class Solution:
    # @param {integer} n
    # @return {integer}
    def countPrimes(self, n):
        isPrime = [True] * max(n, 2)
        isPrime[0], isPrime[1] = False, False
        x = 2
        while x * x < n:
            if isPrime[x]:
                p = x * x
                while p < n:
                    isPrime[p] = False
                    p += x
            x += 1
        return sum(isPrime)

Python:

class Solution(object):
    def countPrimes(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n <= 2: return 0
        vis = [False] * n
        for i in range(2, int(n ** 0.5) + 1):
            if vis[i]: continue
            j = i
            while j * i < n:
                vis[j * i] = True
                j += 1
        ans = 0
        for i in range(2, n):
            if not vis[i]: ans += 1
        return ans

C++:

class Solution {
public:
    int countPrimes(int n) {
        if(!n||n==1)  return 0;
        vector<bool> isPrime(n,true);
        // Loop's ending condition is i * i < n instead of i < sqrt(n)
        // to avoid repeatedly calling an expensive function sqrt().
        for(int i=2;i*i<n;++i)
        {
            if(!isPrime[i]) continue;
            //填表起點i*i,如3*3,由於3*2已填,步長+i
            for(int j=i*i;j<n;j+=i)
            {
                isPrime[j]=false;
            }
        }
        int count=0;
        for(int i=2;i<n;++i)
        {
            if(isPrime[i])  ++count;
        }
        return count;
    }
};

  

All LeetCode Questions List 題目彙總

相關文章
相關標籤/搜索