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







<< PreviousNext >>

Code for Listing Prime Numbers in Python



Randomness of Prime Numbers

Prime numbers, in ascending order, are:

2, 3, 5, 7, 11, 13, 17, 19, 23, ...

Because prime numbers are so random in their progression, they are very difficult to predict as they get larger.

Hence writing a Python code to list prime numbers will involve checking every number in a range of interest and gathering those that are without factors.

Say we want to list all prime numbers between 2 and 100 inclusive, we would start from 2; check to see whether it has any factors; keep it as a prime number if it has no factors; otherwise discard it.
We would then go to 3, and repeat the same process.
Repeat same for 4, 5, 6, 7, ..., 98, 99, 100.


Code that lists Prime Numbers in Python

But we can always use a few tricks .

We will take the following steps:
Step 1:

First, we'll start our range from 9 (keeping 2, 3, 5, and 7 as prime numbers).

Step 2:

Next, we'll only check through odd numbers.

Step 3:

Next, we'll check against the factors 2, 3, and 5.

Step 4:

Lastly, we'll check with a subset of smaller prime numbers that we'll gather as our check progresses.


Create a new class file; File, New File.
Call it listPrimeNumbers.py.

Type out the adjoining Python code for listing prime numbers.


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









<< PreviousNext >>