Description
LCM (Least Common Multiple) of two numbers is the smallest number which can be divided by both numbers. A simple solution is to find all prime factors of both numbers, then find union of all factors present in both numbers. Finally, return the product of elements in union.
C/C++
/* C Program to find LCM(Least Common Multiple) */
//Save it as CalculateLCM.c
#include<stdio.h>
int main()
{
int firstNumber, secondNumber, maxVal;
printf("Enter first number : ");
scanf("%d",&firstNumber);
printf("Enter second number : ");
scanf("%d",&secondNumber);
maxVal = (firstNumber>secondNumber)?firstNumber:secondNumber;
while(maxVal){
if(maxVal%firstNumber == 0 && maxVal%secondNumber == 0)
{
printf("The LCM of %d and %d is %d",firstNumber,secondNumber,maxVal);
break;
}
else
{
maxVal++;
}
}
return 0;
}
Input: Enter first number : 6 Enter second number : 8 Output: The LCM of 6 and 8 is 24
Java
/* Java Program to find LCM(Least Common Multiple) */
//Save it as CalculateLCM.java
import java.io.*;
import java.util.Scanner;
public class CalculateLCM {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter first number : ");
int firstNumber = scanner.nextInt();
System.out.println("Enter second number : ");
int secondNumber = scanner.nextInt();
int maxVal;
maxVal = (firstNumber>secondNumber)?firstNumber:secondNumber;
while(true){
if(maxVal%firstNumber == 0 && maxVal%secondNumber == 0)
{
System.out.println("The LCM of "+firstNumber+" and "+secondNumber+" is "+maxVal);
break;
}
else
{
maxVal++;
}
}
}
}
Input: Enter first number : 6 Enter second number : 8 Output: The LCM of 6 and 8 is 24
Related Programs
1) Program to find HCF/GCD and LCM2) Program to find HCF using Recursion
3) Program to find factors of a Number
4) Program to calculate factorial using Recursion
5) Program to convert Binary to Hexa Decimal
6) Program to display multiplication table of a number
7) Program to reverse a number
8) Program to add two complex numbers
9) Program to calculate volume and surface area of cylinder
10) Program To Check Armstrong Number