Find LCM in C

Beginner
⏱️ 10 min read
📚 Updated: Aug 2026
🎯 2 Code Examples
🚀 Live Preview
gcd & lcm

What You’ll Learn

The least common multiple is the smallest shared positive multiple of two integers. This tutorial covers the gcd–lcm identity, a safe C formula with long long, a brute multiple scan for intuition, a live preview, algorithm steps, worked C examples, edge cases, and complexity.

Definition

Smallest m

Positive m with a | m and b | m — the first shared multiple.

Identity

gcd · lcm

gcd(a,b) · lcm(a,b) = a · b for nonnegative inputs.

Safe Formula

(a/g)*b

Divide by gcd before multiplying; use long long for the product.

Brute Scan

Multiples

Step by max(a,b) until both divide — pedagogical, slower.

Live Preview

a & b

See gcd and lcm for nonnegative safe integers instantly.

Zero Rule

lcm(0,·)=0

Convention on this page: return 0 if either argument is zero.

Introduction

The least common multiple of positive integers a and b is the smallest positive integer m such that both a and b divide m. For 12 and 18, that value is 36.

In C interviews you typically implement Euclid gcd, then apply lcm = (a / gcd) * b in a wide type — mentioning overflow and the lcm(0, ·) convention.

Why it matters?

LCM shows up in scheduling, fraction arithmetic, and any problem that needs a shared period or denominator — and it is the natural follow-up once you know gcd.

Key Highlights

gcd Unlocks lcm

One identity gives a fast formula.

Divide First

(a / g) * b beats (a * b) / g in int.

long long

Widen the product when results may exceed INT_MAX.

Zero Convention

Return 0 when either input is zero.

In short: compute g = gcd(a,b), then return (a / g) * b in a wide type — or 0 if either argument is zero.

📝 Problem & Approach

Given nonnegative integers a and b, compute lcm(a,b). Prefer the gcd formula; optionally show a brute multiple scan for the same inputs.

c
/* a = 12, b = 18
 * gcd = 6
 * lcm = (12 / 6) * 18 = 2 * 18 = 36
 *
 * Multiples of 12: 12, 24, 36, ...
 * Multiples of 18: 18, 36, ...
 * First common positive multiple: 36
 */

Inputs & Outputs

ItemTypeDescription
a, bintNonnegative integers (examples use 12 and 18).
Resultlong long / intLeast common multiple (or 0 if either input is zero).

Minimal workflow

Pseudocode
function gcd(a, b):  // nonnegative
    while b != 0:
        (a, b) = (b, a mod b)
    return a

function lcm(a, b):
    if a = 0 or b = 0:
        return 0
    g = gcd(a, b)
    return (a / g) * b

Method comparison

MethodIdeaExtra space
gcd + formula(a / g) * b after EuclidO(1)
Brute scanStep by max(a,b) until both divideO(1)

⚡ Quick Reference

GoalPattern
Euclid stepnum2 = num1 % num2; num1 = temp;
Safe lcmreturn (long long)a / g * (long long)b;
Zero inputsif (a == 0 || b == 0) return 0LL;
Brute stepstep = a > b ? a : b; m += step;
Print wideprintf("%lld\\n", lcm);

📋 Formula vs Brute vs Factorization

Three ways to think about lcm — interviews almost always want the gcd formula.

gcd formula
(a/g)*b

Fast, standard interview answer

Brute scan
step max

Shows the definition; can be slow

Prime factors
max exp

Useful when factor tables already exist

Interview tip
overflow

Mention divide-first and long long

Context

When This Problem Shows Up

Reach for LCM when you need a shared multiple or period.

  1. Interview follow-up to GCD

    After Euclid, ask for lcm via the identity.

  2. Scheduling / periods

    Two events repeating every a and b units meet at lcm.

  3. Fraction denominators

    Common denominators use lcm of the bottoms.

  4. Multi-argument fold

    lcm(a,b,c) = lcm(lcm(a,b), c).

  5. Not for huge brute steps

    Prefer gcd when values can be large.

Key benefit: you get a correct lcm from a tiny Euclid loop plus one careful multiply — with a clear story about overflow.

🔮 Live Preview

Enter two nonnegative integers and see gcd and lcm (same identity as the C examples).

Try (4, 6), (0, 7), or (17, 13).

Live result
Press “Compute lcm”.

Examples Gallery

Two complete C programs — lcm from gcd with long long, and a brute multiple scan. Both use 12 and 1836. Click View Output to reveal sample console results.

📚 Getting Started

Preferred interview approach: Euclid then divide-before-multiply.

Example 1 — lcm from gcd (12, 18)

Uses long long and divides by gcd before the final multiply so the product is safer in practice.

c
#include <stdio.h>

int find_gcd(int num1, int num2) {
    while (num2 != 0) {
        int temp = num2;
        num2 = num1 % num2;
        num1 = temp;
    }
    return num1;
}

long long find_lcm_ll(int num1, int num2) {
    int g;

    if (num1 == 0 || num2 == 0) {
        return 0LL;
    }

    g = find_gcd(num1, num2);
    return (long long)num1 / g * (long long)num2;
}

int main(void) {
    int number1 = 12;
    int number2 = 18;
    long long lcm = find_lcm_ll(number1, number2);

    printf("LCM of %d and %d is: %lld\n", number1, number2, lcm);
    return 0;
}

How It Works

With g = 6, 12/6 = 2 and 2 · 18 = 36. This matches (12 · 18) / 6 = 216 / 6 without forming 12 * 18 in a narrow int first.

📈 Practical Patterns

Walk the definition along multiples of the larger input.

Example 2 — Brute Scan Along Multiples

No explicit gcd: start at max(a,b) and add the step until both divide. Same answer, slower in general.

c
#include <stdio.h>

int lcm_scan_positive(int a, int b) {
    int step;
    int m;

    if (a <= 0 || b <= 0) {
        return 0;
    }

    step = a > b ? a : b;
    m = step;

    while (m % a != 0 || m % b != 0) {
        m += step;
    }

    return m;
}

int main(void) {
    int number1 = 12;
    int number2 = 18;

    printf("LCM of %d and %d is: %d\n", number1, number2,
           lcm_scan_positive(number1, number2));
    return 0;
}

How It Works

Start at 18; it is not a multiple of 12. Add another 18 to reach 36, which both divide.

🧠 How the gcd Formula Finds lcm

1

Handle zeros

If a == 0 or b == 0, return 0 (this page’s convention).

Guard
2

Run Euclid

Replace (a,b) with (b, a % b) until the remainder is 0.

gcd
3

Divide then multiply

Compute (a / g) * b in long long.

Formula
=

lcm ready

For 12 and 18, g = 6 and lcm is 36.

🔎 Worked Walkthrough — 12 and 18

Trace Euclid, then the divide-before-multiply formula.

StepabNote
11218start Euclid
2181212 % 18 = 12 after swap pattern
312618 % 12 = 6
460gcd = 6
5(12 / 6) * 18 = 36

Check: 12 · 18 = 216 and 216 / 6 = 36 — same lcm, but the formula avoids forming 216 in a narrow int first.

Use Cases

Where LCM thinking shows up beyond the interview prompt.

1. Shared Periods

Two timers meet at the least common multiple of their cycles.

Example: events every 12 and 18 minutes meet at 36.

2. Fraction Arithmetic

Common denominators often use lcm of the bottoms.

Example: 1/12 + 1/18 needs denominator 36.

3. Overflow Awareness

Teaches divide-first and wider integer types in C.

Example: (long long)a / g * b.

4. Multi-Number Fold

Reduce an array by pairwise lcm.

Example: lcm(lcm(a,b), c).

5. Coprime Shortcut

If gcd = 1, then lcm = a * b (still widen the product).

Example: lcm(17, 13) = 221.

6. Pair with GCD Page

Reuse the same Euclid helper from the GCD tutorial.

Example: link both solutions in one interview answer.

Pro Tip: say the identity out loud — gcd · lcm = a · b — then show divide-first to prove you thought about overflow.

Advantages

Why the gcd-based approach earns interview points.

  1. 1. Algebraically Exact

    The identity guarantees the least common multiple for nonnegative inputs.

  2. 2. Fast in Practice

    Euclid is O(log min(a,b)); the formula itself is O(1).

  3. 3. Reuses GCD Code

    One helper powers both GCD and LCM interview answers.

  4. 4. Clear Overflow Story

    Divide-first plus long long shows production-minded C.

Pro Tip: mention that brute scan is fine for tiny demos but gcd is what you ship.

Usage Tips

Small habits that keep LCM code clean in interviews.

  1. 1. State Nonnegative Inputs

    Clarify the domain before coding; normalize signs if required.

  2. 2. Handle Zeros Early

    Return 0 (or your documented convention) before dividing by gcd.

  3. 3. Divide Before Multiply

    Use (a / g) * b, not (a * b) / g, in narrow integers.

  4. 4. Print with %lld

    Match long long results with the correct format specifier.

  5. 5. Test (12,18), (0,9), Coprimes

    Cover the happy path, zero rule, and gcd = 1.

Pro Tip: dry-run 12 and 18 on paper (table above) before coding — it locks in both Euclid and the formula.

Common Pitfalls

Mistakes that commonly break LCM solutions in C.

  1. 1. Multiplying in int First

    (a * b) / gcd can overflow even when the true lcm fits.

    → Use (a / g) * b and widen to long long.

  2. 2. Ignoring Zero Arguments

    Blindly dividing by gcd when an input is zero is messy and convention-dependent.

    → Return 0 early if either argument is zero (this page’s rule).

  3. 3. Trusting Brute for Large Inputs

    Stepping by max(a,b) can take a huge number of iterations.

    → Prefer the gcd formula; keep brute as a teaching demo.

  4. 4. Wrong printf Specifier

    Printing long long with %d is undefined behavior.

    → Use %lld (or cast carefully for the platform).

  5. 5. Negatives Without a Policy

    C remainder rules make naive Euclid messy on signed values.

    → Normalize with absolute values if the API promises a nonnegative lcm.

Edge Cases

Check these inputs before calling the solution done.

Happy path

(12, 18)

gcd = 6, lcm = 36.

Zero

a == 0 or b == 0

This page returns 0 for lcm; avoid dividing by a zero gcd path casually.

Coprime

(17, 13)

gcd = 1, so lcm = 17 * 13 = 221.

Brute

Scan overflow

Repeatedly adding step can exceed INT_MAX; use wider counters for large inputs.

Three+

More arguments

Fold: lcm(a,b,c) = lcm(lcm(a,b), c) (watch zeros at each step).

Sign

Negative inputs

Normalize with absolute values if your API promises a nonnegative lcm.

🔄 Sample Values

Known results for common interview inputs.

(a, b)gcdlcm
(12, 18)636
(4, 6)212
(17, 13)1221
(0, 9)90

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Read a and b from stdin

  • Use scanf and validate nonnegative inputs
  • Print lcm with %lld

2. Array fold

  • Compute lcm of an array of positive ints
  • Handle zeros with your convention

3. Overflow stress

  • Compare (a*b)/g vs (a/g)*b on large pairs
  • Explain which overflows first

4. Brute vs formula

  • Time both methods on medium inputs
  • Confirm they always match for positive pairs

Notes

  • Identity. For nonnegative a, b, gcd(a,b) · lcm(a,b) = a · b.
  • a is always divisible by gcd(a,b), so a / g is an exact integer.
  • Convention here: lcm(0, n) = lcm(n, 0) = 0.
  • Prime-factor max-exponent is another valid view when you already have factors.

Quick Takeaway: Euclid for gcd, then (a / g) * b in a wide type — and return 0 when either input is zero.

⏱️ Time and Space Complexity

MethodTimeExtra space
gcd + formulaO(log min(a,b))O(1)
Brute scanO(lcm / max(a,b)) steps worst caseO(1)

The gcd-based method dominates in practice.

Wrap Up

🎉 Conclusion

LCM is the natural partner of GCD: one identity turns Euclid into a least-common-multiple function. Prefer the divide-first formula with a wide type, and keep the brute scan only as a definition check.

Practice both examples above, then continue to leap year for another classic branching warm-up.

Compute g = gcd(a,b), then return (a / g) * b in long long — or 0 if either input is zero.

💡 Best Practices

✅ Do

  • State the gcd–lcm identity before coding
  • Divide by gcd before multiplying
  • Use long long (and %lld) for the result
  • Document the zero-argument convention
  • Test (12,18), (0,n), and a coprime pair

❌ Don’t

  • Form a * b in int first
  • Skip the zero case
  • Rely on brute scan for large inputs
  • Print long long with %d
  • Ignore signed-input remainder quirks

Key Takeaways

Knowledge Unlocked

Five things to remember about LCM in C

Compute them the interview-friendly way.

5
Core concepts
/ 02

Formula

(a / g) * b

Code
64 03

Widen

long long product

Safety
0 04

Zeros

lcm(0,·) = 0

Edge
O 05

Complexity

O(log min)

Analysis

❓ Frequently Asked Questions

The least common multiple of a and b is the smallest positive integer m such that a|m and b|m (when a and b are nonzero). It is unique for positive inputs.
For nonnegative a and b, gcd(a,b) * lcm(a,b) = a * b. Hence lcm(a,b) = a / gcd(a,b) * b, dividing before multiplying to reduce overflow risk.
Conventionally lcm(0, n) = 0 for any n, because every integer divides 0; the smallest positive multiple interpretation does not apply when one argument is 0.
Computing a * b in int can overflow before the division by gcd. Using a wider type or dividing first (as in a / g * b) avoids many practical overflows.
Definitions vary on signs; this page keeps inputs nonnegative so lcm is nonnegative.
Euclid gcd costs O(log min(a,b)) steps; lcm from gcd is O(1) after that. The brute scan can be O(lcm) steps in the worst case and is mainly pedagogical.
a is always divisible by gcd(a,b), so a / g is an exact integer. Doing that first keeps the intermediate product smaller and reduces int overflow risk.
Fold pairwise: lcm(a,b,c) = lcm(lcm(a,b), c). Handle zeros at each step with your chosen convention.

Did you Know? 🔊

For nonnegative integers a and b, gcd(a,b) · lcm(a,b) = a · b (with the convention lcm(a,0)=lcm(0,b)=0). That identity is why one small gcd loop unlocks lcm.

Continue to Leap Year

Learn how to check leap years with clear divisibility rules in C.

Leap Year tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful