In this article we going to calculate LCM of two numbers using java code.
Example:- if a=10(first number), b=15(Second number) then answer=30, it is the LCM of 10 and 15.
Steps:-
- Take two inputs for a and b from the user.
- find the max of a and b and store in a variable x.
- calculate a*b and store in a variable y.
- Run a loop from i=x to i<=y.
- Inside the loop check if a and b both are divisible by i then, break the loop and i will be the answer.
Java code to find LCM of two numbers.
package gangforcode;
import java.util.*;
public class LCM {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number");
int a = sc.nextInt();
System.out.println("Enter second number");
int b = sc.nextInt();
int x=Math.max(a, b);
int y=a*b;
int ans=x;
for(int i=x;i<=y;i++) {
if(i%a==0 && i%b==0) {
ans=i;
break;
}
}System.out.println(ans);
}
}
Output:-
You can use the same logic to find the LCM of two numbers using other programming languages.