繁体   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