File tree Expand file tree Collapse file tree 1 file changed +23
-0
lines changed Expand file tree Collapse file tree 1 file changed +23
-0
lines changed Original file line number Diff line number Diff line change @@ -150,6 +150,29 @@ int countPrimes(int n) {
150150
151151![ labuladong] ( ../pictures/labuladong.png )
152152
153+ [ ruicore] ( https://github.com/ruicore/algorithm ) 提供 Python3 代码:
154+
155+ ``` py
156+ class Solution :
157+ def countPrimes (self , n : int ):
158+ # 前 2 个数不是素数
159+ if n < 3 :
160+ return 0
161+ # isprime 数组
162+ isprime = [1 ] * n
163+
164+ for i in range (2 , int (n ** 0.5 ) + 1 ):
165+ if isprime[i]:
166+ # 从 i*i(包括自己) 到 n(不包括n),每步增加 i 的所有数的个数
167+ tmp = ((n - 1 - i * i) // i + 1 )
168+ # 这种方式赋值比用 for 循环更高效
169+ isprime[i * i: n: i] = [0 ] * tmp
170+
171+ # 前 2 个数不是素数,去掉
172+ count = sum (isprime[2 :])
173+ return count
174+ ```
175+
153176[ 上一篇:如何实现LRU算法] ( ../高频面试系列/LRU算法.md )
154177
155178[ 下一篇:如何计算编辑距离] ( ../动态规划系列/编辑距离.md )
You can’t perform that action at this time.
0 commit comments