Q23. Write a code to find LCM of two numbers.
LCM :- LCM (Least Common Multiple) of numbers is defined as the smallest possible multiple of two or more numbers.
For Example :-
Input = 6 and 5
Output = 30 is the LCM.
As we can see 30 is the smallest possible multiple of 6 and 5 therefore, 30 is the least common multiple (LCM) of two numbers 6 and 5
Algorithm For LCM
START
Step 1 → Initialize num1 and num2 with positive integers
Step 2 → Store maximum of num1 & num2 to max
Step 3 → Check if max is divisible by num1 and num2
Step 4 → If divisible, Display max as LCM
Step 5 → If not divisible then increase max by 1 and then goto step 3
STOP
Code For LCM
#include <stdio.h>
int main()
{
int num1=5, num2=6, max;
max = (num1 > num2) ? num1 : num2;
while (1) {
if (max % num1 == 0 && max % num2 == 0) {
printf(“The LCM of %d and %d is %d.”, num1, num2, max);
break;
}
max++;
}
return 0;
}
#include <bits/stdc++.h>
using namespace std;
int main()
{
int num1=6, num2=5, max;
max = (num1 > num2) ? num1 : num2;
while (1) {
if (max % num1 == 0 && max % num2 == 0) {
cout << “LCM of “<< num1<<” and “<< num2<<” is “<< max;
break;
}
max++;
}
return 0;
}
public class LFC {
public static void main(String[] args) {
int num1 = 6, num2 = 5, max;
max = (num1 > num2) ? num1 : num2;
while(true) {
if( max % num1 == 0 && max % num2 == 0 ) {
System.out.printf(“The LCM of %d and %d is %d.”, num1, num2, max);
break;
}
max++;
}
}
}
num1 = 6
num2 = 5
if num1 > num2:
max = num1
else:
max = num2
while(True):
if((max % num1 == 0) and (max % num2 == 0)):
break
max += 1
print(“The LCM of given number is “, max)
$num1 = 6;
$num2 = 5;
$max = 0;
$max = $num1 > $num2 ? $num1 : $num2;
while (1) {
if ($max % $num1 == 0 && $max % $num2 == 0) {
echo “The LCM of the {$num1} and {$num2} numbers is {$max}.”;
break;
}
++$max;
}
Output
LCM of 5 and 6 is 30
Recommended Programs
Program to find factorial of a number
Program to count number of digits in a number