yea, im just looking for a way to make the function go quicker than using a for loop, i know how to put it together with if statements, but i dont want 40 if statements...
Don't send PMs needlessly. PMs can't be searched so other people won't be compelled to not ask the same question.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
long getFibonacciNumber( long n )
{
// expect that n is a positive number.
assert( n >= 0 );
// Base Case: where n < 2, i.e. 0 and 1, we return the first two numbers in
// the sequence.
if( n < 2 )
return n;
// Inductive Step: if we know the two preceding numbers (n-1 and n-2) in the
// sequence, then we can use them to compute the n'th number.
return getFibonacciNumber( n - 1 ) + getFibonacciNumber( n - 2 );
}
getFibonacciNumber() is incorrect. The first two numbers in the series are 1 and 1, not 1 and 2.
Don't use an assert() for that. IIRC, assert()s are removed once a certain #declared constant is un#declared. Possibly _DEBUG.
To make the function iterative, you'll need three variables: one stores fib[i], another stores fib[i-1], and yet another stores fib[i-2].