class Solution {
public:
int countPrimes(int n) {
if(n<=1) return 0;
int count=0;
int sqrt_n=sqrt(n);
bool flag[n]={0}; // set all the elements in the array to 0.
for(int i=2;i<=sqrt_n;i++){ //find the multiples of i and mark them by setting flag[ ] to TRUE
if(flag[i]==false){
for(int j=i*i;j<n;j+=i)
flag[j]=true;
}
}
for(int k=0;k<n;k++)// count primes
if(flag[k]==0) count++;
return count-2;// flag[1] and flag[0] are FALSE.
}
};
CINTA作业7
最新推荐文章于 2021-09-18 21:43:02 发布