I would like to find the greatest common divisor using JavaScript.
Anyone done that before and willing to share?
I would like to find the greatest common divisor using JavaScript.
Anyone done that before and willing to share?
Here is a recursive solution, using the Euclidean algorithm.
var gcd = function(a, b) {
if (!b) {
return a;
}
return gcd(b, a % b);
}
Our base case is when b
is equal to 0
. In this case, we return a
.
When we're recursing, we swap the input arguments but we pass the remainder of a / b
as the second argument.
var gcd = function(a,b) { return (!b)?a:gcd(b,a%b); };
. Nice solution by the way, +1 –
Vo var gcd = function(a,b) { return b ? gcd(b,a%b) : a; };
–
Panties const gcd = (a,b) => !b ? a : gcd(b,a%b)
–
Ns const gcd = (...n) => n.length === 2 ? n[1] ? gcd(n[1], n[0] % n[1]) : n[0] : n.reduce((a, c) => a = gcd(a, c));
–
Halfprice function gcd(a, b) { while (b) { [a, b] = [b, a % b]; } return a; }
–
Custos Taken from Wikipedia.
Recursive:
function gcd_rec(a, b) {
if (b) {
return gcd_rec(b, a % b);
} else {
return Math.abs(a);
}
}
Iterative:
function gcd(a,b) {
a = Math.abs(a);
b = Math.abs(b);
if (b > a) {var temp = a; a = b; b = temp;}
while (true) {
if (b == 0) return a;
a %= b;
if (a == 0) return b;
b %= a;
}
}
if (a < 0) a = -a;
You can also do a = Math.abs(a);
(same for the next line) –
Supererogation function egcd(a, b) {
if (a == 0)
return b;
while (b != 0) {
if (a > b)
a = a - b;
else
b = b - a;
}
return a;
}
egcd(1000000002, 4)
will take several seconds and send your fan spinning out of control because it is doing 250 million subtractions, before finally spitting out: 2 –
Reclaim © 2022 - 2024 — McMap. All rights reserved.