当前位置:网站首页>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)
边栏推荐
猜你喜欢
随机推荐
Pytorch中 nn.BatchNorm2d() 归一化操作
.net(一)WebService创建
C语言:打印菱形
监视文本框的输入
3.MySQL插入数据, 读取数据、Where子句和Order By关键字
测试和开发之间的恩恩怨怨
[STL]stack与queue
记录一次客户的APP数据库版本号升级失败的情况
VOC format label to YOLO format
浅谈Flask_script
3D精彩案例,清软英泰建成综合轻量化显示平台!
网络层协议介绍
C: print the diamond
弹性盒样式、移动端、VW适配、响应式布局
CoCube传感器MPU6050笔记
包子凑数----欧几里得+dp
js数组相关知识复习
db2数据库备份恢复问题
LeetCode·每日一题·636.函数的独占时间·栈模拟
Win10电脑的WLAN消失的故事