Fibonacci Function Question - c++

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``

Related

What would the 1st recursive call for this function look like?

int Fun(int m, int n)
{
if(n==0)
{
return n + 2;
}
return Fun(n-1, m-1) + Fun(m-1,n-1) + 1;
}
I'm completely lost as to what the 1st case would visually look like for this function. I don't understand why the function has two parameters and why we only return 1 parameter at the end with our base case. What would be the process to work this out? Any input you want to use to explain to me is fine I was trying (3,3). Although, now that I'm thinking about it how would this function look like if one of the inputs was smaller than the other like (3,2) or (2,3)?
Note that return n + 2; simplifies to return 2;.
The function takes two arguments (parameters) and returns a single value. That's like the operation of adding two numbers that you were taught in your first year at school.
Whether or not Fun(n - 1, m - 1) is called before Fun(m - 1, n - 1) is not specified by the C++ standard. So I can't tell you what the first recursive call will look like. This gives compilers more freedom in making optimisation choices. Of course the order in which the functions are called has no effect on the eventual result.
The best way of analysing what happens in your particular case is to use a line by line debugger.
There is nothing special about recursive functions - they work exactly like non-recursive functions.
Fun(3,3) does this:
if(3==0)
{
return 3 + 2;
}
return Fun(2, 2) + Fun(2, 2) + 1;
It needs the value of Fun(2,2), which does this:
if(2==0)
{
return 2 + 2;
}
return Fun(1, 1) + Fun(1, 1) + 1;
And that needs Fun(1,1), which does
if(1==0)
{
return 1 + 2;
}
return Fun(0, 0) + Fun(0, 0) + 1;
and Fun(0,0) does
if(0==0)
{
return 0 + 2;
}
return Fun(-1, -1) + Fun(-1, -1) + 1;
which returns 2 since the condition is true.
So, Fun(1, 1) will do
return 2 + 2 + 1;
which is 5, and Fun(2,2) will do
return 5 + 5 + 1;
which is 11, and Fun(3,3) will do
return 11 + 11 + 1;
which is 23.
I'm sure you can work through other examples on your own.

Returning a Linear List in C++ and Time Complexity

I'm currently studying for my data structures exam and ran across a problem I could use clarification on. I'm supposed to create a function InsertZero(int k, int i) that inserts k zeroes after element i, checking indices each time and throwing appropriate exceptions.
I've done this, but I'm stuck on how to return a LinearList& that the function definition is asking me to in the class. I've tried return *element, return &element, and a few others to no avail. Where am I going wrong?
Additionally, I'm supposed to give the time complexity of the function as a "function of list length and k". I analyzed the steps throughout the function (see comments) and came up with O(k)...this doesn't use the list length, and I'm a bit confused on how to do so.
Any help will be greatly appreciated. I'm looking for comprehension, not just answers.
template <class T>
LinearList<T>& LinearList<T>::InsertZero(int i, int k)
{
//Complexity statements are in the form of
// "Number of steps" * "Number of times executed" = total
if ( i<0 || i> (MaxSize-1) || k<0) // 3 * 1 = 3
cout<<"Bad input exception thrown"<<endl;// 1 * 1 = 1
else if (k > (MaxSize-i-1) ) // 1 * 1 = 1
cout<<"NoMem exception thrown"<<endl; // 1 * 1 =1
else
{
while (k!=0) // 1 * k = k
{
element[i+1]=0; // 1 * k = k
i++; // 1 * k = k
k--; // 1 * k = k
}
return &element; // 1 * 1 = 1
}
//Total = 3+1+1+1+k+k+k+k+1 = 4k+7 = O(k)
}
I guess element array is a data member of the LinearList class. element is the basic C++ type (array of ints) whereas LinearList is derived one. I would do return *this at the end of your method.
The return type looks to be a the same type as the class. So you should return *this. It appears that elment should be a member variable, and that there is no need to return it.

Recursion in c++ Factorial Program

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

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.

c recursion program problem

I'm new to concept of recursion. I want to write a recursive function which take a float and integer as argument and call it recursively in a way that the float value remain constant and integer value changes
I write the following code:
#include <stdio.h>
float sum(float f, int k)
{
static float c;
c = f - k;
c = sum(f, k - 1);
return c;
}
int main()
{
float f, g = 10.00;
int i = 5;
f = sum(g, i);
printf("the sum of integer and float = %f", f);
}
When I compile it it shows no errors but when I run the program it shows a segmentation fault.
My question are following:
what is wrong with the code?
why it is showing segmentation error?
how to use recursion in a function which has more than one argument?
Please explain me with some example of recursive function which has two arguments.
The code is wrong because it can never end (I presume it fails with a stackoverflow error).
For recursion, you need two things
A base case
A recursive case that moves towards the base case
Looks like you've only got the second. I suspect sum should return when k is zero. Something like this hopefully makes sense:
float sum(float f, int k) {
if (k <= 0) {
// The base case
return f;
} else {
// The recursive case. This does one step of the work
// and moves towards the base case
return 1 + sum(f, k - 1);
}
}
Your recursion does not have a base (non-recursive), terminating case.
Every call to sum makes a recursive call to itself, this continues till your stackoverflows, resulting in a seg fault.
The recursion never stops, and eventually you run out of stack. You need to decide when it is time to stop the recursion. for example, if k equals 0 you don't call sum again, but exit with return.
float sum(float f ,int k)
{
static float c;
if (k > 0)
{
c=f-k; /// <<< why is this here? you ignore the value and overwrite it in the next step.
c=sum(f,k-1);
}
return c;
}
Of course there are additional problems: having c as static may be a problem that will affect the correctness of the calculation, and also the place I marked looks suspicious because you loose the value and overwrite it with the subsequent call to sum.
How about this?
#include <stdio.h>
float sum(float f, int k, float c) {
if (k == 0)
return c;
sum(f, k - 1, f - k);
}
The first thing I see is that your recursion has no termination. It will go on forever. Perhaps you want:
float sum(float f ,int k)
{
static float c;
c=f-k;
if (k != 0)
c=sum(f,k-1);
return c;
}
So that when k is zero the recursion stops. You had a stack overflow.
When you do recursion you need a status to end it.
So your code with changes:
#include <stdio.h>
float sum(float f, int k)
{
if(k == 0) return f;
return 1 + sum(f,k-1);
}
int main()
{
float f, g = 10.00;
int i = 5;
f = sum(g, i);
printf("the sum of integer and float = %f", f);
}
With that code, and your example f=10.00 and i=5
Call sum(10.0, 5)
return 1 + sum(10.0, 4)
1 + sum(10.0, 3)
1 + sum(10.0, 2)
1 + sum(10.0, 1)
1 + sum(10.0, 0)
10
1 + 10 = 11
1 + 11 = 12
1 + 12 = 13
1 + 13 = 14
1 + 14 = 15
return 15;
I don't understand what the "sum" function is for. Is it supposed to be adding f and k? In which case, there is no recursion; you should just add f and k: return f + k.
But to try to answer your questions:
There is no base case. This is the cause of the infinite recursion. Every recursive function needs a base case which is a condition under which it does not recurse. Your function recurses no matter what; therefore it will always recurse forever.
When recursion segfaults, it's usually due to a stack overflow (no pun intended); it means you are recursing forever and eventually running out of space.
You can use recursion in a function with more than one argument, just the same as any other function. Just call it with whatever the new values are for the next iteration.
Note that you often have a "constant" value, that doesn't change during the recursion. To do that, you just pass the value unchanged on the recursive call, so the same value is available at each step.