Unfortunately, this is not a very good implementation of finding the Greatest Common Divisor (GCD). I suggest you look up Euclid's method on WikiPedia.
The way the above works is the program continues to divide both numbers by increasing values of i
starting with 1. When both a
and b
are divisible by i
, i
is assigned to hcf
and the loop continues until i
exceeds the larger of a
and b
. The last assignment to hcf
is the GCD.
The Least Common Multiple (LCM) is the smallest number that is divisible by both a
and b
and is computed mathematically as the product of a
and b
divided by their greatest common divisor.
The %
sign in java means for a % i
get the remainder. So if the remainder of both a
and b
when divided by i
is zero, then i
would be the GCD.
Updated Answer
Although I don't like the above approach, the idea can still be improved in several ways which I will identify and explain here. (Euclid's method would still be better).
Don't find the largest of a
and b
, find the smallest. Why keep iterating from or toward a larger termination point? No value larger than v
will ever divide v
. So stop as soon as the smaller value is exceeded.
Don't iterate starting at 1
and increasing toward the smaller number. Start with the smaller number and decrease until you hit the first successful test. That would be the GCD of both numbers.
Don't do this (a*b)/gcd
to get the LCM. It is possible that a*b
could overflow a long. Since it is known that the gcd
divides both, divide one of the values by gcd
and then multiply by the other.
Here is the code with the changes.
public static long lcm(long a, long b) {
// find min(a,b)
long hcf = a<b?a:b;
// just loop and decrement
for (;; hcf--) {
if((a%hcf==0) && (b%hcf==0)) {
// guaranteed to exit
// when hcf reaches 1
break;
}
}
return a*(b/hcf);
}