Welcome, guest | Sign In | My Account | Store | Cart

check a number out of prime.

Python, 11 lines
 ``` 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 ``` Michael Grünewald 13 years, 6 months ago

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:

``````from itertools import count
def isPrime(n):
if n <= 1:
return False

for i in count(2):
if i * i > n:
return True
if n % i == 0:
return False
`````` Rogier Steehouder 13 years, 6 months ago

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
`````` mitnk king (author) 13 years, 6 months ago

yeah, thx guys! Ryan V 11 years, 2 months ago

This is the fastest python prime detecting function I've found:

def isPrimeNumber(number): if number <= 1: 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
`````` Ryan V 11 years, 2 months ago

Sorry, it got messed up, and apparently won't let me edit it:

``````from math import sqrt

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`
`````` Created by mitnk king on Tue, 2 Mar 2010 (MIT)

### Required Modules

• (none specified)