I am calculating Fibonacci numbers in C# and I am getting wrong numbers since the number 94.
This is my code.
static void Main(string[] args)
{
string N = Console.ReadLine();
ulong n = ulong.Parse(N);
ulong[] fibonacci = new ulong[n+1];
fibonacci[0] = 0;
if (n == 1)
{
fibonacci[1] = 1;
}
if (n>=2)
{
fibonacci[1] = 1;
for (ulong i = 2; i < n+1; i++)
{
fibonacci[i] = (ulong)fibonacci[i-1] + (ulong)fibonacci[i-2];
}
}
}
Console.WriteLine(fibonacci[n]);
I am ok until the 93th number which is 12200160415121876738, but I am getting 1293530146158671551 with the 94th, the real one is 19740274219868223167.
I don't know what could be wrong with my code.
18446744073709551615
. You're hoping to store a value that's larger than that, which won't work. I suggest you look atBigInteger
.