check a number out of prime.
1 2 3 4 5 6 7 8 9 10 11
import math def isPrime(n): if n <= 1: return False for i in range(2, int(math.sqrt(n)) + 1): if n % i == 0: return False return True
There is another variant without using sqrt:
def isPrime(n): if n <= 1: return False i = 2 while i*i <= n: if n % i == 0: return False i += 1 return True
Looks nicer if you use count from the itertools module:
count
itertools
from itertools import countdef isPrime(n): if n <= 1: return False for i in count(2): if i * i > n: return True if n % i == 0: return False
You can save half the calculations by skipping the even numbers:
def isPrime(n): if n <= 1: return False if n == 2: return True if n % 2 == 0: return False i = 3 while i * i <= n: if n % i == 0: return False i += 2 return True
yeah, thx guys!
This is the fastest python prime detecting function I've found:
def isPrimeNumber(number): if number <= 1: return False
if number == 2: return Truefor divisor in xrange(3, int(sqrt(number))+1, 2): if number % divisor == 0: return Falsereturn True
Sorry, it got messed up, and apparently won't let me edit it:
from math import sqrtdef isPrimeNumber(number): if number <= 1 or number % 2 == 0: return False if number == 2: return True for divisor in xrange(3, int(sqrt(number))+1, 2): if number % divisor == 0: return False return True`
There is another variant without using sqrt:
Looks nicer if you use
count
from theitertools
module:You can save half the calculations by skipping the even numbers:
yeah, thx guys!
This is the fastest python prime detecting function I've found:
def isPrimeNumber(number): if number <= 1: return False
Sorry, it got messed up, and apparently won't let me edit it: