统计所有小于非负整数 n 的质数的数量。
示例:
输入: 10
输出: 4
解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。
创建一个容器: bool[] nonPrime = new bool[n]; 全部为false
通过计算更改 nonPrime 为true
查询true的数量
public class Solution {
public int CountPrimes(int n) {
if(n < 2) return 0;
bool[] nonPrime = new bool[n];
for(int i = 2; i <= Math.Sqrt(n); i++)
if(!nonPrime[i-1])
for(int j = i * i; j <= n; j += i)
nonPrime[j-1] = true;
int result = 0;
for(int k = 2; k < n; k++)
result += nonPrime[k-1] ? 0 : 1;
return result;
}
}