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-08-07
  • 2021-10-24
  • 2021-06-16
  • 2021-11-23
  • 2021-11-26
  • 2021-09-15
猜你喜欢
  • 2021-08-14
  • 2021-09-07
  • 2021-07-19
  • 2021-05-04
  • 2022-02-05
相关资源
相似解决方案