usingMaths.com
Demonstrating and showing pupils and students one application of Mathematics.







<< PreviousNext >>

Code to Check for Primeness in Python



The thing about Prime Numbers

Prime numbers are tricky to spot.
A number that looks like a prime may in fact be a multiple of a smaller prime number.

So let's see how to know for sure that a number is a prime.
Of-course there is only one way:


Code in Python for Checking Prime Numbers

A prime number is one that can only be divided by itself and one (1).

Consider the number 97.
To know for sure whether it is a prime number, we will recursively (repetitively) divide it by every number between 2 and 96 (97 minus 1).
If none of these divisors gives a remainder of zero, then 97 is certainly a prime number.


Create a new module file; File, New File.
Call it CheckPrime.py
Type out the adjoining Python code for checking for primeness.


Base Theory of Quick-Check for Primeness in Python

Since the world is always in a hurry, we can make use of a little extra speed.

Consider the number 36; Its factors are:

1, 2, 3, 4, 6, 9, 12, 18 and 36.

Every factor of 36, when arranged in ascending or descending order, can be divided into 2 equal parts at the position of its square-root.

1, 2, 3, 4, |, 9, 12, 18, 36

It is easily seen that every factor of 36 on one side of the divide has a complementary factor on the other side.

Complementary factors

Hence, we can search for only a particular group of factors, (preferably the more compact group, i.e, between 1 and √36) to see if 36 has any factors.


A fast Check for Primeness in Python

So for our quick check, we will use the range of 2 to √number.
Type out the adjoining Python code for fast prime number check.


Note: You can simply tweak the existing function.
You can comment out the Python code for the main class from the previous lesson if you have been following.









<< PreviousNext >>