我有以下函数可以找到 2 个整数的最大公约数。我不明白 returnGreatestCommonDivisor(b, (a % b)); 中发生了什么部分。
如果我执行GreatestCommonDivisor(8, 12),我会得到4,这是正确的,但是当我尝试评估返回的GreatestCommonDivisor(b, (a % b));我得到 (12, (8 % 12)) 简化为 (12, 0) 这怎么等于 4?
// Finds greatest common divisor
function greatestCommonDivisor(a, b) {
if (b == 0) {
return a;
}
return greatestCommonDivisor(b, (a % b));
}
最佳答案
该函数使用递归来调用自身,直到满足返回实际答案的基本条件。
在 greatestCommonDivisor(8, 12)
的情况下,会发生以下情况:
- b != 0 所以调用GreatestCommonDivisor(12, 8 % 12)//8 % 12 = 8
- b != 0 所以调用GreatestCommonDivisor(8, 12 % 8)//12 % 8 = 4
- b != 0 所以调用GreatestCommonDivisor(4, 8 % 4)//8 % 4 = 0
- b == 0 所以返回 4
关于javascript - 了解返回 2 个值的 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14492513/