>so changing the array to static solved everything.
No, changing the array to static and actually using the values you've cached solved everything. If you don't to the latter, your code won't be any faster than the usual recursive solution.
>It's still really slow, compared to this one
Your function might be slow, but mine is a hair faster in my tests than the code you're referring to. I've included a little test below.
>I'm still frustrated that I can't do static int fibArray [ n ]
>instead of 25, or some other constant value.
A better alternative is to pass a buffer to the function rather than use a static or global array. I've made that change in the test below.
#include <ctime>
#include <iostream>
using namespace std;
int fib ( int fibArray[], int n )
{
if ( n <= 1 )
return 1;
else {
fibArray[0] = 1;
fibArray[1] = 1;
for ( int i = 2 ; i <= n ; i++ ) {
if ( fibArray[i] == 0 )
fibArray[i] = ( fib ( fibArray, n - 1 )
+ ( fib ( fibArray, n - 2 ) ) );
}
}
return fibArray[n];
}
int main()
{
int n;
cout << "Enter number of elements: ";
cin >> n;
int * fibArray = new int[n];
clock_t start;
cout << "Beginning timer..." << endl;
start = clock();
fibArray[ 0 ] = 1;
fibArray[ 1 ] = 1;
for ( int i = 2 ; i < n ; i++ )
fibArray[ i ] = fibArray[ i - 1 ] + fibArray[ i - 2 ];
for ( int j = 0 ; j < n ; j++ )
cout << fibArray[j] << "\t";
cout << '\n';
cout << "\nThe calculation took " << showpoint
<<( double ( clock() ) - start ) / CLOCKS_PER_SEC << " seconds.\n";
cout << "\n\n-- Done --\n\n";
// Reset the array so that previous results don't make fib faster
for ( int i = 0; i < n; i++ )
fibArray[i] = 0;
cout << "Beginning timer..." << endl;
start = clock();
for ( int j = 0 ; j < n ; j++ )
cout << fib ( fibArray, j ) << "\t";
cout << '\n';
cout << "\nThe calculation took " << showpoint
<<( double ( clock() ) - start ) / CLOCKS_PER_SEC << " seconds.\n";
cout << "\n\n-- Done --\n\n";
return 0;
}