我有一个程序可以找到任意数 n 的质因数。运行它时,我收到一个索引错误,因为索引超出了限制(其中限制是 sqrt(n))。我不确定为什么它超过了限制。任何人都可以提供任何见解吗?
我的代码适用于大多数数字:
>>> pFactors(250000)
[2, 2, 2, 2, 5, 5, 5, 5, 5, 5]
>>> pFactors(123456789)
[3, 3, 3607, 3803]
>>> pFactors(123456)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
pFactors(123456)
File "D:\my_stuff\Google Drive\Modules\factors.py", line 50, in pFactors
check = primes[index]
IndexError: list index out of range
>>> pFactors(123455)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
pFactors(123455)
File "D:\my_stuff\Google Drive\Modules\factors.py", line 50, in pFactors
check = primes[index]
IndexError: list index out of range
奇怪的是,到目前为止,我只发现它无法用于数字 123400-1234
这是我的代码:
def pFactors(n):
import primes as p
from math import sqrt
global pFact
pFact, primes, limit, check, num, index = [], [], int(round(sqrt(n))), 2, n, 0
if type(n) != int and type(n) != long:
raise TypeError("Argument <n> can only be <type 'int'> or <type 'long'>")
else:
if p.isPrime(n):
pFact = [1, n]
else:
p.prevPrimes(limit)
for i in p.primes_dict:
if p.primes_dict[i]:
primes.append(i)
while check <= limit:
if check in primes and (num%check==0):
pFact.append(check)
num = num / check
if num in primes:
pFact.append(num)
break
else:
check = primes[index]
index += 1
return pFact
我确信问题不在于primes.py
,因为它工作正常。如果有人对如何解决此问题有任何解决方案,请告诉我。谢谢!