提交 3a7228da 编写于 作者: 何睿 提交者: labuladong

寻找素数 提供 Python3 解法

上级 98119ae7
......@@ -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)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册