leet204. Count Primes

题目:

Count the number of prime numbers less than a non-negative number, n.

分析:

  1. 对于小于3整数特殊处理
  2. 定义判断素数函数

代码:

class Solution(object):
    def countPrimes(self, n):
        """
        :type n: int
        :rtype: int
        """
        def isPrime(num):
            if num % 2 == 0:
                return 0
            n = 3
            while n ** 2 <= num:
                if num % n == 0:
                    return 0
                n += 2
            return 1
        if n <= 2:
            return 0
        i = 3
        counts = 1
        while i < n:
            counts += isPrime(i)
            i += 2
        return counts

思考:

  1. 以上代码是传统思维,在leetcode直接超时
  2. 使用排除法,不断计算sqrt(n)以内每个整数在n以内的k倍数,直接排除
  3. 未被排除的即为素数
  4. 别人的代码如下(来自leetcode中tusizi
class Solution:
# @param {integer} n
# @return {integer}
def countPrimes(self, n):
    if n < 3:
        return 0
    primes = [True] * n
    primes[0] = primes[1] = False
    for i in range(2, int(n ** 0.5) + 1):
        if primes[i]:
            primes[i * i: n: i] = [False] * len(primes[i * i: n: i])
    return sum(primes)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yzpwslc

您的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值