简体   繁体   English

阶乘递归,答案在纸上没有意义?

[英]Factorial Recursion, answer doesn't make sense on paper?

So I was on codingbat doing recursion excercises and I ran into this所以我在codingbat上做递归练习,我遇到了这个

  public int factorial(int n) {
  if (n == 1) {
    return 1;
  }
  return n * factorial(n-1);
}

I don't understand how this works on paper.我不明白这在纸上是如何运作的。 as 1 returns 1 thats fine, 2 returns 2, thats fine, 3 returns 6 thats fine, but then factorial(4) returns 24?因为 1 返回 1 很好,2 返回 2,很好,3 返回 6 很好,但是 factorial(4) 返回 24? factorial(5) returns 120? factorial(5) 返回 120?

It doesn't make sense because it is doing it from the last answer of n I assume but not minusing 1?这没有意义,因为它是从我假设的 n 的最后一个答案开始的,但没有减去 1? But passes all the tests.但是通过了所有的测试。 So it does 6*4 = 24, rather than 4x(n-1) which wouldn't equal 24?所以它是 6*4 = 24,而不是不等于 24 的 4x(n-1)? Help?帮助?

For any factorial(n), it is computed as nx (n-1) x (n-2) x ... x 1对于任何阶乘(n),计算为 nx (n-1) x (n-2) x ... x 1

So for factorial(4) that will be 4 x 3 x 2 x 1 = 24所以对于阶乘(4),这将是 4 x 3 x 2 x 1 = 24

Recursion is mostly introduced using factorial as an example, so to visualize it will look like递归主要以阶乘为例介绍,因此可视化它看起来像

fact(4) = 4 x fact(3)
        = 4 x 3 x fact(2)
        = 4 x 3 x 2 x fact(1)
        = 4 x 3 x 2 x 1 = 24

The recursion repeats until it hits the "anchor" which is the base case of 1递归重复,直到它遇到“锚点”,这是 1 的基本情况

When you're trying to understand recursion, it's good to picture a stack.当您试图理解递归时,最好描绘一个堆栈。 Every time we're calling return n * factorial(n - 1) we are pushing a value down the stack so we can retrieve it after we're done computing the factorial(n - 1) call.每次调用return n * factorial(n - 1)我们都会将一个值向下推入堆栈,以便在计算完factorial(n - 1)调用后可以检索它。 And so on so forth.等等等等。

factorial(5)
= 5 * factorial(4)
= 5 * 4 * factorial(3)
= 5 * 4 * 3 * factorial(2)
= 5 * 4 * 3 * 2 *factorial(1)
= 5 * 4 * 3 * 2 * 1
= 120 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM