Reputation: 43
When running the following code I end up getting negative values. I am only using positive numbers so I am really confused. I have tried to see if this negative number was a return code but there dose not seem to be any codes that return this as a number.
public static int fib(int n)
{
int a = 0;
int b = 1;
for (int i = 0; i < n; i++)
{
int temp = a;
a = b;
b = temp + b;
}
return b;
}
static void Main(string[] args)
{
int n = 0;
bool Run = true;
while (Run == true)
{
n = fib(n + 1);
Console.WriteLine(n);
}
}
Here are the results when the code is run:
1
2
3
5
13
610
-121099088
1
Upvotes: 1
Views: 1802
Reputation: 498982
This is the result of an integer overflow and the use of twos' complement to represent integers.
In C#, the default is not to check for integer overflows. If you do change to a checked
context, you will get an exception.
Either use a checked
context, use uint
or even ulong
- you need to ensure you are using a data type that can hold the values you are calculating.
Upvotes: 7
Reputation: 8190
Your code is computing the 'nth' Fibonacci number, but it's getting it's 'n' from the previous calculation. My guess is that the 610th Fibonacci number is overflowing int. Use unsigned uint or ulong if you want to continue using this logic. Otherwise, you need to modify how you're determining 'n' for your Fibonacci calculation.
Upvotes: 1
Reputation: 1500375
You're just seeing integer overflow. You're trying to compute fib(610)
which is way more than an Int32
can hold - and when you add two large integers together, you'll get a negative number.
If you build it in "checked" mode, an exception will be thrown instead - or you can do it just for the one expression you need:
for (int i = 0; i < n; i++)
{
int temp = a;
a = b;
b = checked(temp + b);
}
See MSDN for more on checked arithmetic.
Upvotes: 13