Prime factors of a number

Last Updated : 27 Oct, 2026

Given a number n, find all prime factors of n.

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.

Try It Yourself
redirect icon

[Naive Approach] Try All - O(n) Time and O(1) Space

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.
C++
#include <iostream>
#include <vector>
using namespace std;

vector<int> primeFactors(int n) {
    vector<int> factors;

    // Check every number from 2 to n
    for (int i = 2; i <= n; i++) {

        // Extract all occurrences of factor i
        while (n % i == 0) {
            factors.push_back(i);
            n /= i;
        }
    }

    return factors;
}

int main() {
    int n = 60;
    vector<int> factors = primeFactors(n);

    for (int factor : factors)
        cout << factor << " ";

    return 0;
}
Java
import java.util.ArrayList;

class GFG {
    static ArrayList<Integer> primeFactors(int n) {
        ArrayList<Integer> factors = new ArrayList<>();

        // Check every number from 2 to n
        for (int i = 2; i <= n; i++) {

            // Extract all occurrences of factor i
            while (n % i == 0) {
                factors.add(i);
                n /= i;
            }
        }

        return factors;
    }

    public static void main(String[] args) {
        int n = 60;
        ArrayList<Integer> factors = primeFactors(n);

        for (int factor : factors)
            System.out.print(factor + " ");

        System.out.println();
    }
}
Python
def primeFactors(n):
    factors = []

    # Check every number from 2 to n
    for i in range(2, n + 1):

        # Extract all occurrences of factor i
        while n % i == 0:
            factors.append(i)
            n //= i

    return factors


if __name__ == "__main__":
    n = 60
    factors = primeFactors(n)
    print(*factors)
C#
using System;
using System.Collections.Generic;

class GFG
{
    static List<int> primeFactors(int n)
    {
        List<int> factors = new List<int>();

        // Check every number from 2 to n
        for (int i = 2; i <= n; i++)
        {
            // Extract all occurrences of factor i
            while (n % i == 0)
            {
                factors.Add(i);
                n /= i;
            }
        }

        return factors;
    }

    static void Main()
    {
        int n = 60;
        List<int> factors = primeFactors(n);

        foreach (int factor in factors)
            Console.Write(factor + " ");

        Console.WriteLine();
    }
}
JavaScript
function primeFactors(n) {
    let factors = [];

    // Check every number from 2 to n
    for (let i = 2; i <= n; i++) {

        // Extract all occurrences of factor i
        while (n % i === 0) {
            factors.push(i);
            n = Math.floor(n / i);
        }
    }

    return factors;
}

// Driver code
let n = 60;
let factors = primeFactors(n);
console.log(factors.join(" "));

Output
2 3 3 

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

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.
  • f 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.
C++
#include <iostream>
#include <vector>
using namespace std;

vector<int> primeFactors(int n) {
    vector<int> factors;

    // Store the number of 2s that divide n
    while (n % 2 == 0) {
        factors.push_back(2);
        n = n / 2;
    }

    // n must be odd at this point. So we can 
     // skip one element (i = i + 2)
    for (int i = 3; i * i <= n; i = i + 2) {
        while (n % i == 0) {
            factors.push_back(i);
            n = n / i;
        }
    }

    // If n is a prime number greater than 2
    if (n > 2)
        factors.push_back(n);

    return factors;
}

int main() {
    int n = 18;
    vector<int> ans = primeFactors(n);

    // Print the factors stored in vector
    for (int factor : ans) {
        cout << factor << " ";
    }
    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

// A function to return all prime factors of a given number n
int primeFactors(int n, int **factors) {
    *factors = (int *)malloc(sizeof(int) * 10000); // allocate memory
    int index = 0;

    // Store the number of 2s that divide n
    while (n % 2 == 0) {
        (*factors)[index++] = 2;
        n = n / 2;
    }

    // n must be odd at this point. So we can 
    // skip one element (i = i + 2)
    for (int i = 3; i * i <= n; i = i + 2) {
        while (n % i == 0) {
            (*factors)[index++] = i;
            n = n / i;
        }
    }

    // If n is a prime number greater than 2
    if (n > 2)
        (*factors)[index++] = n;
        
    // return number of factors stored
    return index; 
}

int main() {
    int n = 18;
    int *ans;
    int size = primeFactors(n, &ans);

    // Print the factors stored in array
    for (int i = 0; i < size; i++) {
        printf("%d ", ans[i]);
    }

    free(ans); // free allocated memory
    return 0;
}
Java
import java.util.ArrayList;

class GfG {

    static ArrayList<Integer> primeFactors(int n) {
        ArrayList<Integer> factors = new ArrayList<>();

        // Store the number of 2s that divide n
        while (n % 2 == 0) {
            factors.add(2);
            n /= 2;
        }

        // n must be odd at this point
        for (int i = 3; i * i <= n; i += 2) {
            while (n % i == 0) {
                factors.add(i);
                n /= i;
            }
        }

        // If n is a prime number greater than 2
        if (n > 2)
            factors.add(n);

        return factors;
    }

    public static void main(String[] args) {
        int n = 18;
        ArrayList<Integer> result = primeFactors(n);

        // Printing the factors stored in ArrayList
        for (int factor : result) {
            System.out.print(factor + " ");
        }
    }
}
Python
def primeFactors(n):
    factors = []

    # Store the number of 2s that divide n
    while n % 2 == 0:
        factors.append(2)
        n //= 2

    # n must be odd at this point
    i = 3
    while i * i <= n:
        while n % i == 0:
            factors.append(i)
            n //= i
        i += 2

    # If n is a prime number greater than 2
    if n > 2:
        factors.append(n)

    return factors


if __name__ == "__main__":
    n = 18
    result = primeFactors(n)

    # Print the factors stored in the list
    print(*result)
C#
using System;
using System.Collections.Generic;

class GFG
{
    static List<int> primeFactors(int n)
    {
        List<int> factors = new List<int>();

        // Store the number of 2s that divide n
        while (n % 2 == 0)
        {
            factors.Add(2);
            n /= 2;
        }

        // n must be odd at this point
        for (int i = 3; i * i <= n; i += 2)
        {
            while (n % i == 0)
            {
                factors.Add(i);
                n /= i;
            }
        }

        // If n is a prime number greater than 2
        if (n > 2)
            factors.Add(n);

        return factors;
    }

    static void Main()
    {
        int n = 18;
        List<int> result = primeFactors(n);

        // Print the factors stored in the list
        foreach (int factor in result)
            Console.Write(factor + " ");

        Console.WriteLine();
    }
}
JavaScript
function primeFactors(n) {
    let factors = [];

    // Store the number of 2s that divide n
    while (n % 2 === 0) {
        factors.push(2);
        n = Math.floor(n / 2);
    }

    // n must be odd at this point
    for (let i = 3; i * i <= n; i += 2) {
        while (n % i === 0) {
            factors.push(i);
            n = Math.floor(n / i);
        }
    }

    // If n is a prime number greater than 2
    if (n > 2)
        factors.push(n);

    return factors;
}

// Driver code
let n = 18;
let result = primeFactors(n);

// Print the factors stored in the array
console.log(result.join(" "));

Output
2 3 3 

Related article: 

Comment