[Tutor] Advice for my function, isPrime(n), please
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
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)):
x = is_prime(n,100)
if x == 0:
Take a large integer I believe to be prime:
n = 88888888888888888888888888888888888888888888888888888888888888943
In : isPrime(n)
In : 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 -
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 : print isPrime(3.7)
In : print isPrime('44')
More information about the Tutor