- What an LCM is, in everyday language — no textbook definition needed
- How to search for the first common multiple with a
forloop - 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.
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 search | Count up from the larger number | Up to a × b − max(a, b) | Small inputs, teaching, exam answers |
| GCD formula | Apply (a/gcd)*b | About log₂(min(a, b)) × small constant | Large 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:
i = 18— 18 % 12 = 6, not divisible → continuei = 19— 19 % 12 = 7, not divisible → continuei = 20— 20 % 12 = 8, not divisible → continue- …
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.