当前位置:网站首页>204. Count Primes
204. Count Primes
2022-08-09 07:57:00 【scwMason】
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
就是寻找比n小的素数有多少个
这里我们用了素数筛的方法,将时间复杂度降到线性时间,素数筛基本思想就是一个素数的倍数一定不是素数
易懂版本:
class Solution:
def countPrimes(self, n: int) -> int:
ispri=[0,0]+[1]*(n-2)
if n==0 or n==1:
return 0
for i in range(2,int(n**0.5)+1):
if ispri[i]:
for j in range(i*i,n,i):
ispri[j]=0
return sum(ispri)
巧用list运算符,结果稍许提高了一些运算时间
def countPrimes(self, n: int) -> int:
ispri=[0,0]+[1]*(n-2)
if n==0 or n==1:
return 0
for i in range(2,int(n**0.5)+1):
if ispri[i]:
ispri[i**2::i]=[0]*(len(ispri[i**2::i]))
return sum(ispri)
边栏推荐
猜你喜欢
随机推荐
3D软件开发工具HOOPS全套产品开发介绍 | HOOPS Exchange、HOOPS Communicator
SiamFC:用于目标跟踪的全卷积孪生网络 fully-convolutional siamese networks for object tracking
Four departments including the Ministry of Industry and Information Technology promote green smart home products to the countryside
Shell编程之正则表达式
3安装及管理程序
C语言笔记 学习预处理 学习宏定义
【机器学习】降维代码练习
App测试
.net(一)WebService创建
毕业我选择了保家卫国,退伍我选择了华为外包
Record a failure to upgrade the client's APP database version number
Set集合
【机器学习】随机森林、GBDT、XGBoost、LightGBM等集成学习代码练习
[STL]stack与queue
db2数据库备份恢复问题
引导过程与服务控制
如何把无用的代码注释为 Deprecated 弃用
接口测试概念
信息反馈平台的设计与实现(一、项目设计)
Solidworks 2022 Inspection新增功能:光学字符识别、可自定义的检查报告