跟着专注于计算机视觉的AndyJ的妈妈我学算法之每日一题leetcode204计数质数

排除法。
题目:

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

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

code:

class Solution:
    def countPrimes(self, n: int) -> int:
        if n<=1: return 0
        res = defaultdict(int)
        for i in range(2,n):
            t = i
            temp = i*t
            while temp < n:
                res[temp] += 1
                t+=1
                temp = i*t
        return n-len(res)-2

好了。

猜你喜欢

转载自blog.csdn.net/mianjiong2855/article/details/107762790