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....
#include <iostream>
usingnamespace 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 = newlong[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 longlong, but will still rather soon hit overflow, after that, you are going to need to make a class that can hold extremely large integers.