LeetCode C++ 204. Count Primes【Math/Hash Table】簡單
Count the number of prime numbers less than a non-negative number, n
.
Example 1:
Input: n = 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
Example 2:
Input: n = 0
Output: 0
Example 3:
Input: n = 1
Output: 0
Constraints: 0 <= n <= 5 * 10^6
題意:統計所有小於非負整數 n
的質數的數量。
解法 埃利特斯拉篩法
普通的埃式篩法:
class Solution {
public:
int countPrimes(int n) { //埃利特斯拉篩法
if (n <= 1) return 0;
int cnt = 0;
const int maxn = 5 * 1e6;
bitset<maxn> bst;
for (int i = 2; i < n; ++i) {
if (bst[i] == 0) {
++cnt;
for (int j = i + i; j < n; j += i) bst[j] = 1;
}
}
return cnt;
}
};
執行效率如下:
執行用時:184 ms, 在所有 C++ 提交中擊敗了69.29% 的使用者
記憶體消耗:7 MB, 在所有 C++ 提交中擊敗了32.00% 的使用者
優化的埃式篩法:
class Solution {
public:
int countPrimes(int n) {
if (n <= 1) return 0;
int cnt = 0;
const int maxn = 5 * 1e6;
bitset<maxn> bst;
for (int i = 2; i * i < n; ++i)
if (bst[i] == 0)
for (int j = i * i; j < n; j += i) bst[j] = 1;
for (int i = 2; i < n; ++i)
if (bst[i] == false) ++cnt;
return cnt;
}
};
執行效率如下:
執行用時:164 ms, 在所有 C++ 提交中擊敗了70.36% 的使用者
記憶體消耗:6.9 MB, 在所有 C++ 提交中擊敗了32.18% 的使用者
相關文章
- LeetCode筆記:204. Count PrimesLeetCode筆記
- LeetCode-Count PrimesLeetCode
- leetcode刷題--Count PrimesLeetCode
- LeetCode C++ 387. First Unique Character in a String【String/Hash Table】簡單LeetCodeC++
- LeetCode C++ 441. Arranging Coins【Math/Binary Search】簡單LeetCodeC++
- 一致性hash的c++簡單實現C++
- [LintCode/LeetCode] Check Sum of K PrimesLeetCode
- Random和Math.random()簡單總結random
- Leetcode Count and SayLeetCode
- LeetCode:Count and SayLeetCode
- Hash破解神器:Hashcat的簡單使用
- C語言實現一個簡易的Hash table(7)C語言
- Leetcode 38 Count and SayLeetCode
- LeetCode-Count BitsLeetCode
- Leetcode-Count and SayLeetCode
- Count and Say leetcode javaLeetCodeJava
- 資料庫表--hash clustered table資料庫
- C++簡單vectorC++
- LeetCode-Count Univalue SubtreesLeetCode
- LeetCode-Count of Range SumLeetCode
- leetcode刷題--Count and SayLeetCode
- hdu 4287Intelligent IME(簡單hash)Intel
- 資料庫表--sorted hash clustered table資料庫
- add hash partition , default tablespace for patitioned table
- 簡單理解C++引用C++
- LeetCode C++ 1464. Maximum Product of Two Elements in an Array【Array/Sort】簡單LeetCodeC++
- LeetCode C++ 703. Kth Largest Element in a Stream【Heap/Design】簡單LeetCodeC++
- 【Leetcode】1395. Count Number of TeamsLeetCode
- SPOJ PGCD - Primes in GCD Table (好題! 莫比烏斯反演+分塊求和優化)GC優化
- 【五】ODB - C++ 表單列函式count、min、max(V1.0)C++函式
- el-table 的 el-table-column 的key使用Math.random() 篩選列random
- C++ - 簡單工廠模式C++模式
- Math ActivityMaker Skills v2.20註冊演算法(簡單)演算法
- LeetCode-Count Complete Tree NodesLeetCode
- LeetCode- Count Numbers with Unique DigitsLeetCodeGit
- 【LeetCode】簡單題目集LeetCode
- Sonnet Primes in PythonPython
- javascript獲取字串的hash值簡單程式碼例項JavaScript字串