Code Snippets

  

C++ Source Code



Fibonacci Number Generator (closed form)

There are snippets here to calculate the nth Fibonacci number using recursion, iteration. But the Fibonacci sequence also has a closed form. See http://en.wikipedia.org/wiki/Fibonacci_number.

Submitted By: Karel-Lodewijk
Actions:
Rating:
Views: 762

Language: C++

Last Modified: February 4, 2012

Snippet


  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. //calculates the nth fibonacci number
  5. int fib(int n) {
  6.     const double phi = (1.0 + sqrt(5.0)) / 2.0;
  7.     const double psi = -1.0/phi;
  8.     return (pow(phi, n) - pow(psi, n)) / sqrt(5.0);
  9. }
  10.  
  11. int main()  {
  12.     for (int i = 1; i < 20; i++) {
  13.         std::cout << fib(i) << std::endl;
  14.     }
  15. }

Copy & Paste


Comments

There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.