JavaScript Prime Factors Program

Beginner
5 min read
Updated: Oct 2026
3 programs
Live preview

What Are Prime Factors?

The prime factors of an integer n > 1 are the prime numbers that multiply together to make n. Every such n has a unique factorization (ignoring order).

Remember
84 = 2 × 2 × 3 × 7
30 = 2 × 3 × 5
17 = 17          (already prime)

Method idea: trial division
  peel small primes from n until only 1 remains
nPrime factors
842, 2, 3, 7
1002, 2, 5, 5
1313

How to Find Prime Factors in JavaScript

Four clear steps — then pick a simple scan or an O(√n) version.

  1. Require n > 1.
  2. While n is even, record 2 and set n = Math.floor(n / 2).
  3. Try odd candidates i = 3, 5, 7, …; whenever i divides n, record i and divide.
  4. If n > 1 remains, that leftover is a prime factor — record it.
MethodIdeaTimeBest for
Simple trialTry factors while i <= nO(n)First explanation
√n trialLoop while i * i <= nO(√n)Interview / practical code

Pseudocode

Pseudocode
function PrintPrimeFactors(n):
    if n <= 1: return

    while n % 2 == 0:
        print 2
        n = n / 2

    i = 3
    while i * i <= n:
        while n % i == 0:
            print i
            n = n / i
        i = i + 2

    if n > 1:
        print n

Cheat Sheet

Keep these facts handy while writing the program.

TopicDetail
Inputn > 1
Factor 2Peel first (only even prime)
Odd loopStep i by 2
LeftoverIf n > 1 after loops, print n
RepeatsPrint the same prime each time it divides
Classic check84 → 2 2 3 7

Live Preview

Enter an integer greater than 1 to see its prime factorization.

Integers from 2 to 1000000. Tap a chip or type a value.

Result
n = 84
Prime factors: 2 × 2 × 3 × 7

JavaScript Programs

Start with the simple trial loop so every step is obvious. Then use the √n version for the usual interview answer, and return a list when you need the factors as data. Each example has a Try it Yourself editor.

Example 1 — Simple Trial

Try candidates from 2 upward while dividing n down to 1.

JavaScript
function printPrimeFactors(n) {
  if (n <= 1) {
    console.log("Enter an integer greater than 1.");
    return;
  }

  let line = "Prime factors of " + n + ": ";
  for (let i = 2; i <= n; i++) {
    while (n % i === 0) {
      line += i + " ";
      n = Math.floor(n / i);
    }
  }
  console.log(line.trim());
}

printPrimeFactors(84);
Try It Yourself

How It Works

  1. Reject n <= 1 — factorization needs an integer greater than 1.
  2. Outer loop tries each candidate i starting at 2.
  3. Inner while peels every copy of that factor from n with Math.floor.
  4. Because smaller factors are removed first, each printed i is prime.
  5. When n becomes 1, the loop ends and the factorization is complete.

Example 2 — √n Trial

Handle 2 first, then odd factors up to √n, then print any leftover prime.

JavaScript
function printPrimeFactors(n) {
  if (n <= 1) {
    console.log("Enter an integer greater than 1.");
    return;
  }

  const original = n;
  let line = "Prime factors of " + original + ": ";

  while (n % 2 === 0) {
    line += "2 ";
    n = Math.floor(n / 2);
  }

  for (let i = 3; i * i <= n; i += 2) {
    while (n % i === 0) {
      line += i + " ";
      n = Math.floor(n / i);
    }
  }

  if (n > 1) {
    line += n;
  }
  console.log(line.trim());
}

printPrimeFactors(84);
printPrimeFactors(13);
Try It Yourself

How It Works

  1. Peel all factors of 2 first so the rest of the search can skip even numbers.
  2. Odd loop runs only while i * i <= n — no need to go past √n.
  3. Each time i divides n, append and divide repeatedly.
  4. After the loop, any leftover n > 1 is itself a prime factor.
  5. Same answers as Example 1, typically much faster for larger n.

Example 3 — Return a List

Same √n logic, but collect factors into an array instead of printing.

JavaScript
function primeFactors(n) {
  if (n < 2) {
    return [];
  }

  const factors = [];

  while (n % 2 === 0) {
    factors.push(2);
    n = Math.floor(n / 2);
  }

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

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

  return factors;
}

console.log(JSON.stringify(primeFactors(84)));
console.log(JSON.stringify(primeFactors(13)));
console.log(JSON.stringify(primeFactors(360)));
Try It Yourself

How It Works

  1. Return an empty array for n < 2.
  2. Use the same peel-2 / odd-√n / leftover steps as Example 2.
  3. Push each factor into factors instead of building a string.
  4. The returned array keeps multiplicity — 8 becomes [2, 2, 2].
  5. Useful when later code needs the factors as data, not just console output.

Edge Cases & Pitfalls

Check these before calling the solution done.

n ≤ 1

Invalid input

Factorization is defined for integers greater than 1.

Prime n

Print itself

If no small factors exist, the leftover n is the answer.

Powers

Repeat factors

8 = 2 × 2 × 2. Keep dividing until that prime no longer divides.

√n stop

Do not skip leftover

Always print remaining n > 1 after the square-root loop.

Time and Space Complexity

ProgramTimeExtra space
Simple trialO(n)O(1)
√n trialO(√n)O(1)
Return a listO(√n)O(k) factors

Prefer the √n method in interviews. Storing factors in an array adds space proportional to the number of prime factors with multiplicity.

Key Takeaways

  • Definition: primes that multiply to n (unique up to order).
  • Method: trial division — peel small primes from n.
  • Speedup: handle 2, then odds up to √n, then leftover.
  • Test set: 84 → 2×2×3×7; 13 → 13; 100 → 2×2×5×5.

One line: divide out small primes from n; whatever is left (if > 1) is also prime.

Frequently Asked Questions

The prime numbers that multiply together to make n. For example, 84 = 2 × 2 × 3 × 7.
Trial division: peel off factor 2, then try odd candidates while dividing n. If anything greater than 1 remains, that leftover is a prime factor.
2 is the only even prime. Removing all factors of 2 first lets the rest of the loop step by 2.
The loops find no small factors, so the final leftover equals the original n and is printed once.
A simple scan up to n is O(n) in the worst case. Stopping at √n is O(√n). Extra space is O(1) aside from storing the factors you collect.
Use the Try it Yourself links under each code sample — they open an in-browser editor with the same logic so you can edit the input and Run.

Next: Prime Number

Check whether a single number is prime.

Prime number tutorial →

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