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 C++ 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 vector | std::vector<int> | Same factors as a returned collection. |
procedure display_prime_factors(n):
if n < 2:
stop
x = n
for i from 2 while i <= x:
while x mod i == 0:
output i
x = 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 ((long) i * i <= x) |
| Leftover prime | if (x > 1) std::cout << x; |
Same factorization — different packaging.
i <= xEasiest to dry-run
i*i <= xInterview upgrade path
factors.Add(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 C++ programs — simple trial division for 56, a faster sqrt-style version, and a helper that returns factors as a vector. Click View Output to reveal sample console results.
Readable nested loops that peel every factor.
Simple readable function using nested loops.
#include <iostream>
bool dividesEvenly(int a, int b) {
return a % b == 0;
}
void displayPrimeFactors(int n) {
if (n < 2) {
std::cout << "Enter an integer n >= 2 (got " << n << ").\n";
return;
}
std::cout << "Prime factors of " << n << " are: ";
int x = n;
int i = 2;
while (i <= x) {
while (dividesEvenly(x, i)) {
std::cout << i << " ";
x /= i;
}
i++;
}
std::cout << "\n";
}
int main() {
displayPrimeFactors(56);
return 0;
} 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.
#include <iostream>
void displayPrimeFactorsFast(int n) {
if (n < 2) {
std::cout << "Enter an integer n >= 2 (got " << n << ").\n";
return;
}
std::cout << "Prime factors of " << n << " are: ";
int x = n;
while (x % 2 == 0) {
std::cout << "2 ";
x /= 2;
}
int i = 3;
while ((long long) i * i <= x) {
while (x % i == 0) {
std::cout << i << " ";
x /= i;
}
i += 2;
}
if (x > 1) {
std::cout << x << " ";
}
std::cout << "\n";
}
int main() {
displayPrimeFactorsFast(56);
return 0;
} 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.
#include <iostream>
#include <vector>
#include <string>
std::vector<int> primeFactors(int n) {
std::vector<int> factors;
if (n < 2) {
return factors;
}
int x = n;
while (x % 2 == 0) {
factors.push_back(2);
x /= 2;
}
int i = 3;
while ((long long) i * i <= x) {
while (x % i == 0) {
factors.push_back(i);
x /= i;
}
i += 2;
}
if (x > 1) {
factors.push_back(x);
}
return factors;
}
std::string joinFactors(const std::vector<int>& factors) {
std::string out;
for (size_t i = 0; i < factors.size(); i++) {
if (i > 0) {
out += ", ";
}
out += std::to_string(factors[i]);
}
return out;
}
int main() {
int values[] = { 56, 17, 360 };
int count = sizeof(values) / sizeof(values[0]);
for (int i = 0; i < count; i++) {
int value = values[i];
std::cout << value << " -> [" << joinFactors(primeFactors(value)) << "]\n";
}
return 0;
} Same peeling logic as Example 2, but factors land in a vector 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; vectors 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.
Casting to double can leave non-integers and break later checks.
→ Keep x and i as int/long so /= is integer division.
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.
long for large n so i * i does not overflow.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)
AnalysisEvery integer greater than 1 can be written as a product of primes in exactly one way (ignoring order).
Learn how to check whether a number is prime in C++.
8 people found this page helpful