0

The function below takes two integers and calculates the greatest common divisor (gcd):-

function mygcd(x, y) {
  while(y) var t = y, y = x % y, x = t;
  return x;
}

I've run through a load of test cases and stepped through the code to see how it comes to its result, but I'm absolutely stumped in terms of the method - can anybody explain to me in simple terms how this works, and how the while loop eventually returns the GCD of the two values x and y?

NOTE: I do understand how the code itself works - what I want to know is how the calculations eventually return the correct result.

Mat Richardson
  • 3,576
  • 4
  • 31
  • 56
  • 1
    This is [Euclid's Method](http://en.wikipedia.org/wiki/Euclidean_algorithm), derived about 2500 years ago. – Pointy Apr 17 '15 at 23:22
  • http://en.wikipedia.org/wiki/Euclidean_algorithm – Benjamin Gruenbaum Apr 17 '15 at 23:22
  • I'm voting to close this question as off-topic because it's about mathematics, not programming. – Barmar Apr 17 '15 at 23:23
  • 2
    @Barmar true but a good proof of the algorithm is pretty cool. :) – Pointy Apr 17 '15 at 23:23
  • @Barmar _sure_ it's programming, just because something is abstract (how does an algorithm work?) doesn't mean it's not a real programming problem. – Benjamin Gruenbaum Apr 17 '15 at 23:24
  • @Pointy Sure, but that proof would be on-topic for math.SE, not SO. – Barmar Apr 17 '15 at 23:24
  • Apologies - I didn't know this was more of a mathematics question, and haven't heard of Euclid's method. I guess I managed to get an answer, at least!! – Mat Richardson Apr 17 '15 at 23:24
  • @BenjaminGruenbaum He said he understands how the code works, he doesn't understand the mathematical basis. – Barmar Apr 17 '15 at 23:24
  • @Barmar I DO understand the mechanism of the code, but not how it eventually gets to the result. I would argue this is perhaps both a mathematics and a programming question... – Mat Richardson Apr 17 '15 at 23:26
  • 1
    @Barmar yeah, that's just saying he understands the _syntax_ - that is what `%` does, what `while` is and what `return` is and so on. There are a lot of code bits where I understand all the parts but not the algorithm. Algorithmic questions are definitely on topic here - especially ones about common algorithms (finding the GCD is a real problem and an knowing why an efficient way to calculate it works is legit) - and indeed, there is a highly voted duplicate. – Benjamin Gruenbaum Apr 17 '15 at 23:26
  • Euclid didn't know anything about computers when he came up with the algorithm. Asking how to calculate it efficiently would be a programming question, but asking how the algorithm works is pure math. – Barmar Apr 17 '15 at 23:29

0 Answers0