Description:
Count the number of prime numbers less than a non-negative number, n.
思路:
The Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers up to n.
埃拉托斯特尼筛法 (http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes)
1. Create a list of consecutive integers from 2 through n: (2, 3, 4, ..., n).
2. Initially, let p equal 2, the smallest prime number.
3. Starting from p, enumerate its multiples by counting to n in increments of p, and mark them in the list (these will be 2p, 3p, 4p, ... ; the p itself should not be marked).
4. Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this new number (which is the next prime), and repeat from step 3.
class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
isprime=[True]*max(n,2) #1~n先全部设定为true
isprime[0]=isprime[1]=False #1和2初始化为false
i=2
while i*i<n: #因n=i*j,且i<=j,则 i*i<span style="font-family: Arial, Helvetica, sans-serif;"><n</span>
if isprime[i]: #只需要check还不是false的i
p=i*i #比i小的部分i*1~i*(i-1)已经被check过了,所以直接判断i*i的
while p<n:
isprime[p]=False
p+=i #p+i
i+=1
return sum(isprime)