// fibo5.cpp
// Glenn G. Chappell
// 30 Sep 2009
//
// For CS 311 Fall 2009
// Computing Fibonacci Numbers
// Version #5: Formula

#include <iostream>
using std::cout;
using std::endl;
using std::cin;
#include <cmath>
using std::sqrt;
using std::pow;


// Define numeric type for holding a (large?) Fibonacci number
typedef long long bignum;
// NOTE: (long long) is not a built-in type in ANSI-1998 C++.
// Use "long" above to make this program ANSI-1998 compliant.
// (And probably reduce the upper limit of the loop in function main.)

// fibo
// Given n, returns F(n) (the nth Fibonacci number).
// F(0) = 0. F(1) = 1. For n >= 2, F(n) = F(n-2) + F(n-1).
// Pre:
//     n >= 0.
//     F(n) is a valid bignum value.
//     F(n) can be computed accurately using phi^n/sqrt(5)
//      with the (long double) type.
// Notes:
//     If bignum is 32-bit signed integer,
//      then first two preconditions hold for 0 <= n <= 46.
//     If bignum is 64-bit signed integer,
//      then first two preconditions hold for 0 <= n <= 92.
//     If (long double) is 96-bit IEEE floating-point,
//      then third precondition holds for 0 <= n <= 70.
// Post:
//     Return value is F(n).
// Does not throw.
bignum fibo(int n)
{
    typedef long double bigfloat;  // High-precision floating-point type
    const bigfloat sqrt5 = sqrt(5.);
    const bigfloat phi = (1. + sqrt5) / 2.;  // "Golden ratio"
    bigfloat nearly = pow(phi, n) / sqrt5;   // phi^n/sqrt(5)
    // Our Fibonacci number is the nearest integer
    return bignum(nearly + 0.5);
}


int main()
{
    cout << "Fibonacci Numbers" << endl;
    cout << endl;
    for (int i = 0; i <= 70; ++i)
        // We only go to 70, since we are using floating-point
    {
        cout << i << ": " << fibo(i) << endl;
    }
    cout << endl;

    cout << "Press ENTER to quit ";
    while (cin.get() != '\n') ;

    return 0;
}

