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
Crtp -- Accessing Incomplete Type Members
Understanding Gsl::Narrow Implementation
How to Invoke a User-Defined Conversion Function via List-Initialization
Programmatically Check Whether My MAChine Has Internet Access or Not
C++11: "Narrowing Conversion Inside { }" with Modulus
Is Using an Union in Place of a Cast Well Defined
Passing a C++ Complex Array to C
Std::Stod Throws Out_Of_Range Error for a String That Should Be Valid
Will Memcpy or Memmove Cause Problems Copying Classes
Print Out All Combinations of Index
Visual Studio 2013 Fatal Error C1041 /Fs
The Fastest Way to Retrieve 16K Key-Value Pairs
Rodrigues into Eulerangles and Vice Versa
Pointer Comparisons ">" with One Before the First Element of an Array Object
How to Alter Qt Widgets in Winapi Threads
Receiving Only Necessary Data with C++ Socket