VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-all-prime-factors-of-a-given-number/

⇱ Prime factors of a number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Prime factors of a number

Last Updated : 3 Oct, 2025

Given a number n, find all prime factors of n.
Note : Prime number is a natural number greater than 1 that has exactly two factors:1 and itself.

Examples:

Input: n = 18
Output: [2, 3, 3]
Explanation: The prime factorization of 18 is 2×32.

Input: n = 25
Output: [5, 5]
Explanation: The prime factorization of 25 is 52.

[Naive Approach] Iterative Time O(n) and space O(1)

Step by Step implementation:

  • Start a loop from i = 2 up to n.
  • For each i, check if n is divisible by i (i.e n % i == 0).
  • While n is divisible by i, store i as a factor and divide n by i.
  • Continue this process for all i up to n to extract all prime factors.

Output
2 3 3 

[Expected Approach] Prime Factorisation Time O(sqrt(n)) and Space (1)

Every composite number has at least one prime factor less than or equal to its square root. This property can be proved using a counter statement -

  • Let a and b be two factors of n such that a*b = n.
  • If both are greater than sqrt(n), a*b > sqrt(n)*sqrt(n), which contradicts the expression a * b = n

Step by Step implementation

  • While n is divisible by 2, print 2 and divide n by 2.
  • After step 1, n must be odd. Now start a loop from i = 3 to the square root of n. While i divides n, print i, and divide n by i. After i fails to divide n, increment i by 2 because next prime factor will also be odd since we have already taken care of all the 2 and continue.
  • If n greater than 2, then n is the last prime factor.

Output
2 3 3 

Related article: 

Comment