# Fibonacci Number Generator (closed form)

Page 1 of 1

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

### #1 Karel-Lodewijk Reputation: 455
• 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

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }