Fibonacci Sequence Overflow, C++

fibonacci sequence overflow, C++

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.

Fibonacci sequence with 32 bit overflow algorithm

It's called Arbitrary-precision arithmetic, you can read more about it here.

Arbitrary-precision arithmetic, also called bignum arithmetic, multiple-precision arithmetic, or sometimes infinite-precision arithmetic, indicates that calculations are performed on numbers whose digits of precision are limited only by the available memory of the host system.

how can i store fibonacci sequence in a matrix

How about using the row and column of the matrix to calculate the "position" of that element at the fibonacci sequence?

#include <stdio.h>
#define ROWS 2
#define COLS 5

int fibonacci(int position)
{
if (position == 0)
return 0;

if (position == 1)
return 1;

return fibonacci(position - 1) + fibonacci(position - 2);
}

int main()
{
int mat[ROWS][COLS];

for(int row = 0; row < ROWS; row++)
{
for(int col = 0; col < COLS; col++)
{
/*
[0,0] = 0 [0,1] = 1, [0,2] = 2, [0,3] = 3, [0,4] = 4
[1,0] = 5 [1,1] = 6, [1,2] = 7, [1,3] = 8, [1,4] = 9
*/
mat[row][col] = fibonacci(COLS * row + col);

printf("%3d, ", mat[row][col]);
}
printf("\n");
}

return 0;
}

Fibonacci function with C

in C, in a switch statement, in a case, to have a local variable, the body of the case must be enclosed in braces '{' and '}'



Related Topics



Leave a reply



Submit