范围太大 Python [英] Range is too large Python

查看:39
本文介绍了范围太大 Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到数字 x 的最大质因数,Python 给出了范围太大的错误.我试过使用 x 范围,但出现溢出错误:Python int 太大而无法转换为 C long

I'm trying to find the largest prime factor of the number x, Python gives me the error that the range is too large. I've tried using x range but I get an OverflowError: Python int too large to convert to C long

x = 600851475143
maxPrime = 0


for i in range(x):
    isItPrime = True
    if (x%i == 0):
        for prime in range(2,i-1):
            if (i%prime == 0):
                isItPrime = False
        if (isItPrime == True):

            if (i > maxPrime):
                maxPrime = i;

print maxPrime

推荐答案

在旧的 (2.x) 版本的 Python 中,xrange 只能处理 Python 2.x ints,受平台的原生长整数大小限制.此外,range 在 Python 2.x 上预先分配了一个包含所有数字的列表,因此不适合大参数.

In old (2.x) versions of Python, xrange can only handle Python 2.x ints, which are bound by the native long integer size of your platform. Additionally, range allocates a list with all numbers beforehand on Python 2.x, and is therefore unsuitable for large arguments.

您可以切换到 3.x(推荐)或 long int(在 C 中)为 64 位长的平台,或使用以下插件:

You can either switch to 3.x (recommended), or a platform where long int (in C) is 64 bit long, or use the following drop-in:

import itertools
range = lambda stop: iter(itertools.count().next, stop)

等效地,以简单的形式:

Equivalently, in a plain form:

def range(stop):
   i = 0
   while i < stop:
       yield i
       i += 1

这篇关于范围太大 Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆