寻找素数 提供 Python3 解法

This commit is contained in:
何睿
2020-06-22 08:23:26 +08:00
committed by labuladong
parent 98119ae724
commit 3a7228da50

View File

@ -150,6 +150,29 @@ int countPrimes(int n) {
![labuladong](../pictures/labuladong.png)
[ruicore](https://github.com/ruicore/algorithm) 提供 Python3 代码:
```py
class Solution:
def countPrimes(self, n: int):
# 前 2 个数不是素数
if n < 3:
return 0
# isprime 数组
isprime = [1] * n
for i in range(2, int(n ** 0.5) + 1):
if isprime[i]:
# 从 i*i包括自己 到 n不包括n每步增加 i 的所有数的个数
tmp = ((n - 1 - i * i) // i + 1)
# 这种方式赋值比用 for 循环更高效
isprime[i * i: n: i] = [0] * tmp
# 前 2 个数不是素数,去掉
count = sum(isprime[2:])
return count
```
[上一篇如何实现LRU算法](../高频面试系列/LRU算法.md)
[下一篇:如何计算编辑距离](../动态规划系列/编辑距离.md)