Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Euclidean greatest common divisor for more than two numbers

Can someone give an example for finding greatest common divisor algorithm for more than two numbers?

I believe programming language doesn't matter.

like image 625
Bogdan Gusiev Avatar asked Aug 05 '09 07:08

Bogdan Gusiev


3 Answers

Start with the first pair and get their GCD, then take the GCD of that result and the next number. The obvious optimization is you can stop if the running GCD ever reaches 1. I'm watching this one to see if there are any other optimizations. :)

Oh, and this can be easily parallelized since the operations are commutative/associative.

like image 104
Sam Harwell Avatar answered Oct 24 '22 16:10

Sam Harwell


The GCD of 3 numbers can be computed as gcd(a, b, c) = gcd(gcd(a, b), c). You can apply the Euclidean algorithm, the extended Euclidian or the binary GCD algorithm iteratively and get your answer. I'm not aware of any other (smarter?) ways to find a GCD, unfortunately.

like image 21
Michael Foukarakis Avatar answered Oct 24 '22 14:10

Michael Foukarakis


A little late to the party I know, but a simple JavaScript implementation, utilising Sam Harwell's description of the algorithm:

function euclideanAlgorithm(a, b) {
    if(b === 0) {
        return a;
    }
    const remainder = a % b;
    return euclideanAlgorithm(b, remainder)
}

function gcdMultipleNumbers(...args) { //ES6 used here, change as appropriate
  const gcd = args.reduce((memo, next) => {
      return euclideanAlgorithm(memo, next)}
  );

  return gcd;
}

gcdMultipleNumbers(48,16,24,96) //8
like image 34
gwpmad Avatar answered Oct 24 '22 14:10

gwpmad