开发者

Recursive loop (C#)

Can someone ple开发者_如何学Pythonase explain it to me? I wrote a function to calculate the factorial of a number like this in 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;
    }
}

But I found some C++ code (I don't really know any C++ btw) which finds a factorial using a recursive loop:

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

Can someone explain to me how it works? Thanks.


Well, it uses the fact that factorial(n) is n * factorial(n - 1) with a base case of n = 1.

So for example:

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

The implementation just uses this recursive definition.


Syntactically, the C++ code is identical to the same code written in C#. Don't let the language discrepancy catch you off guard! It actually looks like C to me, given that the variable is declared at the top of the function; that's not strictly necessary in either C++ or C#. I prefer to declare variables the first time I use them, combining the declaration and initialization in one single statement, but that's merely a stylistic preference that doesn't change the function of the code.

I'll try to explain this by adding comments to each line of the code snippet:

// 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;
}

Recursive calls simply mean that the function calls itself from within the same function. This works because the factorial of n is equivalent to the following statement:

n! = n * (n-1)! 

One great way to understand how code works is to add it to a test project, then single-step through the code using the debugger. Visual Studio has very rich support for this in C# applications. You can watch how the function recursively calls itself, watching each line execute in sequence, and even seeing the values of the variables change as operations are performed on them.


Lets analyze this line by line:

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

Line 1: If the number is less than or equal to zero, we return 1. This is saying that 0! = 1 and 1! = 1

Lines 2 + 3: Otherwise we return number * factorial(number - 1). Lets look at this for 5! (here i use n! as a synonym for factorial(n) for brevity)

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

So the whole thing expands out. Its just using the property that

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

Warning: The recursive code, as always, will suffer from a stack overflow and increased memory usage as compared to an iterative (or tail-recursive-optimized) version, so use at your own risk.


A recursive function is a function that calls itself in its body. For it be bounded, and eventually return a value, two things must happen:

  1. It has to have a base case where it doesn't call itself again, returning a known value. This base case stops the recursion. For the factorial function, this value is 1 when the input is 0.

  2. Its recursive applications must converge to the base case. For factorial, the recursive application calls the function with the input subtracted by 1, which will eventually converge to the base case.

A simpler way to look at this function is this (only valid for positive input):

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


Recursive function are function calling from the same function

eg:

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

look at the code it will call the function again and again

Problem with recursion it will work infinitely so want to stop it by a particular condition

some change in above code now look

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

output will be 10 printed 10 times, here this line cout<<i; will execute after return

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜