Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find GCD, LCM on a set of numbers

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?

like image 844
user339108 Avatar asked Nov 17 '10 05:11

user339108


People also ask

How do you find the GCD of a set of numbers?

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.

What is LCM and GCD of two numbers?

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.


2 Answers

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; } 
like image 106
Jeffrey Hantin Avatar answered Oct 02 '22 19:10

Jeffrey Hantin


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)

like image 44
RyuuGan Avatar answered Oct 02 '22 20:10

RyuuGan