pythonalgorithmfibonaccifibonacci-heap

Computing directly nth Fibonacci term without finding previous terms using binet's formula. (in O(1) time)


from math import sqrt

n = int(input())
phi = (1 + sqrt(5))/2

fib_n = round((phi**n))

print(fib_n)

The above-mentioned code is not correct, it gives some nearer value to fib_n.

from math import sqrt

n = int(input())
phi = (1 + sqrt(5))/2

fib_n = round((phi**n)/sqrt(5))

print(fib_n)

This code works absolutely perfect after dividing by sqrt(5) in the 6th line.

My doubts are:

  1. What is the significance of dividing by sqrt(5) and why only sqrt(5) and not any other number?
  2. Can I solve the same thing using the floor or ceiling (or any other) and without dividing by root(5)?

Any help/guidance/resources are heavily appreciated!


Solution

  • This is the wrong formula. The formula should be:

    from math import sqrt
    
    n = int(input())
    phi1 = (1 + sqrt(5))/2
    phi2 = (1 - sqrt(5))/2
    
    fib_n = (pow(phi1, n) - pow(phi2, n)) / sqrt(5)
    
    print(fib_n) 
    

    The sqrt(5) comes out of the proof: Proof Basically, the sqrt(5) comes from solving the partial fractions

    Side note: pow(phi, n) is usually more efficient than phi ** n and it can also compute mods. pow(phi, n, m) gives (phi ** n) % m