LeetCode C++ 204. Count Primes【Math/Hash Table】简单

95 篇文章 3 订阅
52 篇文章 1 订阅

Count the number of prime numbers less than a non-negative number, n.

Example 1:

Input: n = 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.

Example 2:

Input: n = 0
Output: 0

Example 3:

Input: n = 1
Output: 0

Constraints: 0 <= n <= 5 * 10^6

题意:统计所有小于非负整数 n 的质数的数量。


解法 埃利特斯拉筛法

普通的埃式筛法:

class Solution {
public:
    int countPrimes(int n) { //埃利特斯拉筛法
        if (n <= 1) return 0;
        int cnt = 0;
        const int maxn = 5 * 1e6;
        bitset<maxn> bst;
        for (int i = 2; i < n; ++i) {
            if (bst[i] == 0) {
                ++cnt;
                for (int j = i + i; j < n; j += i) bst[j] = 1;
            }
        }
        return cnt;
    }
};

运行效率如下:

执行用时:184 ms, 在所有 C++ 提交中击败了69.29% 的用户
内存消耗:7 MB, 在所有 C++ 提交中击败了32.00% 的用户

优化的埃式筛法:

class Solution {
public:
    int countPrimes(int n) {
        if (n <= 1) return 0;
        int cnt = 0;
        const int maxn = 5 * 1e6;
        bitset<maxn> bst;
        for (int i = 2; i * i < n; ++i) 
            if (bst[i] == 0) 
                for (int j = i * i; j < n; j += i) bst[j] = 1;
        for (int i = 2; i < n; ++i) 
            if (bst[i] == false) ++cnt;
        return cnt;
    }
};

运行效率如下:

执行用时:164 ms, 在所有 C++ 提交中击败了70.36% 的用户
内存消耗:6.9 MB, 在所有 C++ 提交中击败了32.18% 的用户
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

memcpy0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值