问题描述
#!/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
当我运行这段代码时,它会针对不同的输入抛出不同类型的错误.
when I run this code it is throwing different types of errors for different inputs.
以下是一种输入
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
实际上,我正在编写费马分解的代码以找到给定数字的因数.我的要求是即使输入一百位数字,它也应该给出该输入数字的输出.
Actually I was writing code for Fermat factorization to find the factors of a given number. And my requirement is even if give a hundred digit number as input it should give the output for that input number.
有没有办法摆脱这种问题?我正在使用 Ubuntu 和 python 2.7.5+
Is there any way to get rid this kind of problem?I am using Ubuntu with python 2.7.5+
推荐答案
令人讨厌的是,在 Python 2 中,xrange
要求其参数适合 C long.标准库中没有完全替代品.但是,您并不完全需要直接替换.你只需要继续下去,直到循环 break
s.这意味着你想要 itertools.count
,这就像一个持续运行的 xrange
:
Annoyingly, in Python 2, xrange
requires its arguments to fit into a C long. There isn't quite a drop-in replacement in the standard library. However, you don't quite need a drop-in replacement. You just need to keep going until the loop break
s. That means you want itertools.count
, which is like an xrange
that just keeps going:
import itertools
for b in itertools.count(1):
...
另外,请注意您的代码还有其他错误.它尝试将费马分解应用于偶数,但费马分解不适用于偶数.此外,它没有考虑 n
是正方形的情况,因此它不适用于 n=9
.
Also, note that your code has other bugs. It attempts to apply Fermat factorization to even numbers, but Fermat factorization doesn't work on even numbers. Additionally, it fails to consider the case where n
is a square, so it won't work for n=9
.
这篇关于OverflowError Python int 太大而无法转换为 C long的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!