问题
统计所有小于非负整数 n 的质数的数量。
例子
思路
-
方法1
质数的所有倍数都不是质数
-
方法2
代码
//方法1
class Solution {
public int countPrimes(int n) {
int[] arr = new int[n];
Arrays.fill(arr,1);
for(int i=2; i<n; i++) {
if(arr[i]==1){
for(int j=2*i; j<n; j+=i)
arr[j]=0;
}
}
int res = 0;
for(int i=2; i<n; i++) {
res+=arr[i];
}
return res;
}
}
//方法2