簡體   English   中英

尋找數字的素因子

[英]Finding prime factors of a number

我想找到13195的最大素數因子:

def problem3():
    divisors = []
    primes = []
    num = 13195
    for a in range(2, num):
        if num % a == 0:
            divisors.append(a)
    print divisors #This is the list of all divisors of the number
    // At this point divisors looks like:
    // [5, 7, 13, 29, 35, 65, 91, 145, 203, 377, 455, 1015, 1885, 2639]

    print ""
    primes = divisors
    for elements in divisors:
        for a in range(2,elements):
            if elements % a == 0:
                primes.remove(elements)
                print divisors
                break
    print primes

這是我得到的輸出:

[5, 7, 13, 29, 65, 145, 377, 1015, 2639]

所以它適用於前四個素數,但一旦它開始刪除不是素數的數字,代碼似乎跳過檢查除數列表中的下一個元素,並繼續前進。 為什么這樣做?

重要的是:

primes = divisors

這不會復制列表 - primesdivisors相同

所以,當你這樣做

primes.remove(elements)

它與:

divisors.remove(elements)

通過元素弄亂迭代,這就是為什么它似乎跳過了。

它正在跳過下一個元素,因為一旦刪除元素,每個后續元素的索引將減少一個。 我會嘗試遞減a primes.remove(elements)

問題是您要從列表中刪除同時進行迭代的元素。 它會破壞迭代。

你可以改為做

for elements in divisors:
    isPrime = True
    for a in range(2,int(math.sqrt(elements) + 1)):
        if elements % a == 0:
            isPrime = False
            break
    if isPrime:
        primes.append(elements)
print primes

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM