递归循环(c#)

Recursive loop (C#)

本文关键字:循环 递归      更新时间:2023-10-16

谁能给我解释一下?我在c#中编写了一个函数来计算一个数字的阶乘:

public int factorial(int input)
{
    if (input == 0 || input == 1)
        return 1;
else
{
    int temp = 1;
    for (int i = 1; i <= input; i++)
        temp = temp * i;
    return temp;
    }
}

但是我发现了一些c++代码(我真的不知道任何c++),它发现一个阶乘使用递归循环:

int factorial(int number) {
 int temp;
 if(number <= 1) return 1;
 temp = number * factorial(number - 1);
 return temp;
}
谁能给我解释一下它是怎么工作的?谢谢。

好吧,它使用factorial(n)n * factorial(n - 1)的事实,并以n = 1为基准。

例如:

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

实现只使用这个递归定义。

语法上,c++代码与用c#编写的相同代码完全相同。不要让语言差异让你措手不及!在我看来,它实际上像C语言,因为变量是在函数的顶部声明的;这在c++或c#中都不是严格必要的。我更喜欢在第一次使用变量时声明它们,将声明和初始化合并在一个语句中,但这仅仅是一种风格偏好,不会改变代码的功能。

我将尝试通过在每一行代码片段中添加注释来解释这一点:
// Declare a function named "Factorial" that accepts a single integer parameter,
// and returns an integer value.
int Factorial(int number)
{
    // Declare a temporary variable of type integer
    int temp;
    // This is a guard clause that returns from the function immediately
    // if the value of the argument is less than or equal to 1.
    // In that case, it simply returns a value of 1.
    // (This is important to prevent the function from recursively calling itself
    // forever, producing an infinite loop!)
    if(number <= 1) return 1;
    // Set the value of the temp variable equal to the value of the argument
    // multiplied by a recursive call to the Factorial function
    temp = number * Factorial(number - 1);
    // Return the value of the temporary variable
   return temp;
}

递归调用仅仅意味着函数从同一函数内部调用自身。这行得通,因为n的阶乘等价于下面的语句:

n! = n * (n-1)! 
理解代码如何工作的一个好方法是将其添加到测试项目中,然后使用调试器单步通过代码。Visual Studio在c#应用程序中对此提供了非常丰富的支持。您可以观察函数如何递归地调用自己,观察每一行按顺序执行,甚至可以看到在对变量执行操作时变量值的变化。

让我们逐行分析:

if(number <= 1) return 1;
temp = number * factorial(number - 1);
return temp;

第1行:如果数字小于等于0,则返回1。这就是说0! = 11! = 1

第2 + 3行:否则返回number * factorial(number - 1)。让我们看看5!(这里我使用n!作为factorial(n)的同义词)

5!
5 * 4!
5 * 4 * 3!
5 * 4 * 3 * 2!
5 * 4 * 3 * 2 * 1!
5 * 4 * 3 * 3 * 1 // Here we don't have to expand 1! in the same way because of the condition

整个式子展开。它只是使用了

这个属性

n! = n * (n - 1) * ... * 2 * 1 = n * (n - 1)!

警告:与迭代(或尾部递归优化)版本相比,递归代码总是会遭受堆栈溢出和内存使用量增加的问题,因此使用时请自行承担风险。

递归函数是在函数体中调用自己的函数。要使它有界并最终返回一个值,必须满足两个条件:

  1. 它必须有一个基本情况,它不再调用自己,返回一个已知的值。这个基本情况停止递归。对于阶乘函数,当输入为0时,该值为1。

  2. 它的递归应用必须收敛于基本情况。对于阶乘,递归应用程序调用输入减去1的函数,最终将收敛到基本情况。

查看这个函数的一种更简单的方法是这样的(只对正输入有效):

int factorial(int input) {
  return input == 0 ? 1 : input * factorial(input - 1);
}

递归函数是指从同一函数调用的函数

,

  Test()
    {
      i++;
      Test();
      cout<<i;
    }

看看代码它会一次又一次地调用这个函数

递归的问题它会无限地工作所以想要通过一个特定的条件来停止它

以上代码的一些更改现在看起来

int i=0; 
Test()
        {
         if(i==10) return;
         i++;
         Test();
         cout<<i;
        }

输出将被打印10次,这里这行cout<<i;将在返回

后执行