Definition
Prime ÷ n
Primes that divide n evenly.
Prime factors are the prime numbers that multiply to make n. For example, 56 = 2 × 2 × 2 × 7. This tutorial covers trial division (simple and sqrt-optimized), a live factorizer, worked JavaScript examples, edge cases, and complexity.
Prime ÷ n
Primes that divide n evenly.
Peel factors
Divide out each i while it fits.
Inner while
Capture 2, 2, 2 in 56.
Fewer checks
Stop near sqrt; print leftover.
Try 56 / 360
See factors and product check.
Domain
Factorization starts at 2.
Prime factorization rewrites an integer n >= 2 as a product of primes. By the fundamental theorem of arithmetic, that product is unique up to order.
Interviews usually want trial division: try candidate divisors in increasing order, divide out each one completely, then move on. A faster variant peels 2s first, then odd candidates up to sqrt(x), and prints any leftover prime.
It is a core number-theory skill that feeds prime checks, GCD tricks, and many coding-interview warm-ups.
One prime multiset per n > 1.
Inner while for repeats.
Reject 0, 1, negatives.
Factors rise naturally.
In short: for each candidate i, divide out every copy of i; leftovers are primes.
Given an integer n >= 2, print (or return) its prime factors in non-decreasing order.
# 56 -> 2 2 2 7
# 17 -> 17 (already prime)
# 360 -> 2 2 2 3 3 5
# 1 -> invalid for this tutorial | Item | Type | Description |
|---|---|---|
n | int | Integer to factor (n >= 2). |
| Printed factors | ints | Prime multiset in ascending order. |
| Optional list | number[] | Same factors as a returned collection. |
function displayPrimeFactors(n) {
if (n < 2) {
return;
}
let x = n;
for (let i = 2; i <= x; i++) {
while (x % i === 0) {
console.log(i);
x /= i;
}
}
} | Method | Idea | Notes |
|---|---|---|
| Naive trial | Try i = 2, 3, … while i <= x | Clearest for beginners |
| Sqrt trial | Peel 2s; odds while i*i <= x | Fewer checks; leftover prime |
| Sieve helpers | Precompute primes for many n | Better for bulk queries |
| Goal | Pattern |
|---|---|
| Validate | if (n < 2) return |
| Divide out i | while (x % i === 0): …; x /= i |
| Peel twos | while (x % 2 === 0): |
| Odd candidates | i = 3; i += 2 |
| Sqrt bound | while i * i <= x: |
| Leftover prime | if (x > 1) factors.push(x) |
Same factorization — different packaging.
i <= xEasiest to dry-run
i*i <= xInterview upgrade path
append(i)Reuse factors later
order peelsComposites never survive
Reach for factorization whenever you need the prime building blocks of n.
Classic trial-division prompt.
Same divisor mindset as prime checks.
Factors explain shared primes.
Show the fundamental theorem live.
Reject 0, 1, and negatives here.
Key benefit: one nested-loop pattern that explains why composites never need an explicit is_prime helper.
Uses optimized factorization (2s first, then odd divisors) and verifies the product.
Three complete JavaScript programs — simple trial division for 56, a faster sqrt-style version, and a helper that returns factors as a list. Click View Output to reveal sample console results.
Readable nested loops that peel every factor.
Simple readable method using nested loops.
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); Starting at i = 2, the inner while removes three factors of 2, leaving 7. Then i reaches 7, which divides once, and x becomes 1.
Fewer candidates with a sqrt bound and a leftover prime.
Fewer divisor checks by handling 2 separately and testing odd candidates only.
function displayPrimeFactorsFast(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(" ")}`);
}
displayPrimeFactorsFast(56); After removing factors of 2, x is 7. Because 3 * 3 > 7, the odd loop stops and the leftover 7 is printed.
Collect factors for reuse instead of only printing them.
function primeFactors(n) {
if (n < 2) {
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);
}
return factors;
}
for (const value of [56, 17, 360]) {
console.log(`${value} -> ${JSON.stringify(primeFactors(value))}`);
} Same peeling logic as Example 2, but factors land in a list you can product-check, count, or pass to other helpers.
Factorization is undefined for smaller values here.
Start at 2 (or peel 2s, then odds).
Print/append i and shrink x each time.
(Or print leftover prime in the fast version.)
Trace the naive peel for n = 56.
| i | x before | Action | x after |
|---|---|---|---|
2 | 56 | print 2 three times | 7 |
3 … 6 | 7 | no division | 7 |
7 | 7 | print 7 once | 1 |
Result: 2 2 2 7. Product check: 2×2×2×7 = 56.
Where prime factorization shows up beyond the interview prompt.
Trial division and nested loops.
Example: factor 56.
One prime product per n > 1.
Example: facts callout.
Same divisor thinking as is_prime.
Example: next page.
Shared primes explain GCD.
Example: related GCD.
Return factors for later math.
Example: Example 3.
Sieve primes when factoring many n.
Example: notes tip.
Pro Tip: say “I’ll peel smallest factors completely so composites never need an is_prime call” before coding.
Why trial division works well for beginners and interviews.
Dry-run 56 on paper and watch x shrink.
Ascending order keeps composites from sticking.
Move from naive to sqrt when asked.
Factors emerge in non-decreasing order.
Pro Tip: start with the naive version in interviews, then offer the sqrt optimization unprompted.
Small habits that keep factorization interview-ready.
Reject invalid domains early.
Inner while captures repeated primes.
Multiply factors back to n for confidence.
Fast version must print x if x > 1.
Printing alone is fine; lists compose better.
Pro Tip: sanity-check 56, 17, and 360 — if those three match, your peel logic is solid.
Mistakes that commonly break prime-factor programs.
Printing each divisor only once.
→ Keep dividing while (x % i === 0).
Sqrt version stops and drops the last prime.
→ if x > 1: print/append x.
Undefined domain for this tutorial.
→ Require n >= 2.
x /= i can leave floats.
→ Use x /= i.
Extra prime tests slow and complicate the code.
→ Rely on ordered peeling.
Handle these before claiming factorization is complete.
0, 1, and negatives are out of scope.
Output is just n itself (e.g. 17).
Inner while must run many times.
2 2 2 7.
2 2 2 3 3 5.
Remember if x > 1 after the loop.
Handy follow-ups interviewers sometimes ask.
Try these variations to lock in the pattern.
Quick Takeaway: peel candidate factors completely in ascending order; the product of printed primes is n.
| Approach | Time | Extra space |
|---|---|---|
| Naive trial (i <= x) | O(n) worst | O(1) (+ output) |
| Sqrt trial | O(sqrt(n)) | O(1) (+ output) |
| Many queries + sieve | amortized better | depends on bound |
For interview demos, start naive; upgrade to sqrt when asked about speed.
Prime factorization rewrites n >= 2 as a unique product of primes. Peel candidates with an inner while, upgrade to a sqrt bound when needed, and always handle leftover primes in the fast path.
Practice the three examples above, then continue to checking prime numbers.
Divide out every copy of each i; the remaining primes multiply back to n.
/=isPrime callsFactor n the interview-friendly way.
primes of n
Definitionwhile % i
Loopi*i <= x
Optimizen >= 2
GuardO(√n)
AnalysisThe 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.
Learn how to check whether a number is prime in JavaScript.
8 people found this page helpful