有人可以解释这个递归JS代码来计算指数吗?
我无法理解这个递归,即使它是一个非常简单的例子.当它转到 power(base, exponent - 1);
时,它应该做什么?当幂一直被调用直到 exponent
等于 0 时,事物是如何相乘的?
I can't understand this recursion even though it's a really simple example. When it goes to power(base, exponent - 1);
what is that supposed to do? How are things being multiplied when power keeps getting invoked until exponent
equals 0?
function power(base, exponent) {
if (exponent === 0) {
return 1;
} else {
return base * power(base, exponent - 1);
}
}
让我们从头开始.
假设您调用 power(base, 0)
.由于 exponent
为 0,函数返回 1.
Let's say you call power(base, 0)
. Since exponent
is 0, the function returns 1.
现在,假设您调用 power(base, 1)
.由于这次exponent
不是0,函数调用power(base, exponent - 1)
乘以 base代码>.(这是这里的关键......它从递归调用中获取结果,并添加自己的扭曲.)因为
exponent - 1
= 0,并且 power(base, 0)
为 1,结果实际上是 base * 1
.阅读:base
.
Now, let's say you call power(base, 1)
. Since exponent
isn't 0 this time, the function calls power(base, exponent - 1)
and multiplies it by base
. (That's the key here...it takes the result from the recursive call, and adds its own twist.) Since exponent - 1
= 0, and power(base, 0)
is 1, the result is effectively base * 1
. Read: base
.
现在进入power(base, 2)
.这最终是 base * power(base, 1)
.而 power(base, 1)
是 base * power(base, 0)
.最终结果:base * (base * 1)
.阅读:base
平方.
Now on to power(base, 2)
. That ends up being base * power(base, 1)
. And power(base, 1)
is base * power(base, 0)
. End result: base * (base * 1)
. Read: base
squared.
等等.
顺便说一下,如果不是很明显,这个函数只适用于非负整数指数.如果 exponent
是负数,或者甚至是比整数多或少的最小位,则该函数将永远"运行.(实际上,一旦递归占用了您的所有堆栈,您很可能会导致堆栈溢出.)
In case it wasn't obvious, by the way, this function will only work with non-negative integer exponents. If exponent
is negative, or is even the tiniest bit more or less than a whole number, the function will run "forever". (In reality, you'll more than likely cause a stack overflow, once recursion eats up all of your stack.)
您可以使用一些代码来修复负幂函数
You could fix the function for negative powers with some code like
if (exponent < 0) return 1 / power(base, -exponent);
对于非整数……除了抛出异常之外,没有其他好的方法可以解决这个问题.将数字提高到非整数幂是有道理的,因此您不想只是截断指数或以其他方式假装他们没有尝试这样做 - 最终会返回错误的答案.
As for non-integers...there's no good way to solve that other than throwing an exception. Raising a number to a non-integer power makes sense, so you don't want to just truncate the exponent or otherwise pretend they didn't try to do it -- you'd end up returning the wrong answer.