2

所以这显然是一段有效的代码,但我无法弄清楚power如果exponent参数是除0.

function power(base, exponent) {
  if (exponent == 0)
    return 1;
  else
    return base * power(base, exponent - 1);
}

来自:http: //imgur.com/Sa2BfHJ

4

4 回答 4

8

Because the second call will keep calling with smaller numbers in exponent, until it reaches 0, and then return 1, and roll back aggregating the result ...

I think you'll have to do some reading on recursion :)

Here's a simple case of how it'll look:

power(2,2) 
 power(2,1) 
    power(2,0) 
       return 1 
    return 2*1 = 2 
 return 2*2 = 4 

Taken and modified from this page.

Try this page for an animated view of the recursion (didn't work for me, it's an old page, needs java, and I don't have it installed on my machine ...)


Edit:
It was bothering me I couldn't find any simple example of this, so here's a quick console program that might help you visualize how this is working :

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SO_Console
{
    class Program
    {
        static void Main(string[] args)
        {
            int base_value = 0;
            int exponent = 0;
            string[] parts = new string[2];
            int result = 0;
            Console.Out.WriteLine("Please enter the Power to calculate in this format: x^y "
            + Environment.NewLine + "(where x is the base (int) and y is the exponent (int)."
            + Environment.NewLine);

            var temp = Console.ReadLine();
            if (!string.IsNullOrWhiteSpace(temp))
            {

                parts = temp.Split('^');
                if (parts.Length != 2)
                InvalidInput();
            }
            else
            InvalidInput();


            if (Int32.TryParse(parts[0], out base_value) && Int32.TryParse(parts[1], out exponent))
            result = Power(base_value, exponent, "");
            else
            InvalidInput();

            Console.Out.WriteLine(Environment.NewLine + "Final result = {0}", result);


            Console.Out.WriteLine(Environment.NewLine + "Hit any key to quit.");
            Console.Read();

        }

        /// <summary>
        /// Recursive call to calculate Power x^y
        /// </summary>
        /// <param name="base_value">The base</param>
        /// <param name="exponent">The exponent</param>
        /// <param name="padding">Padding, for output.</param>
        /// <returns></returns>
        private static int Power(int base_value, int exponent, string padding)
        {
            Console.Out.WriteLine(string.Format("{2}Power called with: {0}^{1}", base_value, exponent, padding));
            Thread.Sleep(750);

            if (exponent == 0)
            {
                Console.Out.WriteLine("{0}{1}Base case reached, returning 1.{0}", Environment.NewLine ,padding);
                return 1;
            }
            else
            {
                var return_value = base_value * Power(base_value, exponent - 1, padding + "  ");
                Console.Out.WriteLine("{0}Going back in the recursion, returning {1}.", padding, return_value);
                Thread.Sleep(750);
                return return_value;
            }
        }

        /// <summary>
        /// Inform user about bad input and quit.
        /// </summary>
        private static void InvalidInput()
        {
            Console.Out.WriteLine("Invalid input.");
            return;
        }
    }
}

You can just paste and run it, and your results will look something along:

outputsamuple

Edit 2:
I've written an article about this, explaining in details what happens why where. You're welcome to have a look at it here : simple power recursion, console application.

于 2013-11-15T02:13:27.467 回答
2

递归仅在您有边缘情况时终止。在求幂的情况下,边缘情况是:

n 0 = 1

它读作“任何数字的 0 次方都是 1”

求幂的一般情况是:

n x = n × n x - 1

在像 Haskell 求幂这样的数学语言中,将定义如下:

n ^ 0 = 1
n ^ x = n * n ^ (x - 1)

有趣的是,如果你给这个函数一个负整数,那么边缘条件将永远不会执行,它将进入一个无限循环,最终以堆栈溢出终止。

然而,由于我们只使用整数(0 和正整数)这个函数,你永远不会陷入无限循环。

尽管如此,如果您使用足够大的指数,您仍然会遇到堆栈溢出,因为计算机只有这么多空间来存储中间结果。

在大多数 JavaScript 浏览器中,您可以计算2 ^ 2 ^ 14. 但是,如果您尝试计算2 ^ 2 ^ 15,则会出现堆栈溢出:http: //jsfiddle.net/9chrJ/

于 2013-11-15T02:42:16.270 回答
1

观察 x n = x × x n-1和 x 0 = 1。这就是代码正确的原因。

于 2013-11-15T02:16:14.247 回答
1

只是尝试一个例子。这是 2 的 3 次方

power(2,3) = 2 * (power(2,2) = 2 * (power(2,1) = 2 * (power(2,0) = 1)))

所以:

power(2,3) = 2 * (2 * (2 * 1)))
于 2013-11-15T02:16:30.387 回答