Wednesday, June 5, 2013

Program to find nth Fibonacci number

Fibonacci number in mathematics is defined as the sum of the two previous elements in the series. Formally this is represented as 
f(n) = f(n-1) + f(n-2) where f(1) = 1 and f(2) = 1.

In this post we will see how to generate nth fibonacci number. The algorithm is self-explanatory from the program itself. So jumping in to the code directly..



#include <iostream>
using namespace std;
int fib(int n)
{
  if( n < 3)
   return 1;
   
  int a = 1;
  int b = 1;
  int c = a+b;
  
 int i = 3;
  while ( i < n)
  {
   //store sum of two previous values in c
   c = a + b;
   a = b; //b is first and
   b = c; //c is second for next iteration 
   i++;
  }
  
  return c;
}
int main()
{
 int n;
  cin>>n;
  cout<<fib(n)<<" ";
  return 0;
}