质数的个数

计算小于n的素数个数

思路:

如果一个数m是素数,那么所有m * k就都不是素数。另外2是最小的素数

class Solution {
public:
    int countPrimes(int n) {
        vector<int> nums(n 1);
        int count{0};
        for(int i = 2; i < n; ++i) {
            if(nums[i]) {
                ++count;
                for(int j = 2; i * j < n; ++j) {
                    nums[i * j] = 0;
                }
            }
        }
        return count;
    }
};

猜你喜欢

转载自blog.csdn.net/u010325193/article/details/86501603