Write a C, C++ program to find LCM of two numbers. Given a two numbers a and b, we have to write a code to find LCM of a and b.

The LCM of two numbers is the smallest number that is divisible by both numbers.

LCM(8, 16) - Least common multiple of 8 and 16 is 16.

Multiples of 8 are :

8, 16, 24, 32 .......

Multiples of 16 are :

16, 32, 48, 64 .......

Common multiples of 8 and 16 are :

16, 32, 64 ..........

So,

Formula to calculate LCM(a, b) = (a * b) / GCD(a, b)

In my previous post, i have already discussed and explained the program to find GCD of two numbers.

LCM of 3 and 5 is 15

## What is LCM (Least Common Multiple) ?

The LCM of two numbers is the smallest number that is divisible by both numbers.

__For example__-LCM(8, 16) - Least common multiple of 8 and 16 is 16.

Multiples of 8 are :

8, 16, 24, 32 .......

Multiples of 16 are :

16, 32, 48, 64 .......

Common multiples of 8 and 16 are :

16, 32, 64 ..........

So,

**the least common multiple (LCM) of 8 and 16 are 16.**

Formula to calculate LCM(a, b) = (a * b) / GCD(a, b)

In my previous post, i have already discussed and explained the program to find GCD of two numbers.

## C++ Program to Find LCM of Two Numbers

#include <iostream> using namespace std; int gcd(int a, int b) { if(b == 0){ return a; } return gcd(b , a%b); } int lcm(int a, int b) { return (a*b)/gcd(a, b); } int main() { int a, b, result; // Input cout << "Enter two numbers \n"; cin >> a >> b; // Method call to calculate LCM result = lcm(a, b); cout << " LCM of " << a << " and " << b << " is " << result; return 0; }

## C Program to Find LCM of Two Numbers

#include <stdio.h> int gcd(int a, int b) { if(b == 0){ return a; } return gcd(b , a%b); } int lcm(int a, int b) { return (a*b)/gcd(a, b); } int main() { int a, b, result; printf("Enter two numbers \n"); scanf( "%d%d", &a, &b); result = lcm(a, b); printf("LCM of %d and %d is %d", a, b, result); return 0; }

**Output :****Enter two numbers : 3, 5**

LCM of 3 and 5 is 15

## No comments:

## Post a Comment