fork(1) download
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. // compute fibonacci number for a given n>=0
  6.  
  7. int fibonacci(int n)
  8. {
  9. int f, f1, f2;
  10.  
  11. // for 0 and 1, just return the result right away
  12.  
  13. if (n==0)
  14. return 0;
  15.  
  16. if (n==1)
  17. return 1;
  18.  
  19. // f1 and f2 store the previous two fibonacci numbers
  20. // initialized to f1=0, and f2=1 (for fib0 and fib1).
  21.  
  22. f1 = 0;
  23. f2 = 1;
  24.  
  25. // compute the next fibonacci number until we get
  26. // to the target one
  27.  
  28. for (int i=2; i<=n; i++)
  29. {
  30. // compute new fibonacci number
  31. f = f1 + f2;
  32.  
  33. // move previous to one before the previous
  34. // and move current into previous, for the next
  35. // iteration (we are going to generate a new
  36. // number)
  37.  
  38. f1 = f2;
  39. f2 = f;
  40. }
  41.  
  42. return f;
  43. }
  44.  
  45. // main function
  46.  
  47. int main()
  48. {
  49. int n;
  50.  
  51. // read n from the user
  52.  
  53. cin >> n;
  54.  
  55. // compute and output the fibonacci number f(n)
  56.  
  57. cout << "fib(" << n << ") = " << fibonacci(n) << endl;
  58.  
  59. // return from main
  60.  
  61. return 0;
  62. }
Success #stdin #stdout 0.02s 2684KB
stdin
10
stdout
Enter n:
fib(10) = 55