What would be the easiest way to calculate Greatest Common Divisor and Least Common Multiple on a set of numbers? What math functions can be used to find this information?
Step 1: Applying Euclid's division lemma to a and b we get two whole numbers q and r such that, a = bq+r ; 0 r < b. Step 2: If r = 0, then b is the HCF of a and b. If r ≠0, then apply Euclid's division lemma to b and r. Step 3: Continue the above process until the remainder is zero.
The least common multiple (LCM) of two integers is the smallest positive integer that is a multiple of both. The greatest common divisor (GCD) of two integers is the largest positive integer dividing both. The product of the two numbers is the product of the LCM and the GCD.
I've used Euclid's algorithm to find the greatest common divisor of two numbers; it can be iterated to obtain the GCD of a larger set of numbers.
private static long gcd(long a, long b) { while (b > 0) { long temp = b; b = a % b; // % is remainder a = temp; } return a; } private static long gcd(long[] input) { long result = input[0]; for(int i = 1; i < input.length; i++) result = gcd(result, input[i]); return result; }
Least common multiple is a little trickier, but probably the best approach is reduction by the GCD, which can be similarly iterated:
private static long lcm(long a, long b) { return a * (b / gcd(a, b)); } private static long lcm(long[] input) { long result = input[0]; for(int i = 1; i < input.length; i++) result = lcm(result, input[i]); return result; }
There is an Euclid's algorithm for GCD,
public int GCF(int a, int b) { if (b == 0) return a; else return (GCF (b, a % b)); }
By the way, a
and b
should be greater or equal 0
, and LCM = |ab| / GCF(a, b)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With