Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 求一个数的素因子_Python_Prime Factoring - Fatal编程技术网

Python 求一个数的素因子

Python 求一个数的素因子,python,prime-factoring,Python,Prime Factoring,我试图找到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

我试图找到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
这不会复制列表-
素数
与除数

所以当你这么做的时候

primes.remove(elements)
这与:

divisors.remove(elements)

元素会把迭代搞得一团糟,这就是它似乎会跳过的原因。

它会跳过下一个元素,因为一旦删除一个元素,后面每个元素的索引都会减少一个。我会尝试在
素数之后递减
a
。删除(元素)

问题是您正在从列表中删除元素,而该列表同时被迭代。它将中断迭代

你可以这样做

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

非常感谢。工作得很好!