用Python解答ProjectEuler問題(3)

阿債發表於2010-04-22
E003

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

求600851475143的最大質因子。

今天重寫了求素數的方法

# -*- coding:utf-8 -*-

class Prime:
    primes = [2]

    def __init__(self, maxpri):
        self.expandList(maxpri)

    def testNumber(self, x):
        """
        根據已知素數表用篩法進行測試x
        """
        assert type(1)==type(x) #x必須是整數
        if x<2:
            return False
        isPri = True
        for p in self.primes:
            if p*p>x: #只需測試被sqrt(x)以內的素數整除
                break
            elif 0==x%p: #是合數
                isPri = False
                break
        return isPri

    def expandList(self, maxpri, length=None):
        """
        擴充套件素數表到接近maxpri,或個數達到length
        """
        x = self.primes[-1]
        while (True):
            x += 1
            if self.testNumber(x):
                # Python中改寫類成員需要用self.__class__.引用
                self.__class__.primes.append(x)
            #是否達到目標並退出
            if maxpri and x>=maxpri:
                break
            if length and len(self.primes)>=length:
                break


if __name__ == `__main__`:
    max = 100    
    pri = Prime(max*max)
    print str(pri.primes)

有了上面求素數的程式碼,現在我們可以這樣解決問題

from prime import Prime
from math import sqrt, floor

def problem3(number):
    lmt = floor(sqrt(number))
    factor = 0
    pri = Prime(lmt)
    for p in pri.primes:
        if 0==number%p:
            factor = p
    return factor

if __name__ == `__main__`:
    print str(problem3(600851475143))


相關文章