Factorial Calculations using Recursive Method call - c#

This code is from the book: "C# 5.0 in a Nutshell" and is a sample on LinqPad. On page 39 it says:
"This method is recursive, meaning that it calls itself. Each time the method is entered,
a new int is allocated on the stack, and each time the method exits, the int is
deallocated."
Using the literal 5 yields and answer of 120 (3 yields 6)
Can someone explain how this works? I'm a VB programmer trying to learn C# and would like to understand constructs like this. I've single stepped through it many times and can't understand what happens after x == 0 and 1 is returned. Until x equals zero, the flow of execution is easy to understand. After that, the last return statement seems to be repeatedly executed (magically) until x increments back to it's original value and then returns to the point where it was originally called and produces the aforementioned (magical) numeric result.
static void Main()
{
Console.WriteLine (Factorial(5));
}
static int Factorial (int x)
{
if (x == 0) return 1;
return x * Factorial (x-1);
}

Call Factorial(3) (which returns 3 * 2)
x doesn't == 0
return 3 * Factorial(2)
Calls Factorial(2) (which returns 2 * 1)
x doesn't == 0
return 2 * Factorial(1)
Calls Factorial(1) (which returns 1 * 1)
x doesn't == 0
return 1 * Factorial(0)
Calls Factorial(0) (which returns 1)
x == 0 so return 1
An important point is that the recursive function must have a termination condition, otherwise it would call itself infinitely (until it runs out of stack space). In your example, the if (x == 0) return 1; is the termination condition. Since the function calls itself with a parameter value of one less than it was called with, eventually it will end up calling itself with 0, and that is when the recursion ends.
This brings out a problem with this code though. If you call with a negative number, it will call itself recursively with increasingly negative numbers, will never reach 0, and you'll eventually run out of stack space. How best to handle that is probably outside the scope of your question though.

The concept of recursion is not really limited to any specific language. The idea behind it that the function calls itself.
Let's consider your example: factorial function. But for now let's put implementation aside and think of it in more abstract terms. The function consists of two elements:
i) Instruction how to calculate an element 'n'.
ii) Instruction how to calculate an initial element
So how do we calculate element n for factorial? We take n and multiply it by factorial of a previous element: n-1:
n * Factorial(n-1)
And there is only one initial item: 0. That is when n == 0 the result is 1 or in other words Factorial(0) gives 1.
The algorithm you provided contains really of these two steps
if (x == 0)
return 1; // Do this when calculating Factorial of 0
else
return x * Factorial (x-1); // Do this when calculating an element n
Ok. Now what happens when we want to calculate factorial of 4? Let's break it down to specific steps.
Factorial(4) -> 4 * Factorial(4-1) -> 4 * Factorial(3)
We invoked factorial of 4. So we multiply 4 by factorial of 4-1. To get the factorial of 4-1 we again invoke factorial function:
Factorial(3) -> 3 * Factorial(3-1) -> 3 * Factorial(2)
Now we need to calculate factorial of 2.
Factorial(2) -> 2 * Factorial(2-1) -> 2 * Factorial(1)
And of 1
Factorial(1) -> 1 * Factorial(1-1) -> 1 * Factorial(0)
Note that now we have to calculate factorial of 0. But here we have a special instruction: if the argument is 0 the result has to be 1. Let's wind back our calculations:
Factorial(0) is 1. Replace the result in the calculation for factorial of 1.
Factorial(1) -> 1 * Factorial(1-1) -> 1 * 1 which is also 1
Factorial(2) -> 2 * Factorial(1) -> 2 * 1 -> 2
Factorial(3) -> 3 * Factorial(2) -> 3 * 2 -> 6
Factorial(4) -> 4 * Factorial(3) -> 4 * 3 -> 12
You mentioned following explanation:
Each time the method is entered, a new int is allocated on the stack,
and each time the method exits, the int is deallocated.
These steps when we go inside Factorial function to calculate factorial for a previous number is when a new int has to be allocated on the stack: for factorial of 4 the number 4 goes on the stack and the algorithm calculates factorial of 3, and so on.
And when we get to the very end that is to factorial of 0 we can finally start deallocating numbers. We have factorial of 0, multiply the result by 1. Factorial of 1 is returned and 1 is deallocated. Same happens for 2, 3 and finally 4.
Hope that clarified whole concept a bit. I'm aware the explanation is extensive, but, on the other hand, it's tricky to grasp it at the beginning so I preferred to be too thorough.

It's recursive because this statement here:
return x * Factorial (x-1);
returns the result of x * the result of the call to Factorial (X-1)... It's calling itself to get the answer. It breaks out of the loop when x==0 simply by returning the value of 1.
But one thing to note, to whom does x==0 return the value? The answer is most likely the loop which is accumulating the values.

The method Factorial calls itself again, starting with 5, and decrements the argument (x-1), until the passed argument x is 0.
So the first call to Factorial passes 5, the second call 4, 3, 2, 1, 0.
And the math done is: 5*4*3*2*1 = 120.

What it is doing is calling itself repeatedly.
What's effectively happening is the following.
We enter Factorial with x equal to 5 and since we're greater than 0 we multiply our 5 with the result of calling our self (Factorial) again with 5 - 1 which is 4. Inside this recursive call we find our selves doing another recursive call with 4 - 1 which is 3. We do this repeatedly until we call Factorial with 0, where it returns 1. Then that 1 returns to the recursion which multiplies it by 2, which returns to the recursion which multiplies it by 3, and then the next by 4, and then the next by 5.
In the end you return the result of 1 * 2 * 3 * 4 * 5 which is 120.

There is one call to return for each call to Factorial. These are the recursive calls unwinding after x == 0.
I think this might be easier to see if you slightly modify your code, if only temporarily:
static int Factorial (int x)
{
if (x == 0) return 1;
else
{
int y = x * Factorial (x-1);
return y;
}
}

Thanks for all the great replies to my question. I have a both a better understanding now of this piece of code works and a realization that I need to put a more in-depth study of recursion on my TO-DO list.

Related

Recursion - Understanding return [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
using System;
using System.Collections.Generic;
using System.Linq;
namespace Return
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Factorial(10));
Console.WriteLine(test());
}
private static int Factorial(int factorialNum)
{
if (factorialNum <= 1)
{
return 1;
}
return factorialNum * Factorial(factorialNum - 1);
}
public static int test()
{
return 1;
}
}
}
Okay so here is my thought proccess. If i make a method, that returns 1. I.e: public static int test() { return 1; } And Console.WriteLine that method, then it will say 1. If I change it to 3 it will write 3, and so on. So with the other method, I'm saying that I want to * it with the factorialNum -1. And return that. But if it is 1 it should return 1. And no matter which int I put inside it, it will always eventually = 1. Because we are saying factorialNum -1 But why is it that, when it is eventually 1. And it returns 1 Then why isn't the output in the Console.WriteLine 1 Since we're returning 1
Let's try to execute the code of calling:
Factorial(4)
When this method is called for 4 the return statement would be
4 * Factorial(3)
So we have to call Factorial(3) now and we would get
3 * Factorial(2)
Last
2 * Factorial(1)
At the last point Factorial(1) would return 1 and the result:
2 * 1
Would be passed to 3 * Factorial(2) and would be become
3 * 2 * 1
And that would be passed at the end to 4 * Factorial(3):
4 * 3 * 2 * 1
and now the method returns 24, which is the factorial of 4.
You have to keep an eye on the call stack. The fact that it would stop the recursive calls of the method at the base case factorialNum <= 1, it doesn't mean that the result of calling that method with any argument would be 1.
On the other hand, when you call test you don't have recursive calls, you return immediately 1.
return factorialNum * Factorial(factorialNum - 1);
In the above factorialNum will always be 10 since that was the input value, and will return 10*Factorial(9).
Then in the next loop it will be 9*Factorial(8) and so on. So the final return value will be 10*9*8*7*6*5*4*3*2*1
You get the number 3628800 when you run the Factorial(10) because 10! equals 3628800. If you run through the code, Factorial() returns the current number * the current number - 1. So it returns 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 = 3628800.
You are in fact returning 1 at the end of Factorial(10), but this 1 is simply multiplied by the numbers that come prior.
To get the console to return a 1, you would have to run Factorial(1) because 1! = 1.

multiplicative persistence - recursion?

I'm working on this:
Write a function, persistence, that takes in a positive parameter num
and returns its multiplicative persistence, which is the number of
times you must multiply the digits in num until you reach a single
digit.
For example:
persistence(39) == 3 // because 3*9 = 27, 2*7 = 14, 1*4=4
// and 4 has only one digit
persistence(999) == 4 // because 9*9*9 = 729, 7*2*9 = 126,
// 1*2*6 = 12, and finally 1*2 = 2
persistence(4) == 0 // because 4 is already a one-digit number
This is what I tried:
public static int Persistence(long n)
{
List<long> listofints = new List<long>();
while (n > 0)
{
listofints.Add(n % 10);
n /= 10;
}
listofints.Reverse();
// list of a splited number
int[] arr = new int[listofints.Count];
for (int i = 0; i < listofints.Count; i++)
{
arr[i] = (int)listofints[i];
}
//list to array
int pro = 1;
for (int i = 0; i < arr.Length; i++)
{
pro *= arr[i];
}
// multiply each number
return pro;
}
I have a problem with understanding recursion - probably there is a place to use it. Can some1 give me advice not a solution, how to deal with that?
It looks like you've got the complete function to process one iteration. Now all you need to do is add the recursion. At the end of the function call Persistence again with the result of the first iteration as the parameter.
Persistence(pro);
This will recursively call your function passing the result of each iteration as the parameter to the next iteration.
Finally, you need to add some code to determine when you should stop the recursion, so you only want to call Persistence(pro) if your condition is true. This way, when your condition becomes false you'll stop the recursion.
if (some stop condition is true)
{
Persistence(pro);
}
Let me take a stab at explaining when you should consider using a recursive method.
Example of Factorial: Factorial of n is found by multiplying 1*2*3*4*..*n.
Suppose you want to find out what the factorial of a number is. For finding the answer, you can write a foreach loop that keeys multiplying a number with the next number and the next number until it reaches 0. Once you reach 0, you are done, you'll return your result.
Instead of using loops, you can use Recursion because the process at "each" step is the same. Multiply the first number with the result of the next, result of the next is found by multiplying that next number with the result of the next and so on.
5 * (result of rest)
4 * (result of rest )
3 * (result of rest)
...
1 (factorial of 0 is 1).---> Last Statement.
In this case, if we are doing recursion, we have a terminator of the sequence, the last statement where we know for a fact that factorial of 0 = 1. So, we can write this like,
FactorialOf(5) = return 5 * FactorialOf(4) = 120 (5 * 24)
FactorialOf(4) = return 4 * FactorialOf(3) = 24 (4 * 6)
FactorialOf(3) = return 3 * FactorialOf(2) = 6 (3 * 2)
FactorialOf(2) = return 2 * FactorialOf(1) = 2 (2 * 1)
FactorialOf(1) = return 1 * FactorialOf(0) = 1 (1 * 1)
FactorialOf(0) = Known -> 1.
So, it would make sense to use the same method over and over and once we get to our terminator, we stop and start going back up the tree. Each statement that called the FactorialOf would start returning numbers until it reaches all the way to the top. At the top, we will have our answer.
Your case of Persistence
It calls for recursive method as well as you are taking the result and doing the same process on it each time.
Persistence(39) (not single) = return 1 + Persistence(3 * 9 = 27) = 3
Persistence(27) (not single) = return 1 + Persistence(2 * 7 = 14) = 2
Persistence(14) (not single) = return 1 + Persistence(1 * 4 = 4) = 1
Persistence(4) (single digit) = Known -> 0 // Terminator.
At the end of the day, if you have same process performed after each calculation / processing with a termination, you can most likely find a way to use recursion for that process.
You definitely can invoke your multiplication call recursively.
You will need initial sate (0 multiplications) and keep calling your method until you reach your stop condition. Then you return the last iteration you've got up to as your result and pass it through all the way up:
int persistence(int input, int count = 0) {} // this is how I would define the method
// and this is how I see the control flowing
var result = persistence(input: 39, count: 0) {
//write a code that derives 27 out of 39
//then keep calling persistence() again, incrementing the iteration count with each invocation
return persistence(input: 27, count: 1) {
return persistence(input: 14, count: 2) {
return persistence(input: 4, count: 3) {
return 3
}
}
}
}
the above is obviously not a real code, but I'm hoping that illustrates the point well enough for you to explore it further
Designing a simple recursive solution usually involves two steps:
- Identify the trivial base case to which you can calculate the answer easily.
- Figure out how to turn a complex case to a simpler one, in a way that quickly approaches the base case.
In your problem:
- Any single-digit number has a simple solution, which is persistence = 1.
- Multiplying all digits of a number produces a smaller number, and we know that the persistence of the bigger number is greater than the persistence of the smaller number by exactly one.
That should bring you to your solution. All you need to do is understand the above and write that in C#. There are only a few modifications that you need to make in your existing code. I won't give you a ready solution as that kinda defeats the purpose of the exercise, doesn't it. If you encounter technical problems with codifying your solution into C#, you're welcome to ask another question.
public int PerRec(int n)
{
string numS = n.ToString();
if(numS.Length == 1)
return 0;
var number = numS.ToArray().Select(x => int.Parse(x.ToString())).Aggregate((a,b) => a*b);
return PerRec(number) + 1;
}
For every recursion, you should have a stop condition(a single digit in this case).
The idea here is taking your input and convert it to string to calculate that length. If it is 1 then you return 0
Then you need to do your transformation. Take all the digits from the string representation(in this case from the char array, parse all of them, after getting the IEnumerable<int>, multiply each digit to calculate the next parameter for your recursion call.
The final result is the new recursion call + 1 (which represents the previous transformation)
You can do this step in different ways:
var number = numS.ToArray().Select(x => int.Parse(x.ToString())).Aggregate((a,b) => a*b);
convert numS into an array of char calling ToArray()
iterate over the collection and convert each char into its integer representation and save it into an array or a list
iterate over the int list multiplying all the digits to have the next number for your recursion
Hope this helps
public static int Persistence(long n)
{
if (n < 10) // handle the trivial cases - stop condition
{
return 0;
}
long pro = 1; // int may not be big enough, use long instead
while (n > 0) // simplify the problem by one level
{
pro *= n % 10;
n /= 10;
}
return 1 + Persistence(pro); // 1 = one level solved, call the same function for the rest
}
It is the classic recursion usage. You handle the basic cases, simplify the problem by one level and then use the same function again - that is the recursion.
You can rewrite the recursion into loops if you wish, you always can.

I can't understand this Fibonacci program flow

so Im new to the world of programming and thought Id pick up a book to start learning. I bought A Players Guide to C# 3rd Edition and one of the little homework assignments it gives you has me pretty stumped. I was debugging it step by step to help me understand, but the flow of the program makes no sense to me. Here it is.
static void Main(string[] args)
{
for (int index = 1; index <= 10; index++)
{
Console.WriteLine(Fibonacci(index));
}
Console.ReadKey();
}
/// <summary>
/// Returns a number from the Fibonacci sequence, starting at 1.
/// Note that this implementation is not very optimized, and can
/// take a very long time if you're looking up large numbers.
/// </summary>
/// <param name="number"></param>
/// <returns></returns>
static ulong Fibonacci(int number)
{
if (number == 1) { return 1; }
if (number == 2) { return 1; }
return Fibonacci(number - 1) + Fibonacci(number - 2);
}
the first two times it runs through the for loop it prints out '1' and '1' because the first time through the index is '1' making that first if statement true and the second time through the index is '2' making the second if statement true. But when it runs a 3rd time and the index turns to 3 it goes to that return statement, and if my math is right (3-1) + (3-2) equates to 3, which makes sense right. So I expect it to break from the method return 3 and write that to the Console window, but it doesnt. Instead it runs through the method again this time saying the value of the number is 2.(ok??) well at least it should stop at that 2nd if statement and reprint '1' again. Nope it ignores that line hits the return statement again. What the hell is going on? Please explain this logic.
There is a nice illustration of this kind of recursive hell.
Note that the illustration is for one iteration of your loop
And also, it is drawn for this code :
return Fibonacci(number - 2) + Fibonacci(number - 1);
as you have the reversed addition, the correct program flow would be the opposite as the one shown by the diagram below.
Image was taken here : http://composingprograms.com/pages/28-efficiency.html
I call it hell for two reasons :
Difficult to read for the developper
The first time the fibfunction is called, with parameter 6, it first calls fib(4), (the left part of the tree), then, when it's over, calls fib(5) (the right part of the tree).
Recursion can however be very useful for some case, but this school-one is absolutely not fitted for this recursion. The purpose of code is not to be read only by compilers, it is to be read by developers as well.
Inefficient
As you can see, some fib(n) are called several time with the same n.
At the end, this recursive algorithm is O(2^n), which is quite bad for this problem
Even more inefficient in a loop
Remember, the illustration is for only one iteration ! You can draw a diagram for fib(n) like this for each n.
With this method, you lose each previously calculated values, instead of reusing them to calculate the next value. This loop has then complexity O(n * 2^n)
Well, it's a not so simple example of recursion, and to makes matters worst, it's being executed inside a loop... Hardly what I would use to teach people what recursion is.
So, the point of recursion is that a function will execute itself over and over again until it's stopping condition is met (And if it's never met or doesn't even exists it will create an infinite recursion, that most of the times is not a good thing).
A classic example of recursion would be to calculate factorial (and in case you don't remember how it works, 5! = 5 * 4 * 3* 2 * 1).
So an implementation of a factorial recursive method would be something like this:
Int64 Factorial(int input)
{
if(input < 0)
{
throw new ArgumentOutOfRangeException("Input must be 0 or higher.");
}
if(input < 2)
{
return 1;
}
return input * Factorial(input - 1);
}
(0! = 1, and -3! is invalid...)
Now, let's say you call this method with the number 3:
Factorial(3) will return 3 * Factorial(3-1).
Similarly, Factorial(2) will return 2 * Factorial(2-1).
Factorial(1) will simply return 1.
Putting it all together Factorial(3) will return 3 * 2 * 1 which is 3!.
Now, in your case, The Fibonacci recursive method stopping condition is number is either 1 or 2, but it calls itself twice: Fibonacci(number - 1) + Fibonacci(number - 2);. To make matters worst it's being executed from inside a for loop, calculating the number on the Fibonacci sequences by indexes (from 1 to 10).
Let's examine what Fibonacci(3) does:
Fibonacci(3) will return Fibonacci(3-1) + Fibonacci(3-2).
Fibonacci(2) will return 1.
Fibonacci(1) will return 1.
So, Fibonacci(3) will return 1 + 1.
Let's take the next number:
Fibonacci(4) will return Fibonacci(4-1) + Fibonacci(4-2).
We already calculated that Fibonacci(3) returns 2, and we know that Fibonacci(2) will return 1, so Fibonacci(4) will return 3
(or 1+1+1 if you want to step into every call).
Similarly, Fibonacci(5) will return Fibonacci(5-1) + Fibonacci(5-2) - So it's 3 + 2 and so on (Fibonacci(6) will return 5+3, Fibonacci(7) will return 8+5).

Getting the nearest value that returns true on a bool

If I wanted to get the nearest value to a number, but that value also has to return true on a bool called IsMultipleOf7 which returns true on numbers that are multiples of 7.
For example, I have a int x = 523. So the nearest multiple of 7 is 525, so my bool would return true 525.
How can I get that number?
This function will return the closest multiple of 7 or the number itself if it is a multiple of 7
public int GetClosestNumber(int number, out bool isMultipleOf7)
{
// if the number is a multiple of 7 isMultipleOf7 is set to true
isMultipleOf7 = number%7 == 0;
if (isMultipleOf7)
{
// if it's a multiple of 7 then the closest one is the number itself
return number;
}
// if it's not a multiple of 7 then try find the closest.
var lower = number - (number % 7);
var upper = (number + 7) - (number %7);
var diffL = Math.Abs(number - lower);
var diffU = Math.Abs(number - upper);
return diffL > diffU ? upper : lower;
}
And here's a usage example:
bool IsMultipleOf7;
// Following line will output: Closest multiple of 7 is: 525
Console.WriteLine("Closest multiple of 7 is: {0}",
GetClosestNumber(523, out IsMultipleOf7));
// Following line will output: The number itself is not a multiple of 7"
Console.WriteLine("The number itself is {0} a multiple of 7",
IsMultipleOf7 ? string.Empty: "not");
Live demo is also available here
int x = 523;
while ((int)x/7!=(decimal)x/7){
x++;
}
return x;
int x = 523;
int result = ((x / 7) + 1) * 7;
You may need a more complex formula, if your number is dividable by 7 and should stay the same number. Or maybe you have simplified your problem too much?
There are two ways I can think of. The first is the brute force method I commented about. If you start with the number x, test it. If it works, hooray! If not, try adding one to x and test. Then subtract one from x and test. Then do this with two, and three, testing up and down at the same time. Once your test returns true, you have located (one of) the closest number(s) that work. This method is a general one and will work with any test function.
Because we know you are using IsMultipleOf7 as the test, a smarter method could be possible. Imagine the time it would take if your test was instead IsMultipleOf999999999! So many numbers might have to tested before hitting the closest. Instead, some math can be used. First, compute x modulo 7 (for IsMultipleOf7), written x % 7 in C(++). This value tells you how far x is from the largest multiple of 7 LESS than x. If this value is 0, x is a multiple of 7. If the value is 1, 2 or 3, x minus the value is the closest multiple. If the value is 4, 5 or 6, x plus the difference to make 7 (7 - value) is the closest multiple.
Some pseudo-code:
x = 523
value = x modulo 7
if(value == 0):
return x
if(value < 4): // that is, less than half of 7
return x - value
otherwise
return x + (7 - value)
x=7*Math.Round(((float)x)/7.0)
^Simplest solution right there ;)
No need for all of this looping and stuff.
divide by 7, if the decimals are less than 0.5 then the nearest denominator is floored, else ceiling. Round() does that for you, then just multiply your new int by 7 to create a number evenly divisible by 7 (since it was an int being multiplied by 7). It will get the closest value above or below. No need for bool at all. Make sure you cast float onto x so that it can be divided by 7 without causing flooring with integer logic.

Recursive loop (C#)

Can someone please 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:
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.
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

Categories