Python Program to Print all Prime Factors of a given Number (original) (raw)

Last Updated : 29 Oct, 2025

Given a number n, the task is to print all of its prime factors. Prime factors are the prime numbers that divide a given number exactly without leaving a remainder. For example:

**Input: 12
**Output: 2 2 3

Let's explore different methods to find all prime factors of a number in Python.

Using Sieve of Eratosthenes

In this method, we precompute smallest prime factor for every number up to n using a sieve-like approach. Then, we use these precomputed values to efficiently print all prime factors of the given number.

Python `

n = 315 spf = [0 for _ in range(n + 1)] # Smallest Prime Factor array spf[1] = 1

for i in range(2, n + 1): spf[i] = i

for i in range(4, n + 1, 2): spf[i] = 2

for i in range(3, int(n ** 0.5) + 1, 2): if spf[i] == i: for j in range(i * i, n + 1, i): if spf[j] == j: spf[j] = i

while n != 1: print (spf[n]) n //= spf[n]

`

**Explanation:

Using Math Module

Here, we use math module to divide the number continuously by 2 and then by all odd divisors up to its square root. Each divisor that divides the number completely is printed as a prime factor.

Python `

import math n = 315

while n % 2 == 0: print(2) n //= 2

for i in range(3, int(math.sqrt(n)) + 1, 2): while n % i == 0: print(i) n //= i

if n > 2: print(n)

`

**Explanation:

Using Iterative Division

In this method, number is divided repeatedly by the smallest divisor starting from 2. Each divisor that divides the number is printed immediately, and the process continues until the number becomes 1.

Python `

n = 315 i = 2

while i * i <= n: while n % i == 0: print(i) n //= i i += 1

if n > 1: print(n)

`

**Explanation:

Using Anonymous Function

Here, we use a lambda expression to generate prime factors of the number dynamically. The code repeatedly finds and removes each factor until the number is reduced to 1.

Python `

pf = lambda n: [i for i in range(2, n + 1) if n % i == 0 and all(i % j != 0 for j in range(2, int(i ** 0.5) + 1))] n = 315 f = []

while n > 1: for factor in pf(n): f.append(factor) n //= factor

print(*f)

`

**Explanation: