Find Prime Factors in JavaScript

Beginner
⏱️ 11 min read
📚 Updated: May 2026
🎯 2 Code Examples
Number theory

What you’ll learn

  • What prime factors are (primes you multiply to rebuild a number).
  • A trial division program that prints factors in order with clean JavaScript functions.
  • A faster version that peels off 2, then tests odd divisors only up to roughly the square root.
  • A live preview, input guards (so 0 does not loop forever), and usual edge cases.

Overview

Take 56. You can split it as 56 = 2 × 28 = 2 × 2 × 14 = 2 × 2 × 2 × 7. The primes that show up are 2 (three times) and 7 (once). This page prints that list: 2 2 2 7. The algorithm tries small divisors in order, strips each as many times as it can, and shrinks what is left until nothing is left to strip.

Two programs

Example 1 is the short double loop (easy to explain). Example 2 is the usual interview upgrade.

Live preview

Type 56, 17 (prime), or 360 before compiling.

Safe inputs

We require n >= 2 so 0 cannot get stuck dividing forever.

Prerequisites

for and while loops, remainder %, and integer division /.

  • Rough idea of prime: a whole number > 1 whose only positive divisors are 1 and itself (2, 3, 5, 7, 11…).
  • console.log, loops, and remainder checks with %.

What are prime factors?

Prime factors are prime numbers that multiply together to give your starting number. The order we print them is smallest first; repeated primes mean “that prime appears more than once.”

This is not the same lesson as “odd numbers”—the old reference page had a copy-paste heading mistake there. Here we stay on factorization the whole time.

Why trying 2, 3, 4, … still works

When i is composite (say 6), its prime pieces (2 and 3) were already removed from the running value x. So 6 cannot divide x anymore unless you missed an earlier factor—you did not. That is why a plain “does it divide?” test is enough without calling a separate isPrime function in this pattern.

Multiply the printout

If you multiply every printed factor together, you get the original n (for n >= 2). For a prime like 17, the only factor listed is 17.

Quick examples

56 Composite
Factors
2, 2, 2, 7
17 Prime
Factors
17 only
360 Many primes
Starts with
2, 2, 2, 3, 3, 5 …

Live preview

Uses the same fast pattern as Example 2 (twos, then odd trial divisors). Capped so inputs stay responsive.

Use a whole number from 2 up to about a million in this preview.

Live result
Press “Factorize” to list prime factors.

Algorithm (trial division)

Goal: print every prime factor of n (with repetition), in non-decreasing order, for integers n >= 2.

Validate n

If n < 2, stop or print a message (no prime factorization in this basic form).

Try divisors in order

Let i run from 2 upward. While the current remainder is divisible by i, print i and divide the remainder by i.

Stop when remainder is 1

In the simple version, the for loop can stop when the remainder reaches 1; the code on this page keeps the reference style i <= x for clarity.

📜 Pseudocode

Pseudocode
procedure displayPrimeFactors(n):
    if n < 2:
        report invalid / stop
    x ← n
    for i from 2 while i <= x:
        while x mod i = 0:
            output i
            x ← x / i
1

Straightforward trial division

Same structure as the reference program: divides_evenly is just a readable name for “remainder is zero.” We guard n < 2 so 0 never enters an infinite while (x % 2 == 0) loop.

JavaScript
function dividesEvenly(a, b) {
  return a % b === 0;
}

function displayPrimeFactors(n) {
  if (n < 2) {
    console.log("Enter an integer n >= 2 (got " + n + ").");
    return;
  }

  const factors = [];
  let x = n;

  for (let i = 2; i <= x; i++) {
    while (dividesEvenly(x, i)) {
      factors.push(i);
      x /= i;
    }
  }

  console.log("Prime factors of " + n + " are: " + factors.join(" "));
}

const number = 56;
displayPrimeFactors(number);
Try it Yourself

Explanation

Start with x = 56. At i = 2, peel three twos (56 → 28 → 14 → 7). Later i = 7 peels the seven. The remainder becomes 1 and the loop finishes.

2

Peel 2, then odd divisors up to √x

After removing all factors of 2, test only odd i. Stop when i × i exceeds the current remainder. If anything is left above 1, it is prime. Same printed line for 56 as Example 1.

JavaScript
function displayPrimeFactors(n) {
  if (n < 2) {
    console.log("Enter an integer n >= 2 (got " + n + ").");
    return;
  }

  const factors = [];
  let x = n;

  while (x % 2 === 0) {
    factors.push(2);
    x /= 2;
  }

  for (let i = 3; i * i <= x; i += 2) {
    while (x % i === 0) {
      factors.push(i);
      x /= i;
    }
  }

  if (x > 1) {
    factors.push(x);
  }

  console.log("Prime factors of " + n + " are: " + factors.join(" "));
}

const number = 56;
displayPrimeFactors(number);
Try it Yourself

Explanation

The final if (x > 1) catches one large prime left over (for example after trial division on a semiprime).

Notes

Wheel / sieve. For many queries, sieves or precomputed primes beat naive trial division; for one interview number, Example 2 is usually enough.

Number limits. JavaScript Number is safest for integer work up to Number.MAX_SAFE_INTEGER. Use BigInt for larger exact factorization.

Related: prime check, composite numbers, and GCD build on the same divisor ideas.

❓ FAQ

A prime factor is a prime number that divides your target evenly. Breaking a number into prime factors means writing it as primes multiplied together. Example: 56 = 2 &times; 2 &times; 2 &times; 7.
The old name isPrimeFactor sounded like a prime test, but the code only checks divisibility (remainder zero). The magic is the order: you try 2, then 3, then 4&hellip; By the time you reach a composite like 4, you already removed all factors of 2, so 4 cannot divide what is left.
A prime can appear more than once (like three 2s in 56). The inner while keeps stripping the same prime until it no longer divides.
Prime factorization is usually defined for integers n &gt;= 2. The programs on this page guard n &lt; 2 so you do not get empty lists or infinite loops on bad input.
Yes. Trying i = 2, 3, 4, &hellip; prints factors in non-decreasing order. (Duplicates mean repeated primes.)
Once only odd candidates remain, you can stop testing past sqrt(x) for the current remainder; anything left bigger than 1 is itself a prime factor.

🔄 Input / output examples

Change number in the script, or read input via prompt (browser) / readline (Node.js).

nPrinted factors (conceptually)
562 2 2 7
1717
122 2 3
1Error line from guard (no factorization)

Edge cases

Always guard small values so factorization logic does not loop forever on invalid input.

n = 0

Infinite loop risk

Naive while (x % 2 == 0) on x = 0 never progresses. Always reject n < 2 first.

n = 1

Empty product

Standard factorization starts at n >= 2. Say so in the message you print.

Squares

Repeated primes

36 prints 2 2 3 3—duplicates are expected.

⏱️ Time and space complexity

VersionTime (single n)Extra space
Example 1 (try every i up to current x)worst case about O(n) when n is primeO(1)
Example 2 (√ bound)O(√n) trial divisions typical storyO(1)

Summary

  • Idea: strip smallest divisors first; what you print are prime factors in order.
  • Code: guard n < 2; for + inner while (Example 1) or 2 + odds + leftover (Example 2).
  • Practical safety: validate n >= 2 and keep results in sorted order by divisor traversal.
Did you know?

The fundamental theorem of arithmetic says: every integer greater than 1 can be written as a product of primes in exactly one way if you ignore order. That is why “listing prime factors” feels so tidy—you are reading off that unique recipe.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful