#include <iostream>
#include <cmath>
usingnamespace std;
int main()
{
int N, f;
cout << "Which term would you like? "; cin >> N;
f = pow( 1.618033989, N ) / 2.236067978 + 0.5;
cout << f;
}
Which term would you like? 10
55
It works, but I don't suggest that you hand this in @champ195.
Fundamentally, it's a sequence of terms
1,1,2,3,5,8 ...
with a given rule to derive each term from the previous two. Since you need to do something REPEATEDLY you need to consider LOOPS. Have a read of that section in http://www.cplusplus.com/doc/tutorial/control/
Alternatively, you could use a recursive function, once you've written one for your factorial example.
#include <iostream>
int fib( int N ) { return ( N * N - N ? ( N < 0 ? fib( N + 2 ) - fib( N + 1 ) : fib( N - 2 ) + fib( N - 1 ) ) : N ); }
int main()
{
for ( int N = -10; N <= 10; N++ ) std::cout << fib( N ) << " ";
}
@lastchance from my understanding that's still computing fib(int) at run time (but it's O(1) so it doesn't really matter, in this case). I was trying to get for-loops to work at compile time to calculate fibonacci<i> to <n> but it sadly isn't that simple, apparently. But anyway... that's a discussion for another time, don't wanna hijack champ's thread.
if you want to optimize it, its hard to beat a lookup table. The series gets big enough fast enough that this is not that many values. I think it explodes out of a 64 bit int in < 100 values, but that is from memory.