Description:
Count the number of prime numbers less than a non-negative number, n.
AC代码如下:
class Solution {
public:
int countPrimes(int n) {
int ret=0;
if(n<=2)
return ret;
else{
bool* primeArray=new bool[n];
primeArray[1]=false;
primeArray[2]=true;
ret++;
for(int i=3;i<n;i++)
primeArray[i]=i%2==0?false:true;
int i=3;
for(;i<=(int)sqrt(n);i++){
if(primeArray[i]){
ret++;
for(int j=i*i;j<n;j+=i)
primeArray[j]=false;
}
}
for(;i<n;i++)
if(primeArray[i])
ret++;
return ret;
}
}
};