1. 程式人生 > >LeetCode--Count Primes(素數個數)Python

LeetCode--Count Primes(素數個數)Python

題目:

計算n以內的素數個數。

解題思路:

1、首先考慮直接判斷n以內的每個數是否為素數。再對結果進行求和。判斷某個數是否為素數的方法,之間判斷該數能否整除從2到sqrt(n)的數字。若能則是素數,否則不是素數。複雜度為n*sqrt(n)。但在LeetCode會超時。

程式碼(Python):

class Solution(object):
    def countPrimes(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n==0:
            return 0
        
        def IsPrime(n):
            sqrt_n = int(n**0.5)
            for i in range(2,sqrt_n+1):
                if (n%i)==0:
                    return 0
            return 1
        
        count = 0
        
        for i in range(2,n):
            count+=IsPrime(i)
        
        return count

2、改變判斷某數是否為素數的方式,判斷該數能否整除從2到sqrt(n)的素數。在LeetCode也會超時
class Solution(object):
    def countPrimes(self, n):
        """
        :type n: int
        :rtype: int
        """
        Prime = []
        flag = 0
        for i in range(2,n):
            if Prime==[]:
                Prime.append(i)
                continue
            for j in range(len(Prime)):
                if Prime[j]*Prime[j]>i:
                    flag = 0
                    break
                if i%Prime[j]==0:
                    flag = 1
                    break

            if flag==1:
                flag = 0
                continue
            else:
                Prime.append(i)
        return len(Prime)

3、在網上查詢到的解題思路,降低了複雜度。厄拉多塞篩法。可以AC

連結:http://blog.csdn.net/github_39261590/article/details/73864039

程式碼(Python):

class Solution(object):
    def countPrimes(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n<2:
            return 0
        output = [True]*(n-1)
        output[0:1] = [False]*2
        sqrt_n = int(n**0.5+1)
        for i in range(sqrt_n):
            if output[i]:
                output[i*i:n:i]=[False]*len(output[i*i:n:i])
                
        return sum(output)