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







<< PreviousNext >>

Code for Prime Factors of a Number in Python



Finding Prime Factors in Python

Finding prime factors is all about selecting those factors of a number that are prime.
The prime factors of 36 as an example, are:

2 X 2 X 3 X 3.

Prime Factor code

We'll go about the code in a simple way:

Step 1:

Starting with 2, find the first factor of the number of interest - this factor will definitely be a prime.
Store this factor away.

Step 2:

Divide number in question by found factor.

Step 3:

Using result from Step 2 as the new number in question (number whose prime factors we are trying to find), repeat Step 1.

Step 4:

Continue recursively until we arrive at 1.

Step 5:

We'll use the square-root of number range.


Create a new module file; File, New File.
Call it listPrimeFactors.py.

Type out the adjoining Python code for finding prime factors.


All those steps in a few lines of code;
Now functions come in handy, don't they?

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









<< PreviousNext >>