题目描述:
Description:
Count the number of prime numbers less than a non-negative number, n.
找到比n小的所有质数的个数
这里用wiki上的图来说,就很显然了。
比如n=52,那么就先让2的倍数全纪录下来,然后3的倍数,直到7的倍数,然后其他没有记录下来的就是质数了,加起来就行。
我知道这个方法后一开始用的hashset做,但是超时,后来换成数组,AC了。
原hashSet做法:
public int countPrimes(int n) {
int result=0;
Set<Integer> set=new HashSet<Integer>();
for(int i=2;i<Math.sqrt(n);i++){
for(int j=2;i*j<n;j++){
set.add(i*j);
}
}
for(int i=2;i<n;i++){
if(!set.contains(i)){
result++;
}
}
return result;
}
AC代码:
public int countPrimes(int n) {
int result=0;
boolean[] maps=new boolean[n-1];
for(int i=2;i<Math.sqrt(n);i++){
for(int j=2;i*j<n;j++){
maps[i*j-1]=true;
}
}
for(int i=1;i<n-1;i++){
if(!maps[i]){
result++;
}
}
return result;
}