204. 计数质数
https://leetcode-cn.com/problems/count-primes/
解法一:暴力(超时)
遍历从2到n的所有数,每次用一个质数检测函数检验。检测原理是看n能否整除2到n,只要有一个,n就不是质数,实际上只用检测2到√n即可,因为n以内的素数不会超过√n。
class Solution:
def countPrimes(self, n: int) -> int:
count = 0
for i in range(2, n):
if self.isPrime(i):
count += 1
return count
#检验是否为质数
def isPrime(self, n):
i = 2
#实际上检测能否整除[2, √n]范围即可
#用乘法代替开平方函数,提高速度
while i ** 2 <= n:
if n % i == 0:
return False
i += 1
return True解法二:埃拉托斯特尼筛法
伪代码,摘自维基百科:
其实用sqrt速度也差不多,还简洁:
最后更新于