0

The original question is: Define a function that produces the n'th Fibonacci number, according to the defeintion: fib(0)=1;fib(1)=1;fib(n)=fib(n-1)+fib(n-2)

I was trying to solve this with if & else structure in C programming . I did it successfully and tested it with some small inputs. When the input number is '45', everything seems alright. However when input '46', the result became negative which indicates something must have gone wrong. Really hope that someone can tell me why's that, and what was I doing wrong?

The result when input 45

the result when input 46

Source Code:

include

int fib(int i)
{
    if (i == 0)
     return 1;
    else if (i == 1)
      {
        int result_1 = fib(i - 1);
        return result_1;
    }
    else 
    {
        int result_2= fib(i-1) + fib(i-2);
        return result_2;
    }
}

int main(void)
{
    printf("The final result is %d\n", fib(i));
    return 0;
}
DeriZZZsy
  • 35
  • 5
  • 2
    It is beyond `INT_MAX` which is probably `+2147483647` – Meninx - メネンックス Jan 29 '17 at 08:36
  • Thanks a lot. So are there any methods by which I can get the right answer (when input number is beyond 45) ? – DeriZZZsy Jan 29 '17 at 08:44
  • 1
    You need to extend the variable by using `long long int` instead of `int` but this requires **C99 std.** – Meninx - メネンックス Jan 29 '17 at 08:48
  • C doesn't check if you are outside of the range of a specific data-type. On your machine the first bit indicates if it's a negative number. Normally half of the numbers are negative, and the other half is positive. Fibonacci series converge exponentially. You could use long as an example, but you will run into the same problem very fast. you can test this out easily by having a int which has the max postive integer value assigned and then add 1 to it. you will see that you're suddenly in the ngative range. – Alex_M Jan 29 '17 at 08:51

1 Answers1

1

This is probably due to int is signed and becomes negative after 2e16 - 1.

Try using unsigned int. But even if this works, you are still limited but int maximum size.

You can try using unsigned long or unsigned long long or double to check how far you can get with your function.

Israel Unterman
  • 13,158
  • 4
  • 28
  • 35
  • I will rephrase this: _But even if this works, you are still limited but int maximum size._ to: But even if this works, you are still in the range of `[UINT_MIN ... UINT_MAX]` – David Ranieri Jan 29 '17 at 09:13