寫在前面
題目詳情
統計所有小於非負整數 n 的質數的數量。
示例:
輸入: 10
輸出: 4
解釋: 小於 10 的質數一共有 4 個, 它們是 2, 3, 5, 7 。
ac代碼
class Solution
{
public:
int countPrimes(int n)
{
int cnt = 0;
for(int i=2; i<n; i++)
if(isPrime(i))
cnt++;
return cnt;
}
bool isPrime(int n)
{
if(n==2 || n==3)
return true;
for(int i=2; i*i<=n; i++)
if(n%i==0)
return false;
return true;
}
};
- 空間換時間
- 判斷非質數組,統一計數
vector<int>
數組初始化
count(res.begin(), res.end(), 1)
計算數組中目標值個數
class Solution {
public:
int countPrimes(int n) {
if(n < 3) return 0;
vector<int> res(n, 1);
res[0] = 0;
res[1] = 0;
for(int i = 2; i < sqrt(n); ++i){
if(res[i] != 1)
continue;
for(int j = i*2; j < n; j += i){
res[j] = 0;
}
}
int num = count(res.begin(), res.end(), 1);
return num;
}
};