(Translated by https://www.hiragana.jp/)
Print all prime factors of a given number - GeeksforGeeks
Open In App

Print all prime factors of a given number

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a number n, the task is to find all prime factors of n.

Examples:

Input: n = 24
Output: 2 2 2 3
Explanation: The prime factorization of 24 is 23×3.

Input: n = 13195
Output: 5 7 13 29
Explanation: The prime factorization of 13195 is 5×7×13×29.

Approach:

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

Following are the steps to find all prime factors:

  • 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.
C++
// C++ program to print all prime factors 
#include <bits/stdc++.h>
using namespace std;

// A function to print all prime 
// factors of a given number n 
void primeFactors(int n) {
  
    // Print the number of 2s that divide n 
    while (n % 2 == 0) {
      
        cout << 2 << " "; 
        n = n/2; 
    } 

    // n must be odd at this point. So we can skip 
    // one element (Note i = i +2) 
    for (int i = 3; i*i <= n; i = i + 2) {
      
        // While i divides n, print i and divide n 
        while (n % i == 0) {
          
            cout << i << " "; 
            n = n/i; 
        } 
    } 

    // This condition is to handle the case when n 
    // is a prime number greater than 2 
    if (n > 2) 
        cout << n << " "; 
} 


int main() {
  
    int n = 315; 
    primeFactors(n); 
    return 0; 
} 
C Java Python C# JavaScript

Output
3 3 5 7 

Time Complexity: O(sqrt(n))
Auxiliary Space: O(1)

Related article: 


Prime Factorization
Visit Course explore course icon

Similar Reads