[Tutor] large number question
Kent Johnson
kent_johnson at skillsoft.com
Sun Sep 26 14:21:11 CEST 2004
The problem is that xrange requires an int argument; it is the call to
xrange() that is generating the error:
>>> import sys
>>> sys.maxint
2147483647
>>> for i in xrange(2,2147483648L):
... pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in ?
OverflowError: long int too large to convert to int
>>> for i in xrange(2,2147483647L):
... pass
...
(wait a while and ^C)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyboardInterrupt
One solution is to rewrite your loop to compute the index yourself:
x = 2
limit = int(n**.5 + 1)
while x < limit
if n % x == 0:
prime = False
break
x += 1
or write your own generator function that does the same thing as xrange:
>>> def longRange(beg,end):
... val = beg
... while val < end:
... yield val
... val += 1
...
>>> list(longRange(2147483640, 2147483649L))
[2147483640, 2147483641, 2147483642, 2147483643, 2147483644, 2147483645,
2147483646, 2147483647, 2147483648L]
The first solution is likely to be faster.
Kent
At 09:08 PM 9/25/2004 -0700, Dick Moores wrote:
>I've written a program that will take a range of integers and tell me
>which are prime, and also tell me the prime factors of the non-primes
>(reinventing the wheel). It works well and efficiently, I believe, but I'm
>wondering if there's a way around the apparent limit on the size of
>integers. If I enter anything larger than about 4,610,000,000,000,000,000
>(4 quintillion, 610 quadrillion in American English), I get
>"OverflowError: long int too large to convert to int"
>
>I won't attach my program here, but an obviously important function is
>================================
>def isPrime(n):
> """returns True if n is prime; False if not"""
> prime = True
> if n < 2:
> prime = False
> else:
> for x in xrange(2,int(n**.5 + 1)):
> if n % x == 0:
> prime = False
> break
> return prime
>==============================
>
>If I use just isPrime alone, I get the same error message. Where does this
>limit come from? From Python? From Windows XP? From Dell (which made my
>computer)?
>
>Python v2.3.4, Windows XP.
>
>Thanks, tutors.
>
>Dick Moores
>rdm at rcblue.com
>
>
>_______________________________________________
>Tutor maillist - Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list