1.

Write a program to calculate the Least Common Multiple (LCM) of two numbers. Example : Input : a = 10, b =15 Output : 30 a = 5, b = 7 Output : 35

Answer»

Input :
a = 10, b =15
Output :
30
a = 5, b = 7
Output :
35

Approach:

Let us assume the two numbers are a and b. Then, the two numbers have the following relationship :

 a * b = LCM(a, b) * GCD(a, b)

or,

 LCM(a, b) = (a * b) / GCD(a, b)

Let us take an example to UNDERSTAND better. For a = 10 and b = 15, a * b = 150, LCM(10, 15) = 30, GCD(10, 15) = 5. So, a * b = LCM(a, b) * GCD(a, b).

Code :

 #include <iostream>using namespace std; //Function to find the GREATEST common divisor of the two numbersint findGCD(int a,int b){ if (b == 0) return a; return findGCD(b, a % b);} // Function to return LCM of two numbersint findLCM(int a, int b){ return (a * b) / findGCD(a, b);} int MAIN(){ int a = 10, b = 15; cout <<"The Least Common Multiple of the two numbers " << a << " and " << b << " is : " << findLCM(a, b); return 0;}

Output:

 The Least Common Multiple of the two numbers 10 and 15 is : 30

Explanation: 

In the above code, the function findGCD() finds the greatest common divisor of the two numbers a and b. We use the Euclidean algorithm to find the greatest common divisor of the two numbers. The function findLCM() finds the least common multiple of the two numbers.



Discussion

No Comment Found