0

I want to print the first 100 numbers in the fibonacci sequence. My program prints until around 20 numbers than the numbers turn negative.

Can someone explain this to me please and provide a fix?

Thanks,

/*Fibonacci sequence*/

#include <iostream>

using namespace std;

int main(){
    long int i, fib;
    int firstNum=0, secondNum=1;

    cout << firstNum << endl; 
    cout << secondNum << endl;

    for (i=0; i < 100; i++){
        fib = firstNum + secondNum;
        firstNum = secondNum;
        secondNum = fib;
        cout << fib << endl;
    }

    return 0;
}
Abdirahman Haji
  • 31
  • 1
  • 2
  • 5
  • 2
    The maximum value an `int` can store is +2147483647. Try using `unsigned long long`, even then I think you might overflow before you get to 100. – Jonathan Potter Oct 16 '15 at 21:23
  • 1
    After 20th fabonacci num it crosses the range of int, well you could use long long int but that too will store till 91st fabonacci. so you could either store them in an array digit by digit or use Bigint. – wrangler Oct 16 '15 at 21:23
  • @JonathanPotter The maximum value an int can store is *at least* +2147483647. An `int` may be bigger than 32 bits. – Alan Stokes Oct 16 '15 at 21:44

3 Answers3

1

What you are seeing is an integer overflow problem. firstNum and secondNum are not long.

This should fix it

    unsigned long long i, fib;
    unsigned long long firstNum=0, secondNum=1;

EDIT:

This will help you avoid overflow after the 20th number, but your program will still overflow. You can use unsigned long long, and you'll make it to the 100th sequence element.

Jacob Panikulam
  • 1,196
  • 1
  • 9
  • 12
0

Well even unsigned long long int throws out of range for higher fabonacci num(above 92) but if still interested you could store them digit by digit in array

see this https://docs.google.com/file/d/0BwtP9e5j1RbpSjhvSG4wbkhGcmM/edit

wrangler
  • 3,454
  • 1
  • 19
  • 28
0
  • Either We can store the values in dynamically created structures such as Linked list (If we want to store all the Fibonacci numbers) OR
  • We can use just three string arrays to hold the sum and temp values to print it for this purpose which will solve your issue.

Please see this for reference

Print nth Fibonacci number [upto 1000 digits]

Community
  • 1
  • 1
Shankar
  • 846
  • 8
  • 24