How can I make my gcd even shorter?

hello all, How can I make my gcd function within .reduce() even shorter than the

let gcd = (x,y) => {
  if (y === 0) return x;
  return gcd(y, x % y);
}

here is what I’ve done

return arr.reduce((x,y) => (y === 0) ? x : (y = x % y))

but doesn’t respond as expected.

Your gcd function uses recursion. I believe the only way you will get your reduce function to use recursion is to pass it as the reduce callback.

let gcd = (x,y) => {
  if (y === 0) return x;
  return gcd(y, x % y);
}
return arr.reduce(gcd);

You could however shorten your gcd function a bit.

const gcd = (x, y) => y === 0 ? : gcd(y, x % y);

Thanks
you are right
I’ve brought a little change in it

return arr.reduce(function gcd(x,y) {
    if (y === 0) return x;
    return gcd(y, x % y);
  })
1 Like

if it is mixed with your formula it becomes even shorter ( only two lines )

return arr.reduce(function gcd(x,y) {
    return y === 0 ? x: gcd(y, x % y);
  })