- Why the loop only needs to test divisors up to
√n, not up ton - How dividing out each factor as you find it shrinks
nand speeds up the loop - Why whatever remains after the loop must be prime — the key insight
- Why handling the factor 2 separately lets the loop skip all even divisors
- Why the loop is O(√n) in the worst case, not O(n)
Why √n Is Enough
The naive way to find the largest prime factor of n is to test every divisor from 2 up to n, check primality, and take the largest prime that divides n. That's O(n) just for the trial divisions, plus a primality test on each — hopeless for n = 10⁹ and worse for larger.
The key observation is this: if n is composite, it has at least one prime factor ≤ √n. Why? If n = p × q with p and q both greater than √n, then p × q > √n × √n = n, a contradiction. So every composite number has a prime factor no larger than √n. That means if we trial-divide by all numbers from 2 up to √n and find no factors, then n itself must be prime — and its largest prime factor is n itself.
But the observation gives us something stronger. Suppose n = 12. We trial-divide by 2: 12 / 2 = 6, then 6 / 2 = 3. Now n = 3, and the loop condition is d × d ≤ n with d = 3 — wait, d × d = 9 > 3, so the loop already exits. We're left with n = 3, and since n > 1, n itself is the largest prime factor. That's the trick: once you've divided out all the small factors, whatever's left is prime. You never need to test it for primality — the loop structure guarantees it.
The other trick is that 2 is the only even prime. So we divide out all factors of 2 explicitly, then start the loop at 3 and increment by 2. This halves the number of iterations. Combined with the √n bound, the loop is O(√n) in the worst case — about 31,623 iterations for n = 10⁹, not a billion.
💡 In one line: divide out 2 as many times as possible, then trial-divide by odd numbers up to √n, keeping the last prime factor you find; if n > 1 at the end, n itself is the largest prime factor.
The Trial-Division Algorithm
The standard trial-division algorithm has four phases:
- Handle small factors. While n is divisible by 2, divide it and remember 2 as the largest prime factor so far.
- Trial-divide by odd numbers. For d = 3, 5, 7, …, while d × d ≤ n, divide out every factor of d and remember d.
- Check the remainder. After the loop, if n > 1, then n is prime and is the largest prime factor.
- Print it.
In pseudocode:
largest = 1
while n % 2 == 0:
largest = 2
n = n / 2
d = 3
while d * d <= n:
while n % d == 0:
largest = d
n = n / d
d = d + 2
if n > 1:
largest = n
print largest
The nested loop structure might look a bit unusual, but it's the standard way to strip out all copies of each prime factor before moving on. Each time we divide, n gets smaller, and the loop condition d × d ≤ n is re-checked against the reduced value — so the loop exits as soon as the remaining n can't have factors larger than d.
| n | Prime factorization | Largest prime factor | Notes |
|---|---|---|---|
| 2 | 2 | 2 | Loop on 2 runs once; n becomes 1 |
| 7 | 7 | 7 | Prime — loop on 2 skipped, odd loop skipped, n > 1 at end |
| 12 | 2² × 3 | 3 | Largest = 2 initially, then 3 when odd loop finds it |
| 100 | 2² × 5² | 5 | Largest = 2 then 5 |
| 13195 | 5 × 7 × 13 × 29 | 29 | Classic Project Euler example |
| 600851475143 | 71 × 839 × 1471 × 6857 | 6857 | Project Euler #3 answer |
| 2³¹ − 1 = 2147483647 | 2147483647 (prime) | 2147483647 | Mersenne prime — loop finds no factor, n is the answer |
Complete C Program
Program: largest prime factor using a while loop
#include <stdio.h>
int main(void) {
long long n;
printf("Enter an integer (>= 2): ");
if (scanf("%lld", &n) != 1 || n < 2) {
printf("Invalid input. Enter an integer >= 2.\n");
return 1;
}
long long largest = 1;
/* Phase 1: divide out all factors of 2 */
while (n % 2 == 0) {
largest = 2;
n /= 2;
}
/* Phase 2: trial-divide by odd numbers up to sqrt(n) */
long long d = 3;
while (d * d <= n) {
while (n % d == 0) {
largest = d;
n /= d;
}
d += 2;
}
/* Phase 3: whatever remains is prime */
if (n > 1)
largest = n;
printf("Largest prime factor = %lld\n", largest);
return 0;
}
And here's a variant that also prints the full prime factorization, which is useful for tracing and for seeing the trial-division process at work:
Variant with full factorization output
#include <stdio.h>
int main(void) {
long long n;
printf("Enter N: ");
scanf("%lld", &n);
printf("%lld = ", n);
long long d = 2;
int first = 1;
long long largest = 1;
while (d * d <= n) {
while (n % d == 0) {
if (!first) printf(" * ");
printf("%lld", d);
first = 0;
largest = d;
n /= d;
}
d += (d == 2) ? 1 : 2; /* 2, 3, 5, 7, 9, ... */
}
if (n > 1) {
if (!first) printf(" * ");
printf("%lld", n);
largest = n;
}
printf("\nLargest prime factor = %lld\n", largest);
return 0;
}
The single-variant with the explicit 2-handling is the one to submit for the assignment — it's clearer and slightly faster, since it skips all even divisors. The variant is for understanding: watching the factorization build up term by term shows exactly what trial division does.
Program Output
Enter an integer (>= 2): 13195
Largest prime factor = 29
Try a few more. Input 12 and you should get 3 (12 = 2² × 3). Input 100 and you should get 5 (100 = 2² × 5²). Input 17 and you should get 17 (prime). Input 600851475143 and you should get 6857 — that's the Project Euler #3 answer, and it's a good test of the program's correctness.
Step-by-Step Explanation
Let's walk through n = 13195 and watch the trial division.
1. Reading and validating input
scanf("%lld", &n) reads a long long. The validation n < 2 rejects 0, 1, and negatives, since 1 has no prime factors (its largest prime factor is technically undefined, or 1 by convention). Using long long is important — Project Euler's example uses 600851475143, which is about 6 × 10¹¹, well beyond 32-bit int.
2. Phase 1: dividing out 2
For 13195, n % 2 = 1, so the while loop on 2 is skipped. largest stays 1. If n had been 13196 (an even number), the loop would have set largest = 2 and divided by 2 at least once before moving on. Handing 2 separately serves two purposes: it peels off the only even prime, and it lets the main loop skip all even divisors, which halves its iterations.
3. Phase 2: trial division by odd numbers
Start at d = 3. The condition d × d ≤ n controls the loop. For n = 13195:
d = 3: 13195 % 3 = 1 (since 1+3+1+9+5 = 19, not divisible by 3). Inner loop doesn't run.d = 5.d = 5: 13195 % 5 = 0, so divide: n = 2639,largest = 5. Again: 2639 % 5 = 4, stop.d = 7.d = 7: 2639 % 7 = 0 (2639 = 7 × 377), n = 377,largest = 7. 377 % 7 = 6, stop.d = 9.d = 9: 377 % 9 = 377 − 41×9 = 377 − 369 = 8. Skip.d = 11.d = 11: 377 % 11 = 3. Skip.d = 13.d = 13: 377 % 13 = 0 (13 × 29 = 377). n = 29,largest = 13. 29 % 13 = 3, stop.d = 15.d = 15:15² = 225 > 29, so the outer loop exits.
After the loop, n = 29 > 1, so largest = 29. Final answer: 29. That matches 13195 = 5 × 7 × 13 × 29.
4. Why the loop exits when d × d > n
At that point, the remaining n has no factors less than or equal to √n — otherwise the loop would have found them. By the composite argument, if n were composite, it would have a factor ≤ √n, which the loop would have tested. Since the loop found none, n is prime. That's why the final if (n > 1) largest = n; is correct: it catches the remaining prime factor, which is necessarily the largest (since all smaller factors were already divided out).
5. Why the loop is O(√n) in the worst case
The outer loop runs d from 3 to √n, incrementing by 2. That's about √n / 2 iterations. The inner loop divides out each factor, and the total number of divisions across all iterations is bounded by the number of prime factors of n, which is at most log₂(n). So the dominant cost is the outer loop: O(√n). For n = 10¹², √n = 10⁶ — a million iterations, fast on modern hardware. For n = 10¹⁸, √n = 10⁹ — about a second. This is why trial division is fine up to about 10¹⁸ but not beyond; for larger n, you need Pollard's rho or the number field sieve.
6. Why the d × d ≤ n check is important (overflow warning)
d * d <= n is safer than d <= sqrt(n) for two reasons. First, sqrt on a long long converts to double, which loses precision for values above 2⁵³; for n close to 10¹⁸, that's a real problem. Second, calling sqrt each iteration is slower than multiplying. But there's a subtle overflow risk: if d is close to the square root of LLONG_MAX, then d * d can overflow. For long long, that means d around 3 × 10⁹ — well above what this loop reaches in practice, since it exits when d * d > n ≤ LLONG_MAX ≈ 9.2 × 10¹⁸, so d ≤ 3 × 10⁹ and d * d ≤ 9.2 × 10¹⁸ < LLONG_MAX. The check is safe as long as n fits in long long.
7. Why 2 is handled separately
Without the phase-1 loop, the main loop would need to start at 2 and check every integer. That's twice as many iterations. Handling 2 separately lets the loop start at 3 and step by 2, halving the iteration count. It also simplifies the logic: after phase 1, n is odd, so no even divisor can divide it, and we don't need to test even divisors at all.
🎯 Remember this: divide out 2 first, then trial-divide by odd numbers up to √n, keeping the last factor found. Whatever remains after the loop is prime and is the answer. The loop is O(√n) — fast enough for n up to about 10¹⁸.
Frequently Asked Questions
1. Why does the loop stop at √n instead of n?
Because if n is composite, it has a prime factor ≤ √n. So once you've tested all divisors up to √n and found none that divide the remaining n, the remaining n must be prime. Testing beyond √n would be redundant — the remaining n can't have factors larger than √n that haven't already been divided out.
2. Why handle 2 separately? Can't the main loop start at 2?
It can, but it wastes iterations. Handling 2 separately lets the main loop start at 3 and increment by 2 — it only checks odd numbers. Since 2 is the only even prime, no even divisor > 2 can divide n after phase 1 (n is odd at that point). So the loop has half as many iterations. Purely an optimization; either version is correct.
3. Why does the final check use n > 1 instead of n > largest?
Because after the loop, n is either 1 (all factors were divided out) or a prime larger than any factor already found. If n > 1, it's the largest prime factor — no need to compare with largest, since largest was only set for factors less than or equal to √(original n), and the remaining n is necessarily the largest. Using n > 1 is both correct and clearer.
4. What about n = 0 or n = 1?
The program rejects them with a validation check because 1 has no prime factors (its largest prime factor is undefined) and 0 is divisible by every prime (not a meaningful question). If you want a well-defined answer for n = 1, the convention is 1 — but for the assignment, rejecting n < 2 is the cleaner choice.
5. Why does the program use long long instead of int?
Because the Project Euler example (600851475143) is about 6 × 10¹¹, which exceeds INT_MAX = 2,147,483,647. A 32-bit int would overflow and produce garbage. long long is 64 bits and handles n up to about 9.2 × 10¹⁸. For n > 10¹⁸, trial division becomes too slow, and you'd need a different algorithm (Pollard's rho, quadratic sieve, etc.) — well beyond this assignment.
6. Can I use sqrt() from <math.h> instead of d * d <= n?
You can, but it's less safe. sqrt() returns a double, which has only 53 bits of mantissa — so for n above 2⁵³ ≈ 9 × 10¹⁵, sqrt(n) loses precision and can return a value off by one, breaking the loop condition. The d * d <= n version stays in integer arithmetic and is exact. It's also faster (multiplication vs. a library call). Use the integer version.
💡 Tip: After this program, try the variant that returns the smallest prime factor instead of the largest — it's a useful step toward factoring numbers completely. Then try counting the number of distinct prime factors, which uses the same trial-division skeleton. And if you're curious about the Project Euler #3 answer, run the program with n = 600851475143 and verify it returns 6857.