leetcode-python-计数质数

1)逐个判断,太慢了!

2)埃氏筛法,从2开始,1不是质数

class Solution:
    def countPrimes(self, n: int) -> int:
        isNumPrimes = [True] * n 
        count = 0  
        for i in range(2, n):
            if isNumPrimes[i]:
                count += 1
                # 使用埃拉托斯特尼 筛选法进行过滤 将合数去除
                for j in range(i*i, n, i): 
                    isNumPrimes[j] = False 
        return count

 

posted @ 2021-06-09 17:04  泊鸽  阅读(73)  评论(0)    收藏  举报