Version iterativa
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 26 27 28 | #include <iostream> using namespace std; int fibonacci( int n ) { if( n == 0 || n == 1 ) { return n; } // prev2 -> prev1 -> fib (prev1 + prev2) int prev2 = 0; int prev1 = 1; int fib; for(int i = 2; i <= n; i++) { fib = prev1 + prev2; prev2 = prev1; prev1 = fib; } return fib; } int main() { for(int i = 0; i < 10; i++) { cout << "fib " << i << " = " << fibonacci(i) << endl; } return 0; } |
No comments:
Post a Comment