DEV Community

Discussion on: Let's Get Clever #1: Fibonacci Sequence

Collapse
 
_bigblind profile image
Frederik 👨‍💻➡️🌐 Creemers • Edited

Python solution that uses the fact that the ratio of consecutive numbers in the sequence approaches Phi

def fib(n):
    if n < 3:
        return 1
    return int(round(1.618 * fib(n-1)))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
codemouse92 profile image
Jason C. McDonald

This one is absolutely beautiful.

Collapse
 
kamalhm profile image
Kamal

I tried running the code but when I tried to run fib(10) it returns 1, did i do something wrong?

Collapse
 
_bigblind profile image
Frederik 👨‍💻➡️🌐 Creemers

Nope, I made a stupid mistake when writing this function on Dev.to, I originally wrote it in the REPL. Fixing it now.

Collapse
 
grumpytechdude profile image
Alex Sinclair

Excellent stuff!

Collapse
 
mortoray profile image
edA‑qa mort‑ora‑y

This is closely related to my closed form solution, as they are both based on Binet's Formula

Using a hard-coded value, mine can be reduced as well:

import math

sq5 = math.sqrt(5.0)
φ = (1.0 + sq5)/2.0
ψ = -1/φ

def fib_x( n ):
    return  int( (φ ** n - ψ ** n) / sq5 )

for i in range(20):
    print(fib_x(i))

Where φ is the Phi value you are using.

Collapse
 
kamalhm profile image
Kamal

Wow, so we can actually get O(1) with this? Amazing

Thread Thread
 
radu1999 profile image
Chivereanu Radu

It s not actually O(1) since ** n takes time too :))