1. 题目
统计所有小于非负整数 n 的质数的数量。
2. 示例
输入: 10 输出: 4 解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。
3. 解答
python3 超出时间限制
只需要对n**0.5的数进行遍历。
import math class Solution: def countPrimes(self, n): """ :type n: int :rtype: int """ if n <= 2: return 0 count = 1 for i in range(2, n): s = math.ceil(math.sqrt(i)) pos = True for j in range(2, s+1): if i%j == 0: pos = False break if pos: count += 1 return count solution = Solution() c = solution.countPrimes(20)
4. 优答
python3 使用厄拉多塞筛法算法。理论讲解参考博客:https://blog.csdn.net/github_39261590/article/details/73864039
很巧妙的转换方法。
别人的解答1
class Solution(object): def countPrimes(self, n): isPrime = [True] * max(n, 2) isPrime[0], isPrime[1] = False, False x = 2 while x * x < n: if isPrime[x]: p = x * x while p < n: isPrime[p] = False p += x x += 1 return sum(isPrime)
别人的解答2
def countPrimes(self, n): if n < 3: return 0 primes = [True] * n primes[0] = primes[1] = False for i in range(2, int(n ** 0.5) + 1): if primes[i]: primes[i * i: n: i] = [False] * len(primes[i * i: n: i]) return sum(primes)