Write a program to find LCM of two numbers.
LCM - is the least common multiple. If the numbers are 20 and 18, then LCM of these numbers is 90.
The easiest and fastest way of finding LCM is finding GCD(greatest common divisor or highest common factor - the largest number which divides two numbers) and then dividing GCD by product of numbers.
LCM * GCD = n1 * n2
Now to find GCD we can use the following algorithm.
- If num1 is divisible by num2 return num2
- If not, return gcd of num2 and num2%num1
- set num2 = num1%num2
- set num1 = num2
- find gcd of num1 and num2 and return it.
We will write gcd as a recursive function. A recursive function is a function which calls itself. Similar to our factorial program.
int gcd(int n1,int n2){
if(n1%n2==0)
return n2;
return gcd(n2,n1%n2);
}
Here is the complete program.
import java.util.Scanner; class Demo{ int gcd(int n1,int n2){ if(n1%n2==0) return n2; return gcd(n2,n1%n2); } public static void main(String args[]){ int num1,num2; Demo obj = new Demo(); Scanner scanner = new Scanner(System.in); num1 = scanner.nextInt(); num2 = scanner.nextInt(); if(num1<num2){ int t = num1; num1 = num2; num2 = t; } int gcd = obj.gcd(num1,num2); int lcm = (num1*num2)/gcd; System.out.println("LCM of "+num1+" and "+num2+"is "+lcm); } }
Comments
Post a Comment