Fibonacci Number Generation with Golden Ratio Code

The formula and explanation are all available in here in wikipedia. It won’t produce correct result for any number greater than 70.

Code Fibonacci Generation with Golden ratio:
/**
 * Author:    Asif Ahmed
 * Site:      https://quickgrid.wordpress.com
 * Problem:   Fibonacci number generation using golden ratio.
 * Technique:
 */

#include<bits/stdc++.h>
using namespace std;


int main(){

    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);

    long double phi  = 1.61803398874989484820458683436563811772030917980576286213544862270526046281890;
    long double phiN = 0.61803398874989484820458683436563811772030917980576286213544862270526046281890;


    // Change value of n to desired value.
    // Should give correct Fibonacci value for 1 to 70.
    int n = 70;

    long double F = ( pow(phi, n) - pow( phiN, n ) ) / sqrt(5);

    cout.setf(ios::fixed);
    cout << setprecision(0) << round(F) << "\n";



    return 0;
}
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s