How to use Greatest Common Divisor In Java
Below given formula for finding the LCM of two numbers ‘u’ and ‘v’ gives an efficient solution.
u x v = LCM(u, v) * GCD (u, v)
LCM(u, v) = (u x v) / GCD(u, v)
Here, GCD is the greatest common divisor.
Below is the implementation of the above method:
// Java program to find LCM
// of two numbers.
class gfg {
// Gcd of u and v
// using recursive method
static int GCD(int u, int v)
{
if (u == 0)
return v;
return GCD(v % u, u);
}
// LCM of two numbers
static int LCM(int u, int v)
{
return (u / GCD(u, v)) * v;
}
// main method
public static void main(String[] args)
{
int u = 25, v = 15;
System.out.println("LCM of " + u + " and " + v
+ " is " + LCM(u, v));
}
}
Output
LCM of 25 and 15 is 75
Complexity of the above method:
Time Complexity: O(log(min(a,b))
Auxiliary Space: O(log(min(a,b))
Java Program to Find LCM of Two Numbers
LCM (i.e. Least Common Multiple) is the largest of the two stated numbers that can be divided by both the given numbers. In this article, we will write a program to find the LCM in Java
Contact Us