LeetCode 204. 计数质数 Count Primes

 厄拉多塞筛法

class Solution {
public:
    int countPrimes(int n) {
        int cnt = 0;
        vector<bool> signs(n, true);
        for (int i = 2; i < n; i++)
        {
            if (signs[i])
            {
                cnt++;
                for (int j = i; j < n; j+=i)  //排除非质数
                    signs[j] = false;
            }
        }
        return cnt;
    }
};

猜你喜欢

转载自www.cnblogs.com/ZSY-blog/p/12985541.html
今日推荐