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)))
This one is absolutely beautiful.
I tried running the code but when I tried to run fib(10) it returns 1, did i do something wrong?
1
Nope, I made a stupid mistake when writing this function on Dev.to, I originally wrote it in the REPL. Fixing it now.
Excellent stuff!
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.
φ
Wow, so we can actually get O(1) with this? Amazing
It s not actually O(1) since ** n takes time too :))
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Python solution that uses the fact that the ratio of consecutive numbers in the sequence approaches Phi
This one is absolutely beautiful.
I tried running the code but when I tried to run fib(10) it returns
1
, did i do something wrong?Nope, I made a stupid mistake when writing this function on Dev.to, I originally wrote it in the REPL. Fixing it now.
Excellent stuff!
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:
Where
φ
is the Phi value you are using.Wow, so we can actually get O(1) with this? Amazing
It s not actually O(1) since ** n takes time too :))