Prime factors of a number (original) (raw)

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.

Try It Yourselfredirect icon

Table of Content

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

Step by Step implementation:

#include #include using namespace std;

vector primeFactor (int n ){ vector ans ; for (int i = 2 ; i <= n ; i++){

    // n %  i  == 0 means n is divisible by i 
    while (n % i == 0 && n > 0 ){
        ans.push_back(i);
        n = n / i ;
    }
}
return ans ;

} int main() { int n = 18; vector ans = primeFactor(n); for (auto x : ans ){ cout << x <<' '; } return 0 ; }

Java

import java.util.ArrayList;

class GFG { public static ArrayList primeFactor(int n) { ArrayList ans = new ArrayList<>();

    // Loop from 2 to n
    for (int i = 2; i <= n; i++) {
        
        // n % i == 0 means n is divisible by i
        while (n % i == 0 && n > 0) {
            ans.add(i);
            
            // divide n by i to remove this factor
            n = n / i; 
        }
    }
    return ans;
}

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

    for (int x : ans) {
        System.out.print(x + " ");
    }
}

}

Python

def primeFactor(n): ans = []

# Loop from 2 to n
for i in range(2, n+1):
    
    # n % i == 0 means n is divisible by i
    while n % i == 0 and n > 0:
        ans.append(i) 
        
         # divide n by i to remove this factor
        n = n // i
return ans

if name == "main":

n = 18
ans = primeFactor(n)
for x in ans:
    print(x, end=' ')

C#

using System; using System.Collections.Generic;

class GFG {

static List<int> primeFactor(int n) {
    List<int> ans = new List<int>();
    
    // Loop from 2 to n
    for (int i = 2; i <= n; i++) {
        
        // n % i == 0 means n is divisible by i
        while (n % i == 0 && n > 0) {
            ans.Add(i); 
            
            // divide n by i to remove this factor
            n = n / i; 
        }
    }
    return ans;
}

static void Main() {
    int n = 18;
    List<int> ans = primeFactor(n);
    foreach (int x in ans) {
        Console.Write(x + " ");
    }
}

}

JavaScript

function primeFactor(n) { let ans = [];

// Loop from 2 to n
for (let i = 2; i <= n; i++) {
    
    // n % i == 0 means n is divisible by i
    while (n % i === 0 && n > 0) {
        ans.push(i); 
        
        // divide n by i to remove this factor
        n = n / i; 
    }
}
return ans;

}

//Driver Code

let n = 18; let ans = primeFactor(n); for (let x of ans) { process.stdout.write(x + ' '); }

`

[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 -

Step by Step implementation

#include #include using namespace std;

vector primeFactors(int n) { vector 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 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

import math def primeFactors(n):

# Print the number of two's that divide n
while n % 2 == 0:
    print 2,
    n = n / 2
    
# n must be odd at this point
# so a skip of 2 ( i = i + 2) can be used
for i in range(3,int(math.sqrt(n))+1,2):
    
    # while i divides n , print i and divide n
    while n % i== 0:
        print i,
        n = n / i
        
# Condition if n is a prime
# number greater than 2
if n > 2:
    print n

if name =="main":

n = 18
primeFactors(n)

C#

using System;

class GfG {

static void primeFactors(int n) {

    // Print the number of 2s that divide n
    while (n % 2 == 0) {

        Console.Write(2 + " ");
        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 += 2) {

        // While i divides n, print i and divide n
        while (n % i == 0) {

            Console.Write(i + " ");
            n /= i;
        }
    }

    // This condition is to handle the case when
    // n is a prime number greater than 2
    if (n > 2)
        Console.Write(n);
}

static void Main() {

    int n = 18;
    primeFactors(n);
}

}

JavaScript

function primeFactors(n) {

// Print the number of 2s that divide n
while (n % 2 == 0) {

    console.log(2 + " ");
    n = Math.floor(n / 2);
}

// n must be odd at this point.
// So we can skip one element
// (Note i = i +2)

for (let i = 3; i <= Math.floor(Math.sqrt(n));
     i = i + 2) {

    // While i divides n, print i
    // and divide n
    while (n % i == 0) {

        process.stdout.write(i + " ");
        n = Math.floor(n / i);
    }
}

// This condition is to handle the
// case when n is a prime number
// greater than 2
if (n > 2)
    process.stdout.write(n + " ");

}

// Driver Code let n = 18; primeFactors(n);

`

**Related article: