Find all prime factors of a number - JavaScript

We are required to write a JavaScript function that takes in a number and returns an array of all the prime numbers that exactly divide the input number.

For example, if the input number is 18, the prime factors are 2 and 3 because 18 = 2 × 3².

Then the output should be ?

[2, 3]

Understanding Prime Factorization

Prime factorization breaks down a number into its prime components. A prime factor is a prime number that divides the original number exactly.

Method 1: Using Helper Function to Check Primes

This approach uses a helper function to verify if each factor is prime:

const num = 18;

const isPrime = (n) => {
    if (n < 2) return false;
    for(let i = 2; i <= n/2; i++){
        if(n % i === 0){
            return false;
        }
    }
    return true;
};

const findPrimeFactors = num => {
    const res = num % 2 === 0 ? [2] : [];
    let start = 3;
    while(start <= num){
        if(num % start === 0){
            if(isPrime(start)){
                res.push(start);
            }
        }
        start += 2; // Skip even numbers after 2
    }
    return res;
};

console.log(findPrimeFactors(18));
console.log(findPrimeFactors(30));
console.log(findPrimeFactors(17));
[2, 3]
[2, 3, 5]
[17]

Method 2: Optimized Division Approach

This more efficient method divides out each prime factor completely:

const findPrimeFactorsOptimized = (n) => {
    const factors = [];
    
    // Handle factor 2
    if (n % 2 === 0) {
        factors.push(2);
        while (n % 2 === 0) {
            n = n / 2;
        }
    }
    
    // Check odd factors from 3 onwards
    for (let i = 3; i * i <= n; i += 2) {
        if (n % i === 0) {
            factors.push(i);
            while (n % i === 0) {
                n = n / i;
            }
        }
    }
    
    // If n is still greater than 2, it's a prime factor
    if (n > 2) {
        factors.push(n);
    }
    
    return factors;
};

console.log(findPrimeFactorsOptimized(18));
console.log(findPrimeFactorsOptimized(60));
console.log(findPrimeFactorsOptimized(97));
[2, 3]
[2, 3, 5]
[97]

Comparison

Method Time Complexity Space Complexity Efficiency
Helper Function Method O(n²) O(k) Less efficient
Division Method O(?n) O(k) More efficient

Key Points

  • Prime factors are unique - each appears only once in the result array
  • The optimized method stops checking at ?n for better performance
  • Handle even numbers separately by checking divisibility by 2 first
  • The remaining number after all divisions is itself a prime if greater than 2

Conclusion

The division method is more efficient for finding prime factors as it eliminates factors during the process. Use this approach for better performance, especially with larger numbers.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements