Question about function failing with large number

A

Anthony Papillion

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512

So I'm using the function below to test a large (617 digit) number for
primality. For some reason, when I execute the code, I get an error
telling me:

OverflowError: long int too large to convert to float

The error is being thrown on this line:

for x in range(3, int(n**0.5)+1, 2):

The odd thing is that the error is not thrown every single time. I can
run the function a few times, it will generate a large number (always
the same length) and run it through the function. After I do this a
few times, it fails with the error. I might get the error on the next
few runs but then, all of a sudden, it functions again.

Any ideas? The entire program, including the method, is below.

#!/usr/bin/env python

from random import getrandbits

bits = 2048

# Test if the number is a prime
def isprime(n):

# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
if not n & 1:
return False
# range starts with 3 and only needs to go up the squareroot of n
# for all odd numbers
for x in range(3, int(n**0.5)+1, 2):
if n % x == 0:
return False
return True

a = getrandbits(bits)
print "\nGenerated Number: ", a, "\n"
print "Number of digits: ", len(str(a))
isNumberPrime = isprime(a)
if isNumberPrime == True:
print "\nThis number is a prime.\n"
else:
print "\nThis number is not a prime.\n"

Thanks!
Anthony


- --
Anthony Papillion
Phone: 1.918.533.9699
SIP: (e-mail address removed)
XMPP: (e-mail address removed)

www.cajuntechie.org
-----BEGIN PGP SIGNATURE-----

iQIcBAEBCgAGBQJSCiKNAAoJEKCKfnPhYIFFn7gP/A8CHOyTv71J/uVpMVYRcDRp
KRwbL9A1gkzUpycQibN3Q90FwY6nsGGPCeOkZByfYZnMKQH0o4Kd7QQf0hEOkhzO
BLiQjbkjzuUq7usE5TIqjTi0pJ6J7DcRm6U77yhAWrVt60MpfOucojLzX8ZolTD6
7Ha1gJ+9uEcwjosx1ynjVt7MQ/uGZwM7xS6WNfOpOwIYnoT5zBUzlKbw1HqSGYLu
6cWmAFTnnnXv6qymbGTxdZf0dxciODXy5xIMp5CzG6zIeHIOvjG03AbcY/+nI5FI
b9fKqjbblE/Npnh9GPXOLpI+I05VZMoO1b0AJSlU+Iq1liZAZOA4s2kf7XCrSb7Y
8Zn6qMPMTuNBPZpRJykTJSrA8s+4RxA0BWoq9rnTNXJPVR6imt6USOtwY4UssPxw
HIUrbSmfAEF9+/g08mcKHTVFstMyQCuAbUGx+LxoxkySnwZkfcwTRQ2vuoBDd7XP
92IJlkAdwepEa748P6NHNkSN4+OV3zAeTczHkzD0OL2KAeCuPY5tlqsI0MAngKOu
TIZrG+w1rvkz1gU3TBILLySuQTk/ioHNoVAH46bvp6ARRJiHJ4Ub61NoyooMCOgX
Lg+XtmcYz9VdUzdayg5uwNQAb/2/DboAyvmuuRDrA2Lzndv1JO3ye222/WCI9e7V
aB1ghvNnNMtrOWA0ZVQX
=BZUP
-----END PGP SIGNATURE-----
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,989
Messages
2,570,207
Members
46,783
Latest member
RickeyDort

Latest Threads

Top