const gcd = (...arr) => { const _gcd = (x, y) => (!y ? x : gcd(y, x % y)); return [...arr].reduce((a, b) => _gcd(a, b)); };
函数使用递归。 基本情况是当y等于0.在这种情况下,返回x。 否则,返回y的GCD和除法x / y的余数。
打开node命令行调试结果如下
> 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 >
原文:https://www.cnblogs.com/typttxs/p/11443575.html