I\' having a problem with fibonacci sequence programming C# I have the following
ID: 669275 • Letter: I
Question
I' having a problem with fibonacci sequence programming C#
I have the following code:
BigInteger FibSequence(int n)
{
if (n < 2)
return n;
else if(fibData.ElementAtOrDefault(n) != default(int))
return fibData[n];
else
{
BigInteger retVal = FibSequence(n - 1) + FibSequence(n - 2);
fibData.Add(retVal);
return retVal;
}
}
To calculate the fibanocci sequence at each level 'n' recursively it works relatively well except for at the n=4 stage for some reason i skip an answer (fib(n=4) = 3) Instead I get 5 and it continues from there.
Sample output -> format = count:fibanswer
1: 0
2: 1
3: 1
4: 2
5: 5
6: 8
7: 13
8: 21
9: 34
10: 55
What am I doing wrong?
Explanation / Answer
working c# code.
Enter value 10 and you will get the correct result.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace fibonaci
{
class Program
{
static void Main(string[] args)
{
int i, count, f1 = 0, f2 = 1, f3 = 0;
Console.Write("Enter the Limit : ");
count = int.Parse(Console.ReadLine());
Console.WriteLine(f1);
Console.WriteLine(f2);
for (i = 0; i <= count; i++)
{
f3 = f1 + f2;
Console.WriteLine(f3);
f1 = f2;
f2 = f3;
}
Console.ReadLine();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.