0 Replies - 1833 Views - Last Post: 03 February 2012 - 05:32 PM

#1 Karel-Lodewijk   User is offline

  • D.I.C Addict
  • member icon

Reputation: 454
  • View blog
  • Posts: 864
  • Joined: 17-March 11

Fibonacci Number Generator (closed form)

Posted 03 February 2012 - 05:32 PM

Description: 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....bonacci_number.
#include <iostream>
#include <cmath>

//calculates the nth fibonacci number
int fib(int n) {
    const double phi = (1.0 + sqrt(5.0)) / 2.0;
    const double psi = -1.0/phi;
    return (pow(phi, n) - pow(psi, n)) / sqrt(5.0); 
}

int main()  {
    for (int i = 1; i < 20; i++) {
        std::cout << fib(i) << std::endl;
    }
}


Is This A Good Question/Topic? 0
  • +

Page 1 of 1