[LeetCode] 204. Count Primes 質數的個數


 

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.

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

 

這道題給定一個非負數n,讓我們求小於n的質數的個數,題目中給了充足的提示,解題方法就在第二個提示 埃拉托斯特尼篩法 Sieve of Eratosthenes 中,這個算法的過程如下圖所示:

 

 

我們從2開始遍歷到根號n,先找到第一個質數2,然后將其所有的倍數全部標記出來,然后到下一個質數3,標記其所有倍數,一次類推,直到根號n,此時數組中未被標記的數字就是質數。我們需要一個 n-1 長度的 bool 型數組來記錄每個數字是否被標記,長度為 n-1 的原因是題目說是小於n的質數個數,並不包括n。 然后來實現埃拉托斯特尼篩法,難度並不是很大,代碼如下所示:

  

class Solution {
public:
    int countPrimes(int n) {
        int res = 0;
        vector<bool> prime(n, true);
        for (int i = 2; i < n; ++i) {
            if (!prime[i]) continue;
            ++res;
            for (int j = 2; i * j < n; ++j) {
                prime[i * j] = false;
            }
        }
        return res;
    }
};

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/204

 

類似題目:

Ugly Number II

Ugly Number

Perfect Squares

 

參考資料:

https://leetcode.com/problems/count-primes/

https://leetcode.com/problems/count-primes/discuss/57588/My-simple-Java-solution

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM