Lcm of two numbers in C
×


Lcm of two numbers in C

177

 The C program calculates the LCM (Least Common Multiple) of two given numbers using a combination of the Greatest Common Divisor (GCD) and a formula.

 LCM is the smallest positive integer that is divisible by both numbers without leaving a remainder.

The program employs the formula: ​

The GCD is calculated using the Euclidean algorithm, and then the LCM is computed using the formula.


Example:

Given two numbers: 12 and 15

Step 1: Calculate GCD using the Euclidean algorithm

GCD(12, 15) = GCD(15, 12 % 15)
= GCD(15, 12)
= GCD(12, 3)
= GCD(3, 0)
= 3

Step 2: Calculate LCM using the formula

LCM(12, 15) = (12 * 15) / 3
= 180 / 3
= 60
// Program to calculate LCM of two numbers
#include<stdio.h>

// Function to calculate GCD (Greatest Common Divisor)
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}

// Function to calculate LCM (Least Common Multiple)
int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}

int main() {
int A1 = 12, A2 = 15; // Example numbers
int result;

result = lcm(A1, A2);

printf("LCM of %d and %d is %d\n", A1, A2, result);

return 0;
}

Output:

LCM of 12 and 15 is 60

The gcd function calculates the Greatest Common Divisor of two numbers using the Euclidean algorithm.

The lcm function calculates the LCM using the formula:

In the main function, two example numbers (12 and 15) are used to demonstrate the LCM calculation.

The calculated LCM is then displayed to the user.



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments