Ad space (banner)
🐍Python Lessons
Lesson 68 / 69

Prime Factorization

This lesson covers an algorithm for prime factorization — expressing a number as a product of primes — so you can experience the connection between math and programming. It's written for anyone who searched "Python prime factorization" and landed here.

Prime factorization means expressing a number as a product of prime numbers. You find it by trying divisors starting from 2, and continuing to divide by any divisor that works. This is an important idea spanning both math and computer science, and it's part of what makes cryptographic techniques like RSA encryption secure.

The sample code increases a variable, d, starting from 2, dividing n by it repeatedly as long as it divides evenly. Once it no longer divides evenly, d increases by 1 and the next number is tried — repeating this process until n reaches 1, collecting every prime factor into a list called factors.

A common beginner mistake is understanding the roles of the two nested loops. The inner loop handles "how many times does the same number divide evenly," while the outer loop (the while) handles "advancing to the next number to try." Understanding this two-level structure reveals the overall flow of the algorithm.

Tallying the prime factorization results into a dictionary showing "how many of each factor" produces a more practical output. It's a great topic for experiencing the connection between computer-science fundamentals and programming.

Python
OUTPUT

💡 The Python engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)