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

understanding


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



down vote accepted


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

n = a*b

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




使用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)