当前位置:网站首页>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)边栏推荐
猜你喜欢
随机推荐
Shell编程之正则表达式
Anaconda replaces the default virtual environment
LeetCode·每日一题·761.特殊的二进制序列·分治
Redis(八)集群
Exclude null values when Oracle limits
Record a failure to upgrade the client's APP database version number
3D软件开发工具HOOPS全套产品开发介绍 | HOOPS Exchange、HOOPS Communicator
动态设置img标签图片失效问题
.net(一)WebService创建
.net(五) 业务层实现
JS基础1
web基本概念
HOOPS助力 SolidWorks edrawings 引入AR/VR技术
897. Increasing Order Search Tree
SSM integration development case
SSM整合开发案例
LeetCode: 876. The middle node of the linked list —— simple
NAT地址转换的原理与配置
Apache POI
权限(下)





![[STL]vector](/img/0b/89231ee7ddf3b80cc305b2a7b48108.png)



