统计所有小于非负整数 n 的质数的数量。 示例: 输入: 10 输出: 4 解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7
class Solution:
def countPrimes(self, n: int) -> int:
import math
def Judge(num):
l = math.sqrt(num)
for i in range(3,int(l)+1,2):
if num%i==0:
return False
return True
if n<=2: return 0
if n==3: return 1
count = 2
for i in range(5,n,2):
if Judge(i):
count +=1
return count
# 思路:将有因子的数全部赋值=0
def countPrimes2(self, n: int) -> int:
if n<=2: return 0
isP = [1 for i in range(n)]
isP[0],isP[1] =0,0
for i in range(2,n):
j = i
while j*i <n:
isP[i*j] = 0
j +=1
return sum(isP)