Dec 10 2009

Print this Post

Determining if a Number is Prime

While working on some caching settings, I had a need to know if a number is prime. I wrote this little Python script which will tell you if the number defined in the script is indeed a prime.

Checks the specified value to determine if it is a prime number.  
If it is not prime the divisor will be returned instead.

@author: Eric Silva

#Change this value to whatever value you want to test for prime.
testValue = 3011

def determineIsPrime(testPrime):
    if testPrime % 2 == 0:
        return 'Divisible by 2'
    testNum = 3
    testLimit = testPrime
    while testLimit >= testNum:
        if testPrime % testNum == 0:
           return 'Divisible by %d' % testNum
        testLimit = testPrime/testNum
        testNum = testNum + 2
    return '%d is prime!' % testPrime

result = determineIsPrime(testValue)

print result 

Permanent link to this article: http://ericsilva.org/2009/12/10/determining-if-a-number-is-prime/

1 ping

  1. To Hell in a Handbasket » Primality Test v2.0

    […] some friends of mine, and doing a little bit of background research, I am writing this update to my original post last week.  As it turns out, by checking all the numbers in the form 6k ± 1  instead of checking each […]

Leave a Reply