当前位置:网站首页>204. 数素数
204. 数素数
2022-08-09 08:02:00 【scwMason】
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10Output: 4Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
It is to find how many prime numbers are smaller than n
Here we use the method of prime number sieve to reduce the time complexity to linear time. The basic idea of prime number sieve is that a multiple of a prime number must not be a prime number
Easy to understand version:
class Solution:def countPrimes(self, n: int) -> int:ispri=[0,0]+[1]*(n-2)if n==0 or n==1:return 0for i in range(2,int(n**0.5)+1):if ispri[i]:for j in range(i*i,n,i):ispri[j]=0return sum(ispri)
Use the list operator skillfully, the result slightly improves the operation time
def countPrimes(self, n: int) -> int:ispri=[0,0]+[1]*(n-2)if n==0 or n==1:return 0for 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)
边栏推荐
猜你喜欢
火星人 --简单的数学题
Jmeter连接Mysql和Mysql编码问题
一文搞懂 条件编译和预处理指令 #define、#undef、#ifdef、#ifndef、#if、#elif、#else、#endif、defined 详解
SSM integration development case
BIM技术多牛逼?BIM技术在建筑工程行业的四大发展趋势
Solidworks 2022 Inspection新增功能:光学字符识别、可自定义的检查报告
【无标题】
3D软件开发工具HOOPS全套产品开发介绍 | HOOPS Exchange、HOOPS Communicator
PyTorch中 torch.nn与torch.nn.functional的区别
ncnn 推理猫狗识别
随机推荐
Exclude null values when Oracle limits
nvm安装以及管理多版本node教程
火星人 --简单的数学题
LeetCode:876. 链表的中间结点————简单
图像处理(一)图像基础
定时任务组件Quartz
[STL]vector
SSM整合开发案例
SOLIDWORKS 2022新功能直播揭秘!速来围观!
浅谈Endpoint
包子凑数----欧几里得+dp
3安装及管理程序
浅谈Flask_script
不同风格的Flask-restful
如何生成dll文件 采用VS2017生成dll文件(动态库文件)和lib文件(静态库文件)以C语言为例
引导过程与服务控制
EXCEL使用函数联调(find,mid,vlookup,xlookup)
转换为onnx模型错误汇总
LeetCode·每日一题·636.函数的独占时间·栈模拟
【无标题】