Loop Assignment 2 — Find LCM of Two Numbers Using For Loop
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Find the LCM (Least Common Multiple) of Two Numbers Using a For Loop

📑 On this page:
  • What LCM Really Means
  • Two Ways to Compute It
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • What an LCM is, in everyday language — no textbook definition needed
  • How to search for the first common multiple with a for loop
  • Why starting from the larger number saves iterations
  • How to rewrite the program with the faster GCD-based formula
  • How to handle zero and negative inputs cleanly
  • Which version to use when — and why interviewers ask about both

What LCM Really Means

The LCM of two numbers is the smallest number that both of them divide evenly. If you've ever tried to line up two repeating events on a calendar — say a bus that comes every 12 minutes and a tram that comes every 18 minutes — you've asked for an LCM. They meet again after 36 minutes because LCM(12, 18) = 36.

That's the useful mental picture. The LCM is the shortest interval where both cycles line up again. It's always a multiple of both numbers, so it's at least as large as the bigger one. And if one number divides the other exactly, the bigger number is automatically the LCM — because it's already a multiple of the smaller one, and nothing smaller can be a multiple of itself.

The other fact worth remembering: when the two numbers share no factors in common (they're coprime, like 8 and 15), the LCM is simply their product — 120. When they do share factors, the LCM shrinks. That's the whole story, and the loop just needs to find the smallest multiple that satisfies both divisions.

💡 In one line: LCM(a, b) is the smallest number that a and b both divide with no remainder. The loop searches upward for it — or you can compute it from the GCD.

Diagram showing multiples of 12 and 18 side by side, with 36 highlighted as the first common multiple — the LCM

Two Ways to Compute It

There are two sensible approaches, and the assignment asks for the for loop version — but you should know both because interviewers ask "which is faster and why."

Method 1: Search upward (the for-loop approach)

Start i at the larger of the two numbers. Step through i = larger, larger + 1, larger + 2, …. The first value that both numbers divide evenly is the LCM. This is simple, easy to reason about, and perfectly fine for small inputs. On a large input like LCM(999, 998), though, you'd loop almost a million times before finding the answer.

Method 2: GCD formula (the fast approach)

There's a clean algebraic identity: a × b = GCD(a, b) × LCM(a, b). Rearranging gives LCM(a, b) = (a × b) / GCD(a, b). Computing the GCD with Euclid's algorithm takes about 20 iterations for any input under a billion, so this version is dramatically faster. Write it carefully to avoid overflow: divide first, then multiply. (a / gcd) * b is safer than (a * b) / gcd because the intermediate product stays small.

Approach Idea Worst-case iterations Best for
For-loop searchCount up from the larger numberUp to a × b − max(a, b)Small inputs, teaching, exam answers
GCD formulaApply (a/gcd)*bAbout log₂(min(a, b)) × small constantLarge inputs, production code, interviews

The assignment asks for the for-loop version, so that's what the main program shows. The GCD-based version appears below as a second snippet — useful for the "how could you speed this up?" follow-up question.

Complete C Program

Program: LCM using a for loop (search upward from the larger number)

#include <stdio.h>

int main(void) {
    int a, b;

    printf("Enter two integers: ");
    if (scanf("%d %d", &a, &b) != 2) {
        printf("Invalid input.\n");
        return 1;
    }

    /* Work with positive values — LCM is defined for non-negatives */
    if (a < 0) a = -a;
    if (b < 0) b = -b;

    /* LCM with any zero is defined as zero */
    if (a == 0 || b == 0) {
        printf("LCM = 0\n");
        return 0;
    }

    /* Start from the larger number — nothing smaller can be a common multiple */
    int start = (a > b) ? a : b;

    int lcm = 0;
    for (int i = start; ; i++) {
        if (i % a == 0 && i % b == 0) {
            lcm = i;
            break;
        }
    }

    printf("LCM = %d\n", lcm);
    return 0;
}
                                    

And here is the faster version using the GCD formula. It's shorter, it runs in almost constant time, and it avoids the risk of a very long loop:

Same LCM, using the GCD formula (fast version)

/* Returns the GCD of two positive integers */
int gcd(int x, int y) {
    while (y != 0) {
        int r = x % y;
        x = y;
        y = r;
    }
    return x;
}

/* LCM via the identity LCM = (a / gcd) * b — divide first to avoid overflow */
int lcm_via_gcd(int a, int b) {
    return (a / gcd(a, b)) * b;
}
                                    

The two versions always produce the same answer. The for-loop one is the one to write in an exam that specifies "using a for loop," but in real code the GCD formula wins comfortably. If you want a third variation, you can also step by the larger number rather than by 1 — that halves (or better) the iteration count when one input is much bigger than the other.

Program Output

Enter two integers: 12 18
LCM = 36
                                

A few more to try by hand: 4 and 6 give 12. 5 and 7 give 35 (they're coprime). 9 and 18 give 18, because 18 already divides 9 times. 0 and any number give 0. Try one of those after you finish reading, and trace the loop on paper — it's the fastest way to make sure the logic sticks.

Step-by-Step Explanation

Let's walk through the 12 and 18 case, then look at the parts that trip people up.

1. Reading input safely

scanf("%d %d", &a, &b) returns the number of values it read successfully. Checking for exactly 2 protects the program from letters, empty input, or a partial read. Without that check, an input like "12 abc" would leave b uninitialised, and the program would compute nonsense.

2. Absolute values and the zero case

The LCM is usually defined only for positive integers. If either input is negative, we flip it to positive — the LCM is the same for 12 and 18 as it is for −12 and 18. If either input is zero, the LCM is defined as 0, because 0 is the only common multiple (no positive number is a multiple of 0). Returning 0 early avoids the infinite loop that would otherwise occur: the loop would start at the larger number and never find a value divisible by 0.

3. Why start at the larger number?

Any common multiple must be a multiple of both inputs, so it can't be smaller than either one. If a = 12 and b = 18, any common multiple is at least 18. Starting at 1 would waste 17 iterations on values that are guaranteed to fail. The start = (a > b) ? a : b line picks the larger one.

4. The for loop

The loop has no termination condition in its header — it reads for (int i = start; ; i++). That looks unusual, but it's fine because the body contains a break that fires as soon as i is divisible by both inputs. A common alternative is to declare lcm = 0 before the loop and use it as a flag. Both work; the version with the unconditional header is easier to read because the check lives right next to the action it enables.

For 12 and 18:

  1. i = 18 — 18 % 12 = 6, not divisible → continue
  2. i = 19 — 19 % 12 = 7, not divisible → continue
  3. i = 20 — 20 % 12 = 8, not divisible → continue
  4. …
  5. i = 36 — 36 % 12 = 0 and 36 % 18 = 0 → break, LCM = 36

The loop runs 19 times in total (from 18 to 36, inclusive). That's fine for these values, but imagine a = 999 and b = 998 (coprime). The loop would run 999 × 998 ≈ 997,000 iterations before finding the answer. That's why the GCD formula exists.

5. Why step by 1 when you could step by max(a, b)?

Good question, and worth trying. The LCM is a multiple of the larger number, so you could write for (i = start; ; i += start) and only check multiples of the larger one. For 12 and 18, that means checking 18, 36 — two iterations instead of 19. The downside is that if start is very large, the intermediate products can overflow int faster than you'd expect. The single-step version is slower but safer. Choose based on whether you know the input range.

6. The GCD formula — why it works

The identity a × b = GCD(a, b) × LCM(a, b) comes straight from the prime factorisations. Each prime appears in a × b with a total exponent equal to the sum of exponents in a and b. On the right side, the GCD takes the minimum of those two exponents and the LCM takes the maximum — min plus max equals sum, so the two sides are equal. Rearranging gives the LCM. That's the whole proof, but the important practical point is: computing GCD with Euclid takes only a handful of steps, so the whole LCM computation is fast.

7. Why divide before multiplying

(a * b) / gcd(a, b) and (a / gcd(a, b)) * b are mathematically identical, but they don't overflow at the same point. If a = 1,000,000 and b = 1,000,000, then a * b = 10^12, which doesn't fit in a 32-bit int (max about 2.1 × 10⁹). Dividing first by the GCD, which is 1,000,000 here, gives 1,000,000 / 1,000,000 = 1, then 1 * 1,000,000 = 1,000,000 — well within range. Same answer, no overflow. This is a habit worth forming early.

🎯 Remember this: LCM(a, b) is the smallest number both inputs divide. Search upward from the larger one with a for loop — that's the assignment. But keep the GCD formula close: (a / gcd) * b. It's shorter, faster, and divide-before-multiply keeps it safe from overflow.

Frequently Asked Questions

1. Why does the loop start at the larger number and not at 1?

Because the LCM is a multiple of both inputs, so it can't be smaller than either. For 12 and 18, any common multiple is at least 18, so starting from 1 would waste 17 checks. Starting from the larger number is the cheapest correct starting point — and it's the trick most interviews are testing when they ask you to write this program.

2. Why is the loop written as for (int i = start; ; i++) with no second part?

Because the loop breaks from inside the body when it finds the answer. The empty middle section means "no automatic termination condition" — the break is the only way out. It's valid C and it's clearer than putting a complex condition in the header, because the check lives right beside the break it triggers. If you prefer the header form, for (i = start; !(i % a == 0 && i % b == 0); i++) does the same thing, but it's harder to read.

3. What is the LCM of 0 and 0?

By the convention used in almost every textbook and standard library, LCM(0, 0) = 0. In practice, the LCM of zero and anything is 0 — because zero is a multiple of every number, and every number is a multiple of zero only in the degenerate sense that 0 = k × 0. The important practical point is that the loop would never terminate if either input were 0 and we didn't handle it early, which is why the program returns 0 before reaching the loop.

4. Can I use the GCD formula instead of the loop?

Yes — and in real code you probably should. The GCD formula is roughly O(log n) vs the loop's O(a × b), which is an enormous difference for large inputs. But the assignment asks specifically for a for loop, and interviewers often ask both. Write the loop version when the question says "using a for loop," and mention the GCD formula as a follow-up to show you understand the trade-off. That said, if you only remember one, remember the GCD formula — it's the version you'll actually use.

5. What if the two numbers are very large? Will the loop overflow?

The loop variable i is an int, so it can hold up to about 2.1 billion. If the LCM of your two inputs exceeds that, i will overflow into negative territory and the loop will go haywire. For inputs where you suspect the LCM could exceed int (say, both inputs are around 50,000), use long long for i and the % checks. Or use the GCD formula with long long — it almost never overflows for realistic inputs.

6. Where is LCM used in real programs?

Adding fractions with different denominators, synchronising repeating events (like the bus-and-tram example), finding the smallest canvas size that fits repeated tiles, computing the period of a repeating pattern, aligning memory buffers to a common size, and — in cryptography — computing modulo inverses. Whenever two cycles or tiles need to line up, the LCM is the number you want.

💡 Tip: Once this clicks, go back to the GCD program and compare the two. The GCD one uses a % b to shrink the pair; this one uses i % a and i % b to test candidates. They feel different, but they're both counting on the same fact — that "divides evenly" is a reliable, cheap test. The next assignment (coprime check) is a two-line modification of this one.

📖 Related Tutorials

  • 1. Find the GCD of Two Numbers Using a While Loop
  • 3. Check Whether Two Numbers Are Coprime Using a While Loop
  • 4. Find All Common Divisors of Two Numbers Using a For Loop
  • 5. GCD of Three Numbers Using Nested Loops
  • 30. Check Whether Two Integers Are Amicable Using a For Loop
  • C FOR Loop
  • While Loop
  • All 30 Loop Assignments

Previous Topic: -->> 1. Find the GCD of Two Numbers Using a While Loop   ||   Next Topic: -->> 3. Check Whether Two Numbers Are Coprime 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.