LeetCode.204.Count Primes

原題鏈接:Count Primes

題目內容:
Description:

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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

統計小於n的所有質數的數量,其中n是非負數


Python.01

易知:

  • 所有的質數除了1和它本身以外不再有其他因數。
  • 一個數n,若小於√n的數中沒有除了1以外的因數,那麼大於√n的數中也沒有。
  • 類似篩選法的思想,從已知的質數序列中取數字作爲因數驗證當前的數字是否爲質數。
class Solution(object):
    def countPrimes(self, n):
        """
        :type n: int
        :rtype: int
        """
        primes = list([2])

        def check_primes(cp, primes):
            for i in primes:
                if cp % i == 0 and i * i <= cp:
                    return False
            return True

        for j in range(2, n):
            if check_primes(j, primes):
                primes.append(j)
        return len(primes) - 1

這個方法會重複驗證2,所以最後的長度-1
雖然結果正確,但是會超時。

Python.02

class Solution(object):
    def countPrimes(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n < 2:
            return 0
        primes = [True for i in range(1,n)]
        primes[0] = False
        i = 2
        count = 0
        while i*i < n:
            if primes[i-1]:
                for j in range(i*i, n, i):
                    primes[j-1] = False
            i += 1  
        for num in primes:
            if num:
                count += 1
        return count
  • 需要注意的一點是0,1的處理,題目中指出是非負數。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章