From 3a7228da50cc974d4b82c032fe22f833d1c035c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BD=95=E7=9D=BF?= Date: Mon, 22 Jun 2020 08:23:26 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AF=BB=E6=89=BE=E7=B4=A0=E6=95=B0=20?= =?UTF-8?q?=E6=8F=90=E4=BE=9B=20Python3=20=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...23\345\215\260\347\264\240\346\225\260.md" | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git "a/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\346\211\223\345\215\260\347\264\240\346\225\260.md" "b/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\346\211\223\345\215\260\347\264\240\346\225\260.md" index 1ded2a7..11420b4 100644 --- "a/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\346\211\223\345\215\260\347\264\240\346\225\260.md" +++ "b/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\346\211\223\345\215\260\347\264\240\346\225\260.md" @@ -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) -- GitLab