leetcode count prime

https://leetcode.com/problems/count-primes/

understanding


why 只需要遍历到sqrt(n).




down vote accepted

If a number n is not a prime, it can be factored into two factors a and b:

n = a*b

If both a and b were greater than the square root of na*b would be greater than n. So at least one of those factors must be less than or equal to the square root of n, and to check if n is prime, we only need to test for factors less than or equal to the square root.



使用sieve methods. 首先排除0和1,然后从2开始逐个做标记,令p = 2,然后从$p^2$开始scan,排除掉所有 p的倍数multiples. 然后p increase to the most recent one that not been marked. 这里直接在最外面的while循环里面加个if判断就行,不要在while里面多弄一个while


这里要注意都是从$p*p$开始,因为p*(p-1)的话,已经被p-1的p倍标记过了

mycode:

class Solution(object):
    def countPrimes(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n == 0 or n == 1:
            return 0
        
        
        p = 2
        flag = [1]* n
        flag[0] = flag[1] = 0
        while p*p < n:
            if flag[p] == 1:#直接在这里判断下一个p是什么
                i = p
                while i * p < n:
                    flag[i * p] = 0
                    i += 1
            p += 1
        
        return sum(flag)

自己重写code


class Solution(object):
    def countPrimes(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n < 2: return 0
        flag = [1]*n
        flag[0], flag[1] = 0, 0
        p = 2
        while p*p < n:
            if flag[p*p] == 1:
                i = p
                while p*i < n:
                    flag[p*i] = 0
                    i += 1
            p += 1
        return sum(flag)




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值