Count the number of prime numbers less than a non-negative number n.
埃拉托斯特尼筛法:
首先使所有数都为prime(true),循环所有数,使此数平方以后的所有此数的倍数都为false
class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
isPrime = [True] * max(n, 2)
isPrime[0], isPrime[1] = False, False
x = 2
while x*x < n:
if isPrime[x]:
p = x*x
while p < n:
isPrime[p] = False
p += x
x += 1
return sum(isPrime)