Loop Assignment 28 — Find the Largest Prime Factor Using a While Loop
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Find the Largest Prime Factor of an Integer Using a While Loop

📑 On this page:
  • Why √n Is Enough
  • The Trial-Division Algorithm
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • Why the loop only needs to test divisors up to √n, not up to n
  • How dividing out each factor as you find it shrinks n and 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.

Diagram showing 600851475143 factored as 71 × 839 × 1471 × 6857, with the largest prime factor 6857 highlighted, and the trial-division process dividing out 71 and 839 first, reducing n to 1471 × 6857 before the loop exits and the remaining factor 6857 is the answer

The Trial-Division Algorithm

The standard trial-division algorithm has four phases:

  1. Handle small factors. While n is divisible by 2, divide it and remember 2 as the largest prime factor so far.
  2. Trial-divide by odd numbers. For d = 3, 5, 7, …, while d × d ≤ n, divide out every factor of d and remember d.
  3. Check the remainder. After the loop, if n > 1, then n is prime and is the largest prime factor.
  4. 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
222Loop on 2 runs once; n becomes 1
777Prime — loop on 2 skipped, odd loop skipped, n > 1 at end
122² × 33Largest = 2 initially, then 3 when odd loop finds it
1002² × 5²5Largest = 2 then 5
131955 × 7 × 13 × 2929Classic Project Euler example
60085147514371 × 839 × 1471 × 68576857Project Euler #3 answer
2³¹ − 1 = 21474836472147483647 (prime)2147483647Mersenne 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:

  1. d = 3: 13195 % 3 = 1 (since 1+3+1+9+5 = 19, not divisible by 3). Inner loop doesn't run. d = 5.
  2. d = 5: 13195 % 5 = 0, so divide: n = 2639, largest = 5. Again: 2639 % 5 = 4, stop. d = 7.
  3. d = 7: 2639 % 7 = 0 (2639 = 7 × 377), n = 377, largest = 7. 377 % 7 = 6, stop. d = 9.
  4. d = 9: 377 % 9 = 377 − 41×9 = 377 − 369 = 8. Skip. d = 11.
  5. d = 11: 377 % 11 = 3. Skip. d = 13.
  6. d = 13: 377 % 13 = 0 (13 × 29 = 377). n = 29, largest = 13. 29 % 13 = 3, stop. d = 15.
  7. 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.

📖 Related Tutorials

  • 26. Sum of the Series 1! + 2! + 3! + … + N! Using a For Loop
  • 27. Generate First N Terms of the Tribonacci Sequence Using a While Loop
  • 29. Iterative Binary Search Using a While Loop
  • 30. Check Amicable Numbers Using a For Loop
  • 1. GCD of Two Numbers Using a While Loop (Euclidean Algorithm)
  • While Loop
  • C FOR Loop
  • All 30 Loop Assignments

Previous Topic: -->> 27. Generate First N Terms of the Tribonacci Sequence Using a While Loop   ||   Next Topic: -->> 29. Iterative Binary Search Using a While Loop


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.