[Tutor] Advice for my function, isPrime(n), please

Dick Moores rdm at rcblue.com
Fri Jul 18 17:32:19 CEST 2008


I'm rather please with the speed of isPrime(). Any credit, of course, 
goes to Alex Martelli, who wrote gmpy.
from gmpy import is_prime
def isPrime(n):
     """
     Return True if n is prime, False if not prime.
     If n not an int or a long, return None.
     """
     if not isinstance(n, (int, long)):
         return None
     x = is_prime(n,100)
     if x == 0:
         return False
     else:
         return True

Take a large integer I believe to be prime:
n = 88888888888888888888888888888888888888888888888888888888888888943

In [15]: isPrime(n)
Out[15]: True

In [16]: timeit isPrime(n)
100 loops, best of 3: 20.1 ms per loop

It couldn't be used for cryptography, I suppose, because it's 
probability of being accurate is not 1, but 1 - 1/(2**100), or 1 - 
7.8886090522101181e-031 .

My question is about whether to test for integerhood. Without that 
test,  isPrime(3.7) returns true, and isPrime('44') returns False. 
I've gone with testing for integerhood, and with returning None when 
n fails the test. Thus,

In [3]: print isPrime(3.7)
None

In [4]: print isPrime('44')
None

Advice?

Thanks,

Dick Moores




More information about the Tutor mailing list