Recursion in c++ Factorial Program - c++

hello i have this piece of code that i coded based on some other recursion and factorial programs
but my problem is that i am really confused as to how it stored the value and kept it and then returned it at the end
int factorialfinder(int x)
{
if (x == 1)
{
return 1;
}else
{
return x*factorialfinder(x-1);
}
}
int main()
{
cout << factorialfinder(5) << endl;
}
so 5 goes in, and gets multiplied by 4 by calling its function again and again and again, then it gets to one and it returns the factorial answer
why? i have no idea how it got stored, why is return 1 returning the actual answer, what is it really doing?

Source: Image is taken from: IBM Developers website
Just take a look at the picture above, you will understand it better. The number never gets stored, but gets called recursively to calculate the output.
So when you call the fact(4) the current stack is used to store every parameter as the recursive calls occur down to factorialfinder(1). So the calculation goes like this: 5*4*3*2*1.
int factorialfinder(int x)
{
if (x == 1) // HERE 5 is not equal to 1 so goes to else
{
return 1;
}else
{
return x*factorialfinder(x-1); // returns 5*4*3*2*1 when x==1 it returns 1
}
}
Hope this helps.

Return 1 is not returning the actual answer. It's just returning the answer to calling
factorialfinder(1);
which happens in your code.
In any program, a call stack is a space in memory that is used to keep track of function calls. Space from this memory is used to store the arguments to a function, as well as the return value of that function. Whenever some function A calls another function B, A gets the return value of B from that space.
A recursive function is nothing special, it's just an ordinary function calling another function (that happens to be itself). So really, when a recursive function F calls itself, it's calling another function: F calls F', which calls F'', which calls F''', etc. It's just that F, F'', F''' etc. execute the same code, just with different inputs.
The expression if (x == 1) is there to check when this process should be stopped.
The return value of F''' is used by F''. The return value of F'' is used by F'. The return value of F' is used by F.
In Factorial of some number, the operation is (n) * (n-1) * (n-2) * .... * (1).
I've highlighted the 1; this is the condition that's being checked.

A recursive function breaks a big problem down into smaller cases.
Going over your program:
call factorialfinder with 5, result is stored as 5 * factorialfinder(4)
call factorialfinder with 4, result is stored as 5 * 4 * factorialfinder(3)
call factorialfinder with 3, result is stored as 5 * 4 * 3 * factorialfinder(2)
call factorialfinder with 2, result is stored as 5 * 4 * 3 * 2 * factorialfinder(1)
call factorialfinder with 1, result is stored as 5 * 4 * 3 * 2 * 1
in essence it combines the result of a stack of calls to factorialfinder until you hit your base case, in this case x = 1.

Well, the factorial function can be written using recursion or not, but the main consideration in the recursion is that this one uses the system stack, so, each call to the function is a item in the system stack, like this (read from the bottom to the top):
Other consideration in the recursion function is that this one has two main code piece:
The base case
The recursion case
In the base case, the recursive function returns the element that bounds the algorithm, and that stop the recursion. In the factorial this element is 1, because mathematically the factorial of number one is 1 by definition. For other numbers you don't know the factorial, because of that, you have to compute by using the formula, and one implementation of it is using recursion, so the recursive case.
Example:
The factorial of 5, the procedure is: 5*4*3*2*1 = 120, note you have to multiply each number from the top value until number 1, in other words, until the base case takes place which is the case that you already knew.

#include<iostream>
using namespace std;
int factorial(int n);
int main()
{
int n;
cout << "Enter a positive integer: ";
cin >> n;
cout << "Factorial of " << n << " = " << factorial(n);
return 0;
}
int factorial(int n)
{
if(n > 1)
return n * factorial(n - 1);
else
return 1;
}

Related

What happens in C++ when we pass a recursive function as an argument to the function itself?

In the below code, if I use just factorial(n), it gives the correct output (120), but when I use factorial(factorial(n)), the result is 0. Could someone please explain what is going wrong?
int factorial(int);
int main()
{
int n = 5; // number of terms
cout<<endl<<"The factorial is:"<<factorial(factorial(n));
return 0;
}
int factorial(int x)
{
if(x==1)
return 1;
else
return x * factorial(x-1);
}
Your problem is that you're hitting integer overflow.
As you noted the factorial of 5 is 120.
So factorial(factorial(5)) is the same as factorial(120). As you can see you're not passing the factorial function as argument to the outer factorial. You're passing the result of the call to the inner factorial as argument to the outer factorial.
The code is equivalent to this :
int result = factorial(5); // result = 120
factorial(result); // factorial (120)
The problem is that the factorial of 120 is a really big number, a number of almost 200 digits
Now this is way bigger than what an int can store. Or even a long long unsigned int. You need specialized libraries to handle arbitrarily big numbers.
factorial(factorial(5));
is effectively evaluated as if were written
temp = factorial(5); factorial(temp);
Based in the fact that we know temp will be set to 120 (we were told the function works for argument 5), the question is what happens in factorial(120).
The answer is: it overflows the maximum value of an integer.

simple recursion tracing understanding stacks

I'm working on a fairly easy tracing exercise however I'm not completely understanding why the solution is what it is...
void f( int n) {
if (n>0) {
f(n-1)
cout << n << " ";
}
}
int main () {
f(5);
return 0;
}
the answer is 1 2 3 4 5, however I'm wondering how this is so, since everytime the function f is called it never gets to the cout line...I understand that there is a stacking system where the last function implemented is looked at, however until the factorial example where it returned a value to multiply to the previous n, I'm not understanding how this is similar. Please don't use the factorial example again, I do understand it, but I'm not udnerstanding how the cout is implemented here.. thank you for your help.
Consider the simple case of calling f(1). We pass the if test and make a recursive call to f(0). This call will return doing nothing and continue executing the body of f(1). The next statement is the call to std::cout << 1 << " ";:
// Substitute the parameter with the passed in argument n = 1
void f(1) {
if (1 > 0) {
f(0);
std::cout << 1 << " ";
}
}
You should now be able to handle the case of f(2), and in general f(n). Whenever you are stuck thinking about recursive programs, consider the base cases and then generalize. Write the code out by substituting the function parameters with actual arguments.
It does get to the output line, after the recursive call to f returns.
The important part here is the stopping condition:
if (n>0)
This makes the recursive call only happen if n is larger than zero. And as the recursive call is with the argument n - 1 it will be lower and lower until it's zero and no more calls will be made.
Lets trace it for you, since you are to lazy to do it yourself in a debugger (or on paper):
The first call from main is made. n == 5 and clearly larger than zero, so a recursive call is made with 5 - 1
In the second call, n == 4, still larger than zero so a call is made again with 4 - 1
In the third call, n == 3, still larger than zero so a call is made again with 3 - 1
In the fourth call, n == 2, still larger than zero so a call is made again with 2 - 1
In the fifth call, n == 1, still larger than zero so a call is made again with 1 - 1
In the sixth call, n == 0, which is not larger than zero, so no more calls are made and the function returns.
Returns to n == 1, and so 1 is printed and then the function returns
Returns to n == 2, and so 2 is printed and then the function returns
Returns to n == 3, and so 3 is printed and then the function returns
Returns to n == 4, and so 4 is printed and then the function returns
Returns to n == 5, and so 5 is printed and then the function returns to the main function
That is, this is how it should have worked if it compiled. Now it won't even get this far since you will have compiler errors (with the code as shown in your question).

Understanding Recursion, c++

For the code below, could anyone please tell me why the function always returns "0" if the return value for the base case (n==0) is 0? I know in order to correct this function, I'd simply have to replace "return 0" with "return 1", however, I'm trying to understand why does it return 0 for the base case below.
Thanks for your help
int factorial(int n) {
if (n == 0) {
return 0;
} else {
return n * factorial(n-1);
}
}
Edit: Hopefully, the code below has no logical errors ...
#include<iostream>
#include<math.h>
using namespace std;
long double factorial (long double n) {
if (n==0) return 1;
if (n<0) return -fabs((n*factorial(n+1)));
return n*(factorial(n-1));
}
int main () {
long double n;
cout << "Enter a number: ";
cin >> n;
cout << "Factorial of " << n << " is " << factorial(n) <<endl;
return 0;
}
If you take a look at how the factorial is defined you'll find something like:
f(0) = 1
f(1) = 1
f(n) = f(n-1) * n
So your function does indeed return the wrong value for factorial(0). The recursion in this function basically works by decrementing n in every new function call of factorial.
Let's assume you call factorial(3). n would that with 3, the else branch will get executed as n does not equal zero. We follow the third rule of our definition an call factorial(2) (which is n-1) and multiply the result of it by n. Your function will step down until factorial(0) is called and returns 0 which then is a factor of all previous calculations, resulting in 3*2*1*0, and that equals to 0.
This code is simply wrong. No matter which n > 0 it gets as argument, every value is eventually multiplied with 0 and therefore factorial( n ) = 0 for all n > 0.
It returns zero since any number times zero is zero. You start with some number n, say n=5. As you go through the recursion you have:
n * factorial(n-1)
5 * factorial(5-1)
5 * 4 * factorial(4-1)
5 * 4 * 3 * factorial(3-1)
5 * 4 * 3 * 2 * factorial(2-1)
5 * 4 * 3 * 2 * 1 * factorial(1-1)
But factorial(1-1) is factorial(0) which returns 0, so you get :
5 * 4 * 3 * 2 * 1 * 0 = 0
For the code below, could anyone please tell me why the function returns "0" if the return value for the base case (n==0) is 0?
Someone chose to do that. You'd have to ask the author why they did that.
I know in order to correct this function, I'd simply have to replace "return 0" with "return 1", however, I'm trying to understand why does it return 0 for the base case below.
Likely because the person who wrote it thought 0! was equal to 0.
I don't get you question entirely but lets cal the function f(int n): int okey to make it shorter
for n = 0 it will return 0 becaulse thats what you told it to do right: if(n == 0) return 0;
for n + 1 youll get the folowing pattern:
f(n+1) ==> n * f(n) becaulse thats wat you told it to do otherwise right? and f again will evaluate.
so thats why youre function will return 0 in any case and if you alter the base case to 1 youll get:
For whatever n (bigger than or equal to 0), you multiply a lot of numbers down to factorial(0) which returns 0.
The result of
n*(n-1)*(n-2)*...*3*2*1*0
is a big fat 0
P.S. Besides not computing properly, the code has a major flaw. If you give it a negative number, you make it cry.

Trying to make a recursive call in C++

This is my first question here so be kind :-) I'm trying to make a recursive call here, but I get the following compiler error:
In file included from hw2.cpp:11:
number.h: In member function ‘std::string Number::get_bin()’:
number.h:60: error: no matching function for call to ‘Number::get_bin(int&)’
number.h:27: note: candidates are: std::string Number::get_bin()
string get_bin ()
{
bin = "";
printf("Value is %i\n",val);
if (val > 0)
{
int remainder = val;
printf("remainder is %i\n",remainder);
printf("numbits is %i\n",size);
for (int numbits = size-1;numbits>=0;numbits--)
{
//printf("2 raised to the %i is %i\n",numbits,int(pow(2,numbits)));
printf("is %i less than or equal to %i\n",int(pow(2,numbits)),remainder);
if (int (pow(2,numbits))<=remainder)
{
bin+="1";
remainder -= int(pow(2,numbits));
printf("Remainder set to equal %i\n",remainder);
}
else
{
bin+= "0";
}
}
return bin;
}
else
{
int twoscompliment = val + int(pow(2,size));
return get_bin(twoscompliment);
}
Any thoughts? I know get_bin works for positive numbers.
In the last line you are calling get_bin() with an integer reference argument, but there are no formal parameters in the function signature.
string get_bin ()
return get_bin(twoscompliment);
These are mutually incompatible. I don't see how you can say that code works for positive numbers since it's not even compiling.
You probably need to change the first line to something like:
string get_bin (int x)
but, since you don't actually use the argument, you may have other problems.
If you're using global or object-level variables to do this work, recursion is not going to work, since they different levels will be stepping on each other's feet (unless you do your own stack).
One of the beauties of recursion is that your code can be small and elegant but using local variables is vital to ensure your data is level-specific.
By way of example, examine the following (badly written) pseudo-code:
global product
def factorial (n):
if n == 1:
return 1
product = factorial (n-1)
return n * product
Now that won't work for factorial (7) since product will be corrupted by lower levels. However, something like:
def factorial (n):
local product
if n == 1:
return 1
product = factorial (n-1)
return n * product
will work just fine as each level gets its own copy of product to play with. Of course:
def factorial (n):
if n == 1:
return 1
return n * factorial (n-1)
would be even better.
The function is defined to take no arguments, yet you pass an int.
It looks like you're accessing a global or member variable val. That should probably be converted into the argument.
string get_bin ( int val )
Since you have not declared bin and val in the function I guess they are global.
Now you define the function get_bin() to return a string and not accept anything. But in the recursive call you are passing it an int. Since you want to pass twoscompliment as val for the recursive call you can do:
int twoscompliment = val + int(pow(2,size));
val = twoscompliment; // assign twoscompliment to val
return get_bin();

Fibonacci Function Question

I was calculating the Fibonacci sequence, and stumbled across this code, which I saw a lot:
int Fibonacci (int x)
{
if (x<=1) {
return 1;
}
return Fibonacci (x-1)+Fibonacci (x-2);
}
What I don't understand is how it works, especially the return part at the end: Does it call the Fibonacci function again? Could someone step me through this function?
Yes, the function calls itself. For example,
Fibonacci(4)
= Fibonacci(3) + Fibonacci(2)
= (Fibonacci(2) + Fibonacci(1)) + (Fibonacci(1) + Fibonacci(0))
= ((Fibonacci(1) + Fibonacci(0)) + 1) + (1 + 1)
= ((1 + 1) + 1) + 2
= (2 + 1) + 2
= 3 + 2
= 5
Note that the Fibonacci function is called 9 times here. In general, the naïve recursive fibonacci function has exponential running time, which is usually a Bad Thing.
This is a classical example of a recursive function, a function that calls itself.
If you read it carefully, you'll see that it will call itself, or, recurse, over and over again, until it reaches the so called base case, when x <= 1 at which point it will start to "back track" and sum up the computed values.
The following code clearly prints out the trace of the algorithm:
public class Test {
static String indent = "";
public static int fibonacci(int x) {
indent += " ";
System.out.println(indent + "invoked with " + x);
if (x <= 1) {
System.out.println(indent + "x = " + x + ", base case reached.");
indent = indent.substring(4);
return 1;
}
System.out.println(indent + "Recursing on " + (x-1) + " and " + (x-2));
int retVal = fibonacci(x-1) + fibonacci(x-2);
System.out.println(indent + "returning " + retVal);
indent = indent.substring(4);
return retVal;
}
public static void main(String... args) {
System.out.println("Fibonacci of 3: " + fibonacci(3));
}
}
The output is the following:
invoked with 3
Recursing on 2 and 1
invoked with 2
Recursing on 1 and 0
invoked with 1
x = 1, base case reached.
invoked with 0
x = 0, base case reached.
returning 2
invoked with 1
x = 1, base case reached.
returning 3
Fibonacci of 3: 3
A tree depiction of the trace would look something like
fib 4
fib 3 + fib 2
fib 2 + fib 1 fib 1 + fib 0
fib 1 + fib 0 1 1 1
1 1
The important parts to think about when writing recursive functions are:
1. Take care of the base case
What would have happened if we had forgotten if (x<=1) return 1; in the example above?
2. Make sure the recursive calls somehow decrease towards the base case
What would have happened if we accidentally modified the algorithm to return fibonacci(x)+fibonacci(x-1);
return Fibonacci (x-1)+Fibonacci (x-2);
This is terribly inefficient. I suggest the following linear alternative:
unsigned fibonacci(unsigned n, unsigned a, unsigned b, unsigned c)
{
return (n == 2) ? c : fibonacci(n - 1, b, c, b + c);
}
unsigned fibonacci(unsigned n)
{
return (n < 2) ? n : fibonacci(n, 0, 1, 1);
}
The fibonacci sequence can be expressed more succinctly in functional languages.
fibonacci = 0 : 1 : zipWith (+) fibonacci (tail fibonacci)
> take 12 fibonacci
[0,1,1,2,3,5,8,13,21,34,55,89]
This is classic function recursion. http://en.wikipedia.org/wiki/Recursive_function should get you started. Essentially if x less than or equal to 1 it returns 1. Otherwise it it decreases x running Fibonacci at each step.
As your question is marked C++, I feel compelled to point out that this function can also be achieved at compile-time as a template, should you have a compile-time variable to use it with.
template<int N> struct Fibonacci {
const static int value = Fibonacci<N - 1>::value + Fibonacci<N - 2>::value;
};
template<> struct Fibonacci<1> {
const static int value = 1;
}
template<> struct Fibonacci<0> {
const static int value = 1;
}
Been a while since I wrote such, so it could be a little out, but that should be it.
Yes, the Fibonacci function is called again, this is called recursion.
Just like you can call another function, you can call the same function again. Since function context is stacked, you can call the same function without disturbing the currently executed function.
Note that recursion is hard since you might call the same function again infinitely and fill the call stack. This errors is called a "Stack Overflow" (here it is !)
In C and most other languages, a function is allowed to call itself just like any other function. This is called recursion.
If it looks strange because it's different from the loop that you would write, you're right. This is not a very good application of recursion, because finding the n th Fibonacci number requires twice the time as finding the n-1th, leading to running time exponential in n.
Iterating over the Fibonacci sequence, remembering the previous Fibonacci number before moving on to the next improves the runtime to linear in n, the way it should be.
Recursion itself isn't terrible. In fact, the loop I just described (and any loop) can be implemented as a recursive function:
int Fibonacci (int x, int a = 1, int p = 0) {
if ( x == 0 ) return a;
return Fibonacci( x-1, a+p, a );
} // recursive, but with ideal computational properties
Or if you want to be more quick but use more memory use this.
int *fib,n;
void fibonaci(int n) //find firs n number fibonaci
{
fib= new int[n+1];
fib[1] = fib[2] = 1;
for(int i = 3;i<=n-2;i++)
fib[i] = fib[i-1] + fib[i-2];
}
and for n = 10 for exemple you will have :
fib[1] fib[2] fib[3] fib[4] fib[5] fib[6] fib[7] fib[8] fib[9] fib[10]
1 1 2 3 5 8 13 21 34 55``