Python"OverflowError" [英] Python "OverflowError"

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

问题描述

我才刚刚开始学习用Python编写代码.我正在尝试编写一些代码来回答这个Euler项目问题​​:

I am just starting to learn to code in Python. I am trying to write some code to answer this Project Euler Question:

13195的主要因子是5、7、13和29.

The prime factors of 13195 are 5, 7, 13 and 29.

600851475143的最大素数是多少?

What is the largest prime factor of the number 600851475143 ?

我的程序可以使用13195的测试用例,但是当我尝试输入600851475143时,出现错误:"OverflowError:range()结果包含太多项" 有谁知道我该如何解决?

My program works with the test case of 13195, but when I try to enter 600851475143, I get the error: "OverflowError: range() results has too many items" Does anyone know how I can fix this?

这是我的代码:

class Euler3:
    "A class to find the largest prime factor of a given number"
     n = 600851475143
     primeFactors = []
     for i in range(2,n):
         if (n%i ==0):
            primeFactors.append(i)
            n = n/i
            i = i -1 #reset i
     print primeFactors

任何帮助或建议将不胜感激!

Any help or suggestions would be much appreciated!

推荐答案

range函数创建一个列表,然后尝试将其存储在内存中.创建一个包含许多数字的列表是导致OverflowError的原因.您可以使用xrange来获取生成器,该生成器根据需要生成数字.

The range function creates a list and tries to store it in memory. Creating a list many numbers long is what's causing the OverflowError. You can use xrange instead to get a generator which produces the numbers on demand.

也就是说,我认为您会发现您的算法对于计算大素数太慢了.质数算法很多,但我建议您将筛网筛网起点.

That said, I think you'll find that your algorithm is way too slow for calculating large primes. There are a lot of prime number algorithms, but I might suggest checking out the Sieve of Eratosthenes as a starting point.

正确地xrange实际上不返回生成器,但是行为很像生成器的xrange对象.我不确定您是否在乎,但这使我感到困惑,因为我不够精确!

Properly xrange actually doesn't return a generator, but an xrange object which behaves a lot like a generator. I'm not sure if you care, but it was bugging me that i wasn't precise!

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

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