python int()转换出错抛出异常类型_溢出错误Python int太大,无法转换为C long

这篇博客讨论了在尝试使用费马小定理进行因子分解时遇到的Python错误,包括MemoryError和OverflowError。作者提供了一段代码,但当输入大数时,代码无法正确运行。解决方案可能涉及使用能处理大数的库,如gmpy2,或者优化算法以减少计算资源的需求。
摘要由CSDN通过智能技术生成

#!/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

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

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

for b in xrange(1,n+1):

OverflowError: Python int too large to convert to C long

实际上,我是在为费马因子分解编写代码,以找到给定数字的因子。我的要求是,即使输入100位数字,也应该给出该输入数字的输出。

有没有办法解决这种问题?

我正在用Ubuntu和python 2.7.5+

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值