质数统计查找 厄拉多塞筛

204. 计数质数

使用厄拉多塞筛法进行 1 到 64 的质数查找的过程如下:

 

 声明一个长度为最大限制数的布尔数组。用布尔值来区别筛选出的数和质数。

代码如下:

class Solution {
public:
    // //超时
    // int countPrimes(int n) {
    //     if(n == 0 || n == 1 || n==2) return 0;
    //     if(iszhishu(n-1))
    //     {
    //         return countPrimes(n-1)+1;
    //     }
    //     else return countPrimes(n-1);
    // }
    // bool iszhishu(int n)
    // {
    //     if(n==2) return true;
    //     for(int i=2; i<n; i++)
    //     {
    //         if(n%i == 0 ) return false;
    //     }
    //     return true;
    // }

  int countPrimes(int n) {
    int count = 0;
    //初始默认所有数为质数
    vector<bool> signs(n, true);
    for (int i = 2; i < n; i++) {
        if (signs[i]) {
            count++;
            for (int j = i + i; j < n; j += i) {
                //排除不是质数的数
                signs[j] = false;
            }
        }
    }
    return count;
  }
};

 

posted @ 2022-02-12 17:58  千寻slimg  阅读(39)  评论(0编辑  收藏  举报