Problem
Compute the nth Fibonacci number.
Solution
#include <iostream>
using namespace std;
int nth_fib(int n)
{
if(n < 0){
cout << "n cannot be less than 0" << endl;
}
if(n == 0 || n == 1){
return 1;
}
int a =1, b = 1;
while(n > 0){
int t = a + b;
a = b;
b = t;
n -- ;
}
return a;
}
int nth_fib2(int n)
{
if(n < 0){
cout << "n cannot be less than 0" << endl;
}
if(n == 0 || n == 1){
return 1;
}
return nth_fib2(n-1) + nth_fib2(n-2);
}
int main(int argc, char* argv[])
{
for(int i = 0; i < 13; i ++){
cout << i << " -- " << nth_fib2(i) << endl;
}
return 0;
}