C Program to Find the Least Common Multiple (LCM)

C Program to Find the Least Common Multiple (LCM)

Finding the Least Common Multiple, or LCM, of two numbers is a common task in mathematics and programming. The LCM of two integers is the smallest positive integer that is divisible by both numbers. Understanding how to calculate the LCM in C helps beginners learn about loops, conditions, and arithmetic operations. In this tutorial, we will cover a complete C program to find the LCM of two numbers using two methods: the traditional iterative approach and a method based on the Greatest Common Divisor (GCD).

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Calculating the LCM is useful in real-world scenarios such as finding common schedules, synchronizing cycles, or solving problems in number theory. Learning this program also reinforces key programming concepts like functions, modular arithmetic, and handling user input. By the end of this tutorial, you will understand how to implement LCM calculation in a clear and efficient way.

Method 1: Iterative Approach to Find LCM

The iterative approach finds the LCM by starting from the larger of the two numbers and checking each consecutive number to see if it is divisible by both integers. This method is straightforward and easy to understand for beginners.

#include <stdio.h>

int main() {

    int num1, num2, max, lcm;

    printf("Enter two integers: ");
    scanf("%d %d", &num1, &num2);

    max = (num1 > num2) ? num1 : num2; // Start from the larger number

    while (1) {

        if (max % num1 == 0 && max % num2 == 0) {
            lcm = max;
            break;
        }

        max++;

    }

    printf("The LCM of %d and %d is %d.\n", num1, num2, lcm);

    return 0;

}

In this program, we first take two numbers as input from the user. We determine which number is larger and start checking from that value. The while loop continues indefinitely until it finds a number divisible by both num1 and num2. Once such a number is found, we store it in the variable lcm and break the loop. Finally, we print the result. This method is simple and effective, though for very large numbers it may require more iterations.

Method 2: Using GCD to Find LCM

A more efficient method to calculate LCM uses the mathematical relationship between LCM and GCD:

$$
\text{LCM}(a, b) = \frac{|a \times b|}{\text{GCD}(a, b)}
$$

By first finding the GCD, we can calculate LCM with a single division and multiplication, which is faster than iterating through numbers.

#include <stdio.h>

int findGCD(int a, int b) {

    while (b != 0) {
    
        int temp = b;
        b = a % b;
        a = temp;
        
    }

    return a;

}

int main() {

    int num1, num2, gcd, lcm;

    printf("Enter two integers: ");
    scanf("%d %d", &num1, &num2);

    gcd = findGCD(num1, num2);
    lcm = (num1 * num2) / gcd;

    printf("The LCM of %d and %d is %d.\n", num1, num2, lcm);

    return 0;

}

In this program, we define a function findGCD that uses the iterative Euclidean algorithm to calculate the greatest common divisor of two numbers. Inside main(), we call this function to find the GCD of the input numbers. Then, we calculate the LCM by dividing the product of the two numbers by their GCD. This approach is efficient and avoids unnecessary looping, making it ideal for larger numbers.

Method 3: Calculating LCM Using Recursive GCD

We know that LCM can be calculated using the relationship:

$$
\text{LCM}(a, b) = \frac{|a \times b|}{\text{GCD}(a, b)}
$$

Instead of using an iterative method to find the GCD, we can define a recursive function to compute it. This makes the code shorter and elegant while maintaining the same logic.

#include <stdio.h>

int findGCDRecursive(int a, int b) {

    if (b == 0)
        return a;
    else
        return findGCDRecursive(b, a % b);

}

int main() {

    int num1, num2, gcd, lcm;

    printf("Enter two integers: ");
    scanf("%d %d", &num1, &num2);

    gcd = findGCDRecursive(num1, num2);
    lcm = (num1 * num2) / gcd;

    printf("The LCM of %d and %d is %d.\n", num1, num2, lcm);

    return 0;

}

In this program, the function findGCDRecursive calculates the GCD by calling itself with smaller values. The base case occurs when b equals zero, in which case the function returns a. For all other cases, the function calls itself with the parameters b and a % b, gradually reducing the problem size until it reaches the base case. In main(), we read two numbers from the user, call the recursive GCD function, and then calculate the LCM using the formula LCM = (a * b) / GCD. Finally, we print the result.

Using recursion makes the program more elegant and shows an alternative way to approach problems in C. It is especially useful for understanding algorithm design and problem decomposition. However, it is important to note that recursion uses stack memory for each function call, so for extremely large numbers, an iterative approach may be more memory-efficient.

Common Mistakes When Calculating LCM

Beginners often run into these problems when calculating the Least Common Multiple (LCM):

  • Dividing by zero or not handling zero inputs properly. Always ensure both numbers are non-zero before calculation.
  • Forgetting that the LCM should always be positive. Using absolute values avoids negative results.
  • Starting the iterative search from 1 instead of the larger input number, which makes the program slower and less efficient.

To avoid these mistakes, validate inputs carefully, use absolute values, and optimize the loop by beginning with the larger of the two numbers.

FAQs About LCM in C

Q1: Can LCM be calculated using recursion?
Yes, by first finding the GCD recursively, you can use the same formula LCM = (a * b) / GCD(a, b) to calculate LCM. Recursion helps simplify the GCD calculation, but the final LCM calculation is still a simple arithmetic operation.

Q2: Which method is better, iterative or GCD-based?
The GCD-based method is more efficient, especially for large numbers. The iterative method is easier to understand for beginners but can be slower.

Q3: What happens if one of the numbers is zero?
If either number is zero, the LCM is undefined. In practice, you should check for zero inputs and handle them appropriately.

Conclusion

Calculating the Least Common Multiple in C is a valuable exercise for learning loops, arithmetic operations, and functions. Both the iterative and GCD-based methods have their advantages. The iterative method is simple and intuitive, while the GCD-based method is more efficient and elegant. Understanding these techniques will help you solve many mathematical and programming problems efficiently. Practice these programs with different inputs to gain confidence and prepare for more advanced C programming challenges.

References & Additional Resources

  1. Kernighan, Brian W., and Dennis M. Ritchie. The C Programming Language. 2nd Edition, Prentice Hall, 1988.
  2. GeeksforGeeks – LCM of Two Numbers – Step-by-step guide to calculating the least common multiple using both naive looping and the efficient GCD-based formula.
  3. TutorialsPoint – C Programming: LCM – A classic tutorial showing the incremental (loop) method and the formula-based method for LCM in C.
  4. Programiz – C Programming: LCM Using GCD – Clear example using loops and also leveraging the GCD-to-LCM formula in C.
  5. Learn-C.org – GCD and LCM Examples – A free interactive C tutorial site, suitable for learning basics, though it may not yet include LCM-specific exercises.
Scroll to Top