算法思路:用质数筛选算法:The Sieve of Eratosthenes
class Solution(object):
def countPrimes(self, n):
flag_list = [1] * n # 1代表素数;0代表非素数
count = 0
for i in range(2, n): # 最小的素数为2
if flag_list[i]:
count += 1
for j in range(i*i, n, i): #从i*i开始就好了,不用从i开始,这样子就重复计算了
flag_list[j] = 0 #将是i的倍数的,都是非素数,都设置为0
return count
# def countPrimes(self, n): # time exceeded
# """
# :type n: int
# :rtype: int
# """
# count = 0
# for i in range(1, n):
# if self.is_prime(i):
# # print(i)
# count += 1
# return count
# def is_prime(self, a):
# if a == 1:
# return False
# for i in range(2, int(math.sqrt(a)+1)):
# if a % i == 0:
# return False
# return True