classSolution: defcountPrimes(self, n: int) -> int: data = set(range(2, n)) primes = set() while data: t = data.pop() primes.add(t) if t ** 2 > n: break for i inrange(2, n // t + 1): try: data.remove(i * t) except: pass returnlen(primes) + len(data)
用list来写:
1 2 3 4 5 6 7 8 9 10
classSolution: defcountPrimes(self, n: int) -> int: if n <= 2: return0 l = [1] * n # l为记录1至n-1是否为质数的列表 l[0] = l[1] = 0# 0和1不是质数 for i inrange(2, int(n ** 0.5) + 1): if l[i] == 1: # 若i为质数 l[2*i:n:i] = [0] * ((n - i - 1) // i) # i的整数倍都不是质数 returnsum(l)