Calculating the greatest common divisor between the digital / array of two or more

const gcd = (...arr) => {
  const _gcd = (x, y) => (!y ? x : gcd(y, x % y));
  return [...arr].reduce((a, b) => _gcd(a, b));
};

  

Recursive function. The basic case is when y is equal to 0. In this case, return x. Otherwise, return the remainder of y GCD and division of x / y.

Open node debugging command line results are as follows

> const gcd = (...arr) => { 
... const _gcd = (x, y) => (!y ? x : gcd(y, x % y)); 
... return [...arr].reduce((a, b) => _gcd(a, b)); 
... }; 
undefined 
> gcd(8, 36); 
4 
> gcd(...[12, 8, 32]); 
4 
>

 

Guess you like

Origin www.cnblogs.com/typttxs/p/11443575.html