[leetcode]python3 算法攻略-计数质数

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

方案一:厄拉多塞筛法   参考:https://blog.csdn.net/github_39261590/article/details/73864039

class Solution(object):
    def countPrimes(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n < 3:
            return 0
        res = [True] * n
        res[0] = res[1] = False
        for i in range(2, int(n**0.5) + 1):
            if res[i]:
                res[i * i: n: i] = [False] * len(res[i * i: n: i])
        return sum(res)

方案二:一般遍历法,超时

class Solution(object):
    def countPrimes(self, n):
        """
        :type n: int
        :rtype: int
        """
        def isPrimes(n):
            if n == 1:
                return False            
            for i in range(2, int(n**0.5) + 1):
                if n % i == 0:
                    return False
            return True
        count = 0
        for i in range(1, n):
            if isPrimes(i):
                count += 1
        return count

猜你喜欢

转载自blog.csdn.net/zhenghaitian/article/details/81141111