mirror of
https://github.com/labuladong/fucking-algorithm.git
synced 2025-07-05 12:04:37 +08:00
寻找素数 提供 Python3 解法
This commit is contained in:
@ -150,6 +150,29 @@ int countPrimes(int n) {
|
||||
|
||||

|
||||
|
||||
[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)
|
||||
|
Reference in New Issue
Block a user