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

5 comments

Michael Grünewald 14 years, 1 month ago  # | flag

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 14 years, 1 month ago  # | flag

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) 14 years, 1 month ago  # | flag

yeah, thx guys!

Ryan V 11 years, 9 months ago  # | flag

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, 9 months ago  # | flag

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

from math import sqrt

def 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`
Created by mitnk king on Tue, 2 Mar 2010 (MIT)
Python recipes (4591)
mitnk king's recipes (3)

Required Modules

  • (none specified)

Other Information and Tasks