C++ Fibonacci sequence help!

Hey there! The assignment is the the Fibonacci sequence except the user has to input how many elements they'd like to run for. We have to dynmically allocate memory this time, and build the array around it.

This is what I have so far, it seems to work but when I input large numbers (like 100 or 200) the code starts returning negative numbers and going crazy....

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;

int main(){
	long n;

cout << "please input the number of elements you would like this fibonacci sequence to run"<<endl;
cin>>n;
cout<<endl<<endl;

	long* fib = new long[n]; 
	for(long i=2; i<n; i++)
	{
		fib[0]=0;
		fib[1]=1;
		fib[i]=fib[i-1]+fib[i-2];
	}
	
       
        for(long i = 0; i < n; i++) cout << fib[i] << ' ';

        delete[] fib;
		system ("pause");
		return 0;
}
Do you need to keep the whole sequence in memory, or could you just keep the last 2, because that's all that's needed to find the next.

At 100, you are hitting overflow, you can change the data type to long long, but will still rather soon hit overflow, after that, you are going to need to make a class that can hold extremely large integers.
which variable should I change to long long? which is the one the code depends on?
Topic archived. No new replies allowed.