leetcode之Count Primes(204)

题目:

统计所有小于非负整数 的质数的数量。

示例:

输入: 10
输出: 4
解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。

python代码:

class Solution:
    def countPrimes(self, n):
        if n < 3:
            return 0
        res = [1] * n
        res[0] = res[1] = 0
        for i in range(2, int(n**0.5)+1):
            for j in range(2*i, n, i):
                res[j] = 0
        return sum(res)
                

心得:此种方法即素数筛选法,简单高效,关于素数筛选法可以点击这里查看。

猜你喜欢

转载自blog.csdn.net/cuicheng01/article/details/82559481