【发布时间】:2014-03-01 12:02:08
【问题描述】:
#!/usr/bin/python
import sys,math
n = input("enter a number to find the factors : ")
j,flag,b= 0l,False,0l
for b in xrange(1,n+1):
a = n + (b*b)
j = long(math.sqrt(a))
if a == j*j:
flag = True
break
if flag:
c = j+b
d = j-b
print "the first factor is : ",c ," and the second factor is : ",d
当我运行这段代码时,它会针对不同的输入抛出不同类型的错误。
以下是一种输入
linux@terminal:~$ ./fermat.py
enter a number to find the factors : 544564564545456
Traceback (most recent call last):
File "./fermat.py", line 8, in <module>
for b in range(1,n+1):
MemoryError
这是第二次输入
linux@terminal:~$ ./fermat.py
enter a number to find the factors : 28888888888888888888888888888888888444444444444444444444444
Traceback (most recent call last):
File "./fermat.py", line 8, in <module>
for b in range(1,n+1):
OverflowError: range() result has too many items
这是第三个输出
linux@terminal:~$ ./fermat.py
enter a number to find the factors : 28888888888888888888888888888888888444444444444444444444444
Traceback (most recent call last):
File "./fermat.py", line 8, in <module>
for b in xrange(1,n+1):
OverflowError: Python int too large to convert to C long
实际上,我正在编写费马因式分解的代码,以找到给定数字的因数。我的要求是,即使输入一百位数字,它也应该给出该输入数字的输出。
有什么办法可以摆脱这种问题吗? 我正在使用 Ubuntu 和 python 2.7.5+
【问题讨论】:
-
您的前两个回溯是针对您未发布的代码;您使用的是
range()而不是xrange(),从而生成了包含太多元素的列表。在任何情况下,您都不应该尝试为此类 巨大 因素生成循环。您的代码永远不会在任何合理的时间内完成无论如何。 -
在Fermat's factorization algorithm 中,您认为首先需要创建这样的循环吗?
-
您不能对偶数使用费马因式分解。
标签: python python-2.7