简体   繁体   English

寻找数字的素因子

[英]Finding prime factors of a number

I'm trying to find the largest prime factor of 13195: 我想找到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

Here's what I get as output: 这是我得到的输出:

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

So it works well for the first four primes, but once it starts removing numbers that aren't primes, the code seems to skip checking the next element in the divisors list, and continues moving on. 所以它适用于前四个素数,但一旦它开始删除不是素数的数字,代码似乎跳过检查除数列表中的下一个元素,并继续前进。 Why does it do this? 为什么这样做?

The important line is: 重要的是:

primes = divisors

This does not copy the list - primes is the same list as divisors 这不会复制列表 - primesdivisors相同

So when you do 所以,当你这样做

primes.remove(elements)

It is the same as: 它与:

divisors.remove(elements)

The messes up the iteration through elements, which is why it seems to skip. 通过元素弄乱迭代,这就是为什么它似乎跳过了。

It's skipping the next element because once you remove an element, the index of each following element is reduced by one. 它正在跳过下一个元素,因为一旦删除元素,每个后续元素的索引将减少一个。 I would try decrementing a after primes.remove(elements) 我会尝试递减a primes.remove(elements)

The problem is that you are removing elements from the list that is at the same time being iterated over. 问题是您要从列表中删除同时进行迭代的元素。 It will break the iteration. 它会破坏迭代。

You could instead do 你可以改为做

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