Ok, I initially wrote a simple code to return the Fibonacci number from the series based on the user input..
n=5 will produce 3..
static int fibonacci(in
Recursively is a very inefficient way to calculate the Fibonacci number.After the number 43 it will take more then 30 sec till you'll have the answer. I tried to find out how much time will take to calculate the number 52 and it took about 47 minutes. So the time grows very fast.
The recursive code:
private int calculateRecursivelyInt(int fnum)
{
if (fnum == 0)
return 0;
if (fnum == 1)
return 1;
return calculateRecursivelyInt(fnum - 1) + calculateRecursivelyInt(fnum - 2);
}
Loops are much more efficient
//This method will be able to calculate till the F46 because int can't hold a
// bigger number. You can calculate till 92 with a type long and till 93 with
// unsigned long in C#.
private int calculateLoopInt(int num)
{
int fnum = 0;
int val1 = 0;
int val2 = 1;
for (int i = 0; i < num; i++)
{
if (num == 1)
fnum = 1;
else if (i > 0)
{
fnum = val1 + val2;
val1 = val2;
val2 = fnum;
}
}
return fnum;
}