排除法。
题目:
204. 计数质数
统计所有小于非负整数 n 的质数的数量。
示例:
输入: 10
输出: 4
解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。
code:
class Solution:
def countPrimes(self, n: int) -> int:
if n<=1: return 0
res = defaultdict(int)
for i in range(2,n):
t = i
temp = i*t
while temp < n:
res[temp] += 1
t+=1
temp = i*t
return n-len(res)-2
好了。