Count the number of prime numbers less than anon-negative number, n.
翻译:找出不打于n的所有非负数的素数。
分析:素数是只能被1和自己整数的数。一般常规方法运行都会超时,这里有一种方式解决,设置一个标记位,直 接将n的所有可能的非素数标记出来,这样的时间复杂度是线性的。代码如下:
public class Solution {
public int countPrimes(int n) {
boolean[] flag=new boolean[n];
intcount=0;
for(inti=2;i<n;i++){
if(flag[i]==false)
count++;
for(intj=2;i*j<n;j++)
flag[i*j]=true;
}
returncount;
}
}