当前位置:网站首页>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)
边栏推荐
猜你喜欢

Laravel文档阅读笔记-Rendering JSON(对JS变量进行赋值)

C语言:调整奇数偶数顺序

Four departments including the Ministry of Industry and Information Technology promote green smart home products to the countryside

SSM integration development case
![[STL]string](/img/25/c53cac1993809266f91662633ecb86.png)
[STL]string

C language: reverse character order

Use tensorflow.keras to build a neural network model modularly

RestFul,会话技术,Fiddler

弹性盒样式、移动端、VW适配、响应式布局

(三)、时间序列预测
随机推荐
三层交换机原理及配置
C language: adjust the order of odd and even numbers
CoCube传感器MPU6050笔记
一站制造项目及Spark核心面试 ,220808,,,
App测试
网络层协议介绍
LeetCode: 876. The middle node of the linked list —— simple
SiamFC:用于目标跟踪的全卷积孪生网络 fully-convolutional siamese networks for object tracking
libtorch示例
静态路由的原理与配置
动态设置img标签图片失效问题
接口测试概念
C language: reverse character order
H3C_利用策略路由实现出口双线路负载(选路)的部署
Kotlin协程 - 异常处理
.net(一)WebService创建
3安装及管理程序
Pytorch中 nn.BatchNorm2d() 归一化操作
C语言:字符逆序
[STL]list