C Program to Find LCM of Two Numbers

1. Introduction

The Least Common Multiple (LCM) of two integers is the smallest integer that is divisible by both of them. The LCM is frequently used in problems related to number theory, fractions, and more. This guide will demonstrate how to write a C program to find the LCM of two numbers.

2. Program Overview

1. Prompt the user to input two numbers.

2. Use the formula: LCM(a, b) = (a * b) / GCD(a, b) to determine the LCM.

3. Display the LCM of the two input numbers.

3. Code Program

#include <stdio.h>

// Function to find the GCD of two numbers
int gcd(int a, int b) {
    while(b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

// Function to find the LCM of two numbers
int lcm(int a, int b) {
    return (a * b) / gcd(a, b);
}

int main() {
    int num1, num2;

    // Asking user to input the numbers
    printf("Enter two numbers: ");
    scanf("%d %d", &num1, &num2);

    // Printing the LCM
    printf("LCM of %d and %d is: %d", num1, num2, lcm(num1, num2));

    return 0;
}

Output:

Enter two numbers: 15 20
LCM of 15 and 20 is: 60

4. Step By Step Explanation

1. The program starts by defining a function gcd that calculates the Greatest Common Divisor of two numbers.

2. A second function lcm is defined to compute the LCM using the relationship: LCM(a, b) = (a * b) / GCD(a, b).

3. In the main function, the user is prompted to input two numbers.

4. The LCM of the two input numbers is then computed by calling the lcm function.

5. The LCM is then displayed.

Comments