by conistonwater · 12y ago · 0 comments
I noticed the following code:
while (b !== 0) { if (a > b) { a -= b; } else { b -= a; } }
This uses repeated subtraction (a -= b) to implement division with remainder (a %= b); imagine a=1e12+1, b=2.Please don't do this in your code. If there is a built it instruction for division with remainder, don't reimplement it poorly in javascript.
34 var tmp = a;
35 a = Math.max(a, b);
36 b = Math.min(tmp, b);
37 if (a % b === 0) return b;
to avoid the unnecessary repetitions if b is already the GCDEdit: Also, if you stick to the original subtraction-based version of the algorithm, why adding that other optimization? That wasn't part of the original algorithm, either. This seems to be double standard.
gcd(a, b) = gcd(b, a mod b),
and there is no need to compute mod with anything other than %.I'm surprised the author didn't implement the binary gcd, however, although it has the same big-O as Euclid: https://en.wikipedia.org/wiki/Binary_GCD_algorithm