题目:
统计所有小于非负整数 n 的质数的数量。
示例:
输入: 10
输出: 4
解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。
代码:
/**
* @作者:dhc
* @创建时间:13:39 2018/8/1
* @描述:204.计数质数
*/
public class TwoHundredAndFour {
//埃氏筛法:对于一个序列,求这个序列的质数,先将所有数标记为质数,从2开始取出第一个质数,
// 然后将这个取出数的所有倍数标记为非质数。这样依次取出的数就是质数
public static int countPrimes(int n) {
int count = 0;
boolean [] list = new boolean[n];
for(int i = 0;i < n;i++){
list[i] = true;
}
for(int i = 2;i < n;i++){
if(list[i]){
count++;
int tem = 2;
//在这里开始也是想循环到n,然后判读是否是i的倍数,结果超时,因此用如下办法来标记
// 。这里也可以用j=j+i;
for(int j = i*tem;j<n;j = i*tem){
tem++;
list[j] = false;
}
}
}
return count;
}
//依次判断从1到n的每一个数,判断每一个数再用一个循环判断这个数是否是质数,这里不用循环到这个数
//只需要循环到这个数的平方根
/*public static int countPrimes(int n) {
int count = 0;
if(n < 2){
return 0;
}
out:for(int i = 2;i < n;i++){
for(int j = 2;j<=(int)Math.sqrt(i);j++){
if(i%j==0){
continue out;
}
}
count++;
}
return count;
}*/
public static void main(String[] args) {
System.out.println(countPrimes(10));
}
}