簡體   English   中英

OverflowError Python int 太大而無法轉換為 C long

[英]OverflowError Python int too large to convert to C long

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

令人討厭的是,在 Python 2 中, xrange要求其參數適合 C long。 標准庫中沒有完全替代品。 但是,您並不完全需要直接替換。 你只需要繼續下去,直到循環break s。 這意味着您需要itertools.count ,它就像一個持續運行的xrange

import itertools
for b in itertools.count(1):
    ...

另外,請注意您的代碼還有其他錯誤。 它嘗試將費馬分解應用於偶數,但費馬分解不適用於偶數。 此外,它沒有考慮n是正方形的情況,因此它不適用於n=9

順便說一句,如果您仍然想要一個可以處理大數字的因子函數,請在這里:

from math import sqrt
def factors(n):
return set(reduce(list.__add__,
            ([i, n//i] for i in range(1, int(sqrt(n)) + 1) if n % i == 0)))

所以現在你只需要說:

>>> factors(largenumhere)

對於大量因素:D

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM