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

示例:

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


class Solution:
    def countPrimes(self, n):
        """
        :type n: int
        :rtype: int
        """
        isPrime = [1] * max(2, n)
        isPrime[0],isPrime[1]=False,False
        x = 2
        while x * x < n:
            if isPrime[x]:
                p = x * x
                while p < n:
                    isPrime[p] = 0
                    p += x
            x +=1
        return (sum(isPrime))

 

参考: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

收藏 打印