1、暴力 超时
class Solution:
def countPrimes(self, n: int) -> int:
# 暴力,O(n*n^(1/2))
def IsPrimes(n):
for i in range(2,n//2+1):
if n%i == 0:
return False
return True
# 2以下无
if n <= 2 :
return 0
else:
count = 1
for i in range(3,n,2):
if IsPrimes(i):
count += 1
return count
class Solution:
def countPrimes(self, n: int) -> int:
# 只与质数匹配
def IsPrimes(n):
for num in m:
if n%num == 0:
return False
return True
# 2以下无
if n <= 2 :
return 0
else:
m = set()
for i in range(3,n,2):
if IsPrimes(i):
m.add(i)
return len(m)+1
2、标记,将所有当前质数的倍数做标记
class Solution:
def countPrimes(self, n: int) -> int:
# 空间换时间 将所有的质数的倍数标记为1
# 2以下无
if n <= 2 :
return 0
else:
m = [0 for i in range(n)]
count = 0
for i in range(2,n):
if m[i]==0:
count += 1
m[i] = 1
# 如果是当前质数的倍数,记录
for j in range(i*i,n,i):
m[j] = 1
return count