python leetcode-204 Count Primes 质数计数

博客介绍了如何使用 Python 解决 LeetCode 的第 204 题——质数计数。作者给出了三种解法,包括超时的 O(n^2) 解法、优化后的平方根解法以及埃拉托斯特尼筛法,并提到对于平方根解法,只需检查小于等于数的平方根即可避免超时。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

title: “leetcode-204 Count Primes 质数计数”
更多解法: https://zszdata.com/2019/03/09/count-primes/

3种解法输出都对,但是前两种超时。

Count Primes

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.
Solution:

1:

class Solution:
    def countPrimes(self, n: int) -> int:
        count = 0
        for i in range(2,n):
            for j in range(2,i):
                if i%j == 0:
                    break
            else:
                count += 1
        return count
        

This solution could work but time limit exceeded. Complexity of this solution is O(n2).超时了。

2:

如果一个数是合数,那么它的最小质因数肯定小于等于它的平方根。
因为如果最小质因数已经大于平方根了,那么大的质因数就要大于平方根,两个质因数相乘肯定大于这个数。所以只需要判断这个数是否能被小于其平方根的所有数整除。

    def countPrimes(self, n: int) -> int:
        if n <= 2:
            return 0
        else:
            res = 0
        for i in range(2, n):
            isPrime = 0
            for j in range(2, int(i**0.5)+1):
                if i%j ==0:
                    isPrime = 1
            if isPrime == 0:
                res += 1
        return res

还是超时了。。

3:

Eratosthenes 埃拉托斯特尼筛法
gif

  1. 是质数,同时划去所有2的倍数,接着查看剩下的数
  2. 是质数,同时划去所有3的倍数,接着查看剩下的数
  3. 一直进行到n的平方根(向上取整)。

sol2经验:只需要判断小于等于平方根的所有数

    def countPrimes(self, n: int) -> int:
        if n <= 2:
            return 0
        else:
            output = [1]*n
            output[0],output[1] = 0,0
            for i in range(2,int(n**0.5)+1):
                if output[i] == 1:
                    output[i*i:n:i] = [0]*len(output[i*i:n:i])
        return sum(output)
    

pic
pic

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值