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

74HC595芯片引脚说明

SA-Siam:用于实时目标跟踪的双重连体网络A Twofold Siamese Network for Real-Time Object Tracking

MDK Keil debug时, watch1中全局变量不更新

账户和权限管理2

9.进程和计划任务管理(1)

C language: detailed explanation of soda bottle
一文搞懂 条件编译和预处理指令 #define、#undef、#ifdef、#ifndef、#if、#elif、#else、#endif、defined 详解

不同风格的Flask-restful

LeetCode·每日一题·636.函数的独占时间·栈模拟

如何把无用的代码注释为 Deprecated 弃用
随机推荐
EXCEL使用函数联调(find,mid,vlookup,xlookup)
配置本地yum源仓库
包子凑数----欧几里得+dp
C语言:调整奇数偶数顺序
pytorch指定GPU
Anaconda 更换默认虚拟环境
prepareStatement的使用
“互联网+”大学生创新创业大赛经历
三层交换机原理及配置
Four departments including the Ministry of Industry and Information Technology promote green smart home products to the countryside
3D软件开发工具HOOPS全套产品开发介绍 | HOOPS Exchange、HOOPS Communicator
安全的Md5加密:两次加密(加盐)
定时任务组件Quartz
Oracle 限制时将空值排除
动态设置img标签图片失效问题
Non-decreasing Array
Shell之函数与数组
C语言:打印菱形
【机器学习】支持向量机(SVM)代码练习
JS基础1