且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

需要帮助理解 Eloquent Javascript 中的递归函数示例

更新时间:2021-08-10 01:18:20

我认为每个递归步骤(调用自身的函数)都会产生一个更短、更容易的问题.

I consider each recursive step (the function calling itself) producing a shorter and easier problem.

最简单的问题是 power(base, 0),它满足 exponent == 0 并返回 1(任何底数的零次方都是 1).

The easiest problem is power(base, 0), which satisfies exponent == 0 and returns one (any base to the zeroth power is 1).

然后,请注意,无论指数有多大,它都会将 exponent 减一,以保证最终会达到指数为零的最简单"问题.它只能是负数,否则永远不会达到这个基本情况".

Then, notice that no matter how large exponent is, it is reducing exponent by one, guaranteeing that it will eventually reach the "easiest" problem where the exponent is zero. It only can't be negative, or else this "base case" is never reached.

因此,2^5 或 power(2, 5) 变为 2 * 2^4.2^4 = 2 * 2^3.通过继续这个扩展,我们得到 2 * 2 * 2 * 2 * 2 * 1,等于 32.1 表示情况 exponent == 0 为真.

So, 2^5, or power(2, 5), becomes 2 * 2^4. And 2^4 = 2 * 2^3. By continuing this expansion, we get 2 * 2 * 2 * 2 * 2 * 1, which equals 32. The 1 represents the case exponent == 0 being true.

计算必须跟踪它累积了多少次乘法,并且一旦达到 exponent == 0 的基本情况,将所有数字相乘.它无法预先确定power(base, exponent-1) 将返回什么.

The computation has to keep track how many of these multiplications it has accumulated, and once the base case of exponent == 0 is reached, multiply all numbers together. It cannot know in advance with certainty what power(base, exponent-1) will return.