Java program to find LCM of two numbers
In this program, LCM(Least common multiple) of two or more numbers is the least positive number that can be divided by both the numbers, without leaving the remainder. It is also known as Lowest common multiple, Least Common Denominator and smallest common multiple. It is denoted by LCM (a, b) or lcm (a, b) where a and b are two integers.
It is used when we add, subtract, or compare the fractions. While we perform addition or subtraction of the fractions, we find the LCM of the denominators and then solve the fraction. The LCM of the denominator is known as the Least Common Denominator (LCD).
public class Main {
public static void main(String[] args) {
int a = 72, b = 120, lcm;
lcm = (a > b) ? a : b;
while(true) {
if( lcm % a == 0 && lcm % b == 0 ) {
System.out.printf("The LCM of %d and %d is %d.", a, b, lcm);
break;
}
++lcm;
}
}
}
The LCM of 72 and 120 is 360.
In this program, we have covered different logic in java programs to find GCD of two numbers.
We have initialized two numbers n1=11 and n2=102. After that, we have used a for loop that runs from 1 to the smallest of both numbers. It executes until the condition i<=n1 && i<=n2 returns true. Inside the for loop, we have also used if statement that tests the condition (n1%i== && n2%i==0) and returns true if both conditions are satisfied. At last, we have stored the value of i in the variable gcd and print the same gcd variable.
class Main {
public static void main(String[] args) {
int n1 = 11, n2 = 102; // find GCD between n1 and n2
int gcd = 1; // initially set to gcd
for (int i = 1; i <= n1 && i <= n2; ++i) {
if (n1 % i == 0 && n2 % i == 0) // check if i perfectly divides both n1 and n2
gcd = i;
}
System.out.println("GCD of " + n1 +" and " + n2 + " is " + gcd);
}
}