LeetCode 204. Count Primes

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

Example:

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

解析:给出了一个非负数n,计算小于n的数里面素数的个数。

首先想到的是暴力法,遍历2到n然后挨个判断是否是素数。但是这样会超时。

看到网上的一种做法,我们从2开始遍历到根号n,先找到第一个质数2,然后将其所有的倍数全部标记出来,然后到下一个质数3,标记其所有倍数,一次类推,直到根号n,此时数组中未被标记的数字就是质数。称为埃拉托斯特尼筛法。

图形描述如下:

class Solution {
public:
    int countPrimes(int n) {
        int res = 0;
        vector<bool> prime(n, true);
        for(int i=2; i < n; i++)
        {
            if(!prime[i])
                continue;
            res ++;
            for(int j =2; i*j < n; j++)
                prime[i*j] = false;
        }
        return res;
    }
};

参考:https://www.cnblogs.com/grandyang/p/4462810.html

Add a Comment

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据