Function Assignment 8 — Find the LCM (Least Common Multiple) of Two Numbers Using a Function
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

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

📑 On this page:
  • What is the LCM?
  • The GCD-based formula — and why it works
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • What the LCM is and how it relates to the GCD
  • How to compute the LCM efficiently using the formula (a / gcd(a, b)) × b
  • Why dividing before multiplying avoids integer overflow
  • Why the naive "loop up to a × b" approach is slow
  • How to build a program with two mutually-reinforcing functions

What is the LCM?

The least common multiple of two positive integers a and b is the smallest positive integer that's a multiple of both. For example, lcm(4, 6) = 12 because 12 is the smallest number divisible by both 4 and 6. Likewise, lcm(12, 18) = 36, lcm(5, 7) = 35 (since 5 and 7 are coprime — no common factors), and lcm(10, 15) = 30.

The LCM shows up wherever you need to combine two periodic events — adding fractions with different denominators, scheduling two processes that run at different intervals, or finding the smallest common unit between two measurement systems. Anywhere you'd think "when do these two things line up again?" — that's the LCM at work.

The naive way to compute it is to loop through multiples of the larger number until you find one divisible by the smaller. That works, but it's O(lcm(a, b)) — which for coprime inputs can be as large as a × b. For lcm(999, 1000), that's 999,000 iterations. There's a much better way: use the GCD. The identity is lcm(a, b) = (a × b) / gcd(a, b). Since we already have a fast GCD (Euclidean, O(log min(a, b))), the LCM becomes O(log min(a, b)) too. That's an enormous speedup for a one-line change.

This assignment is really about two functions working together — gcd and lcm — where each one is small, testable, and reusable. It's a great example of how factoring a problem into small functions compounds: once you have a fast GCD, everything built on top of it becomes fast too.

💡 In one line: implement gcd (Euclidean algorithm), then write lcm(a, b) { return (a / gcd(a, b)) * b; }. Divide first, multiply second — that order avoids overflow and gives the right answer.

Two periodic sequences with different periods; the LCM is the point where they line up again.

The GCD-based formula — and why it works

The formula is:

lcm(a, b) = (a × b) / gcd(a, b)
                                

This identity has been known for over two thousand years, and it's one of the most useful relationships in elementary number theory. Here's the intuition: every prime factor of a and b appears in both a × b and in lcm(a, b), but with a different exponent. In lcm(a, b), the exponent is the maximum of the two exponents; in gcd(a, b), it's the minimum. When you multiply the LCM by the GCD, you add the max and min — which is exactly the sum of the two exponents in a × b. So the product is equal, and the identity follows.

Let's check it with a concrete example. Take a = 12 = 2² × 3 and b = 18 = 2 × 3².

Quantity Value Prime factorization
a = 12122² × 3¹
b = 18182¹ × 3²
a × b2162³ × 3³
gcd(a, b)62¹ × 3¹
lcm(a, b)362² × 3²
gcd × lcm2162³ × 3³

Notice how the exponents add up: for prime 2, gcd has exponent 1 and lcm has exponent 2; their sum is 3, which matches the exponent of 2 in a × b. Same for prime 3. So gcd(a, b) × lcm(a, b) = a × b, which rearranges to the LCM formula.

The important engineering subtlety is how you write the formula in code. If you write (a * b) / gcd(a, b), the multiplication a × b happens first, and for inputs near the limit of int (around 2 billion), the product can overflow before you ever divide. For example, a = b = 46341 gives a × b = 2,147,488,281, which is one over INT_MAX — and overflows to a negative number. The result is garbage.

The fix is to divide first: (a / gcd(a, b)) * b. Since gcd(a, b) divides a exactly (by definition), the division is exact — no truncation, no remainder — and the result is a / gcd(a, b). Then you multiply by b, which produces the LCM. The intermediate value never exceeds b × (a / gcd), which is bounded by the actual LCM, so you don't overflow unless the LCM itself doesn't fit in an int. That's the best you can do with int — for larger results, you'd use long long or a bignum library.

🎯 Overflow trap: write (a / gcd(a, b)) * b, not (a * b) / gcd(a, b). Both are mathematically equivalent, but the first avoids overflow. This is one of those "details that matter" — a difference of just the order of operations, but the consequences are real for large inputs.

Complete C Program

Program: GCD + LCM, iterative

#include <stdio.h>
#include <stdlib.h>

/* Function prototypes */
int gcd(int a, int b);
int lcm(int a, int b);

int main(void) {
    int a, b;

    printf("Enter two positive integers: ");
    scanf("%d %d", &a, &b);

    if (a <= 0 || b <= 0) {
        printf("Please enter positive integers.\n");
        return 1;
    }

    printf("GCD of %d and %d is %d\n", a, b, gcd(a, b));
    printf("LCM of %d and %d is %d\n", a, b, lcm(a, b));

    return 0;
}

/* Euclidean algorithm */
int gcd(int a, int b) {
    a = abs(a);
    b = abs(b);
    while (b != 0) {
        int r = a % b;
        a = b;
        b = r;
    }
    return a;
}

/* LCM via GCD — divide first to avoid overflow */
int lcm(int a, int b) {
    if (a == 0 || b == 0) return 0;
    return (a / gcd(a, b)) * b;
}
                                    

And here's a version that uses long long so the LCM can exceed INT_MAX — useful when the inputs are large:

Variant: long long version

#include <stdio.h>
#include <stdlib.h>

long long gcd(long long a, long long b) {
    a = llabs(a);
    b = llabs(b);
    while (b != 0) {
        long long r = a % b;
        a = b;
        b = r;
    }
    return a;
}

long long lcm(long long a, long long b) {
    if (a == 0 || b == 0) return 0;
    return (a / gcd(a, b)) * b;
}

int main(void) {
    long long a, b;
    printf("Enter two positive integers: ");
    scanf("%lld %lld", &a, &b);
    printf("GCD = %lld\n", gcd(a, b));
    printf("LCM = %lld\n", lcm(a, b));
    return 0;
}
                                    

With long long, the maximum LCM is about 9.22 × 10¹⁸ — enough for most real-world uses. If you needed to go further, you'd need a bignum library, but that's a different topic. For the purposes of this assignment, long long is the "production-grade" version, and int is the "learning" version.

And a version that goes to great lengths to avoid abs/llabs includes and uses inline negation — a valid alternative that avoids a library dependency:

Variant: no <stdlib.h> needed

#include <stdio.h>

int gcd(int a, int b) {
    if (a < 0) a = -a;
    if (b < 0) b = -b;
    while (b != 0) {
        int r = a % b;
        a = b;
        b = r;
    }
    return a;
}

int lcm(int a, int b) {
    if (a == 0 || b == 0) return 0;
    int g = gcd(a, b);
    /* Sign handling for potentially negative inputs */
    if (a < 0) a = -a;
    if (b < 0) b = -b;
    return (a / g) * b;
}

int main(void) {
    int a, b;
    printf("Enter two integers: ");
    scanf("%d %d", &a, &b);
    printf("LCM = %d\n", lcm(a, b));
    return 0;
}
                                    

This version makes the sign handling explicit, which some people find clearer than relying on abs. Both work; pick whichever reads better to you.

Program Output

A typical run:

Enter two positive integers: 12 18
GCD of 12 and 18 is 6
LCM of 12 and 18 is 36
                                

With coprime numbers (no common factors):

Enter two positive integers: 5 7
GCD of 5 and 7 is 1
LCM of 5 and 7 is 35
                                

When one number divides the other:

Enter two positive integers: 4 12
GCD of 4 and 12 is 4
LCM of 4 and 12 is 12
                                

With equal numbers:

Enter two positive integers: 9 9
GCD of 9 and 9 is 9
LCM of 9 and 9 is 9
                                

With larger inputs:

Enter two positive integers: 100 250
GCD of 100 and 250 is 50
LCM of 100 and 250 is 500
                                

Notice the pattern: when a divides b, gcd = a and lcm = b. When a and b are equal, both GCD and LCM equal a. These are useful sanity checks — if your function returns anything else for those cases, something's wrong.

Step-by-Step Explanation

Let's look at the two functions and trace through an example.

1. The gcd function

This is the same Euclidean algorithm from assignment 7. Two abs calls to normalize signs, then the while loop that reduces the pair until b = 0, returning a. If you've already implemented gcd for that assignment, you can copy it here verbatim — that's the benefit of a well-designed function. It's a reusable building block.

2. The lcm function

The body is one line after the guard: return (a / gcd(a, b)) * b;. Let's unpack the operation order:

  1. gcd(a, b) is computed — say, 6 for inputs 12 and 18.
  2. a / gcd(a, b) — 12 / 6 = 2. This is the exact division we need.
  3. 2 * b — 2 * 18 = 36. That's the LCM. ✓

The guard if (a == 0 || b == 0) return 0; handles the case where one input is zero. The LCM of 0 and anything is conventionally 0 (since 0 is a multiple of everything, but no positive multiple of 0 is well-defined). Without the guard, gcd(0, b) returns b, and the division 0 / b is 0, so 0 * b = 0 anyway — but the guard makes the intent explicit and avoids a useless gcd computation.

3. Tracing lcm(12, 18)

  1. Call gcd(12, 18):
    • a = 12, b = 18, r = 12 % 18 = 12. New pair: (18, 12).
    • a = 18, b = 12, r = 18 % 12 = 6. New pair: (12, 6).
    • a = 12, b = 6, r = 12 % 6 = 0. New pair: (6, 0).
    • b = 0, loop ends. Return 6.
  2. Compute 12 / 6 = 2.
  3. Compute 2 * 18 = 36.
  4. Return 36. ✓

4. Why divide before multiply?

Let's see what happens if we use the other order. For a = 46341, b = 46341:

  1. a * b = 46341 × 46341 = 2,147,488,281.
  2. This is INT_MAX + 34, so it overflows to -2,147,479,015 (on a two's-complement system).
  3. The subsequent division by gcd = 46341 gives -46341 — a nonsense answer.

With the correct order:

  1. a / gcd(a, b) = 46341 / 46341 = 1.
  2. 1 * b = 1 × 46341 = 46341. ✓

The intermediate value stayed bounded, no overflow. The correctness of (a / g) * b = (a * b) / g relies on g dividing a exactly — which is guaranteed by the definition of GCD. So dividing first is always safe, and it's always the right choice when overflow is a concern.

5. The relationship to fractions

Adding two fractions like 3/8 + 5/12 requires a common denominator — which is typically the LCM of the denominators. lcm(8, 12) = 24, so 3/8 + 5/12 = 9/24 + 10/24 = 19/24. If you used a × b as the common denominator (96 in this case), you'd get 36/96 + 40/96 = 76/96 = 19/24 — the same answer, but with much larger intermediate values. Using the LCM keeps the numbers small and reduces the risk of overflow. That's the practical payoff of the GCD/LCM pair.

6. The naive alternative

You could compute the LCM by looping:

int lcm_slow(int a, int b) {
    int max = (a > b) ? a : b;
    int candidate = max;
    while (1) {
        if (candidate % a == 0 && candidate % b == 0) return candidate;
        candidate += max;
    }
}
                                

This works, but it does O(lcm(a, b) / max(a, b)) iterations. For lcm(999, 1000) = 999000, that's 999 iterations of a loop with two modulo operations each — around 2,000 operations. The GCD-based version does about 30 operations (log₂(1000) iterations of Euclid) plus one division and one multiplication. That's roughly 60× faster. For larger coprime inputs, the gap grows. The GCD-based version is always the right answer.

7. Why a × b = gcd × lcm matters

This identity — a × b = gcd(a, b) × lcm(a, b) — is not just a way to compute the LCM. It's a fundamental relationship that shows up in modular arithmetic, ring theory, and cryptography. In modular arithmetic, the pair (gcd, lcm) characterizes the intersection and union of the subgroups generated by a and b — a deep fact that underlies many cryptographic protocols. Knowing the identity by heart is useful in itself; understanding why it holds is the gateway to more advanced number theory.

8. Handling zero and negative inputs

The LCM is defined for positive integers. For zero, the LCM is conventionally 0 (some definitions say it's undefined, since 0 has no positive multiples). For negatives, the LCM is usually taken to be the same as for absolute values — lcm(-4, 6) = 12, not -12. Our implementation handles both: the gcd function takes absolute values internally, and the guard if (a == 0 || b == 0) return 0; catches zeros before any division happens. For negative inputs, the division a / gcd(a, b) might be negative, but the final multiplication by b (if positive) restores a positive result. If both a and b are negative, the result is also negative — which is unconventional but rarely encountered. For a stricter handling, take absolute values at the top of lcm too.

🔍 Try this: temporarily change (a / gcd(a, b)) * b to (a * b) / gcd(a, b) and run with 46341 46341. The output will be negative or otherwise garbled due to overflow. Then change it back and run again — the answer is 46341 (since a × b / gcd = a² / a = a). This is the most direct way to see why the order of operations matters.

Frequently Asked Questions

1. Why is lcm(a, b) = (a × b) / gcd(a, b)?

Because every prime factor appears in a with some exponent and in b with another exponent. In the GCD, the exponent is the minimum; in the LCM, it's the maximum. The sum of max and min equals the sum of the two exponents — which is what you get when you multiply a and b. So gcd × lcm = a × b, and rearranging gives the formula. The identity is one of the most elegant in elementary number theory.

2. Why divide before multiplying?

To avoid integer overflow. If you multiply first, a × b can exceed INT_MAX even when the actual LCM fits comfortably in an int. Dividing first (a / gcd(a, b)) keeps the intermediate value small, since a / gcd is at most a. Both orderings are mathematically equivalent, but only one is safe for large inputs. For 32-bit int, a × b overflows when both are greater than about 46,341 — which is not a large number by modern standards.

3. What is lcm(a, 0)?

By convention, 0. Since every positive integer is a multiple of 0 in the trivial sense (0 × any integer = 0), the "smallest positive multiple" doesn't really exist, but the LCM is usually taken to be 0 for arithmetic consistency. Some definitions say it's undefined; either interpretation is defensible. Our function returns 0 to avoid division by zero and to keep the behavior consistent.

4. Can I compute LCM for three or more numbers?

Yes, by folding: lcm(a, b, c) = lcm(lcm(a, b), c). The LCM is associative, so you can iterate over an array: result = arr[0]; for (i = 1; i < n; i++) result = lcm(result, arr[i]);. This works because the LCM of a set of numbers is the LCM of the pairwise LCMs — a fact that follows from the prime factor definition (max of exponents is associative). You'll see this in problems involving scheduling or combining fractions.

5. How do I compute the LCM of two fractions?

The LCM of fractions isn't generally defined — you're more likely looking for the LCD (Least Common Denominator), which is lcm(denominator1, denominator2). To add a/b + c/d, find L = lcm(b, d), then compute (a × L/b + c × L/d) / L. For example, 3/8 + 5/12: lcm(8, 12) = 24, so (3 × 3 + 5 × 2) / 24 = (9 + 10) / 24 = 19/24. The GCD is also useful here — simplifying 19/24 requires checking if gcd(19, 24) == 1, which it does, so the fraction is already in lowest terms.

6. What's the fastest way to compute LCM?

The GCD-based formula is essentially the fastest simple method — O(log min(a, b)) operations. For extremely large numbers (hundreds of digits), you'd use a bignum library, but the algorithm is the same. There's no meaningful way to compute the LCM faster than computing the GCD, because the two are mathematically equivalent in complexity — the gcd × lcm = a × b identity ties their complexities together. So any advance in GCD algorithms (like the binary GCD, or the half-GCD for bignums) automatically transfers to LCM.

💡 Tip: Once this works, try solving the classic "train problem": one train leaves every 8 minutes, another every 12. When do they next depart together? That's lcm(8, 12) = 24 minutes. Then write a program that takes the periods of N trains and finds the next simultaneous departure — that's the LCM fold over an array. The pattern generalizes naturally, and the code is barely more than the two-function version.

📖 Related Tutorials

  • Introduction to Functions in C
  • Recursion in C
  • Function Definition
  • Function Declaration
  • Types of Functions
  • Previous: GCD of Two Numbers Using a Function
  • All 33 Function Assignments

Previous Topic: -->> 7. Find the GCD (Greatest Common Divisor) of Two Numbers Using a Function   ||   Next Topic: -->> 9. Swap Two Numbers Using a Function


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.