Python Program to Find the Prime Factors of a Number
Intermediate · Numbers
The prime factors of a number are the prime numbers that multiply together to make it, for example 360 = 2 x 2 x 2 x 3 x 3 x 5. This program finds them by dividing the number by the smallest possible factor again and again.
Program
Prime factors of 360: [2, 2, 2, 3, 3, 5] 360 = 2 x 2 x 2 x 3 x 3 x 5
How it works
- The search starts at 2, the smallest prime.
- The inner
whilekeeps dividing by the same divisor for as long as it fits, so a prime that appears three times, like 2 in 360, is recorded three times. - Only primes are ever recorded: by the time
divisorreaches 4, every 2 has already been divided out, so 4 can no longer dividen. - The loop stops once
divisor * divisoris bigger thann; anything above 1 left innat that point is a prime factor, like the 5 in 360. " x ".join(...)puts the factors together into the product shown on the last line.
Other ways to write it
Primes with their powers
360 = 2^3 x 3^2 x 5 Distinct prime factors: [2, 3, 5]
A dictionary counts how many times each prime divides the number, giving the power form used in maths books: 360 = 2^3 x 3^2 x 5.
Using recursion
12 -> [2, 2, 3] 97 -> [97] 1001 -> [7, 11, 13]
Each call either takes out one factor or moves on to the next divisor. It is neat, but a large prime would hit Python's recursion limit.
Try it yourself
Find the largest prime factor of 600851475143, a well-known Project Euler puzzle.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises