Re:Recursive fibonacci benchmark using top languages on GitHub
by khebbie on Friday September 28, 2018 @05:15AM
(#18092001)
The rigth way to do fibonacci would probably be to add memoization...
[ Parent
| on HN ]
Re:Recursive fibonacci benchmark using top languages on GitHub
by spatulon on Friday September 28, 2018 @07:14AM
(#18092471)
Or turn it into a simple iterative process, instead of a recursive process. They explain how quite simply in SICP:
http://sarabander.github.io/sicp/html/1_002e2.xhtml (Ctrl-F "We can also formulate an iterative process for computing the Fibonacci numbers.")
Here's a Python implementation:
def fib(n):
a = 1
b = 0
i = 0
while i < n:
temp = a
a += b
b = temp
i += 1
return a
With that, fib(100000) takes half a second to compute on my machine.
Re:Recursive fibonacci benchmark using top languages on GitHub
by Al-Khwarizmi on Friday September 28, 2018 @05:19AM
(#18092014)
The "right" way to do Fibonacci is to use matrix multiplication to get the nth Fibonacci number in logarithmic time (google Fibonacci log n matrix).
Re:Recursive fibonacci benchmark using top languages on GitHub
by braythwayt on Friday September 28, 2018 @06:37AM
(#18092302)
A matrix implementatiom in JavaScript:
http://raganwald.com/2015/12/20/an-es6-program-to-compute-fi...
It is based on a Ruby implementation:
Re:Recursive fibonacci benchmark using top languages on GitHub
by toolslive on Friday September 28, 2018 @05:46AM
(#18092124)
Why not calculate it in constant time ?
https://artofproblemsolving.com/wiki/index.php?title=Binet%2...
Re:Recursive fibonacci benchmark using top languages on GitHub
by braythwayt on Friday September 28, 2018 @06:38AM
(#18092308)
As mentioned in other comments, working with floating point numbers in practice is trickier than it looks in theory:
Re:Recursive fibonacci benchmark using top languages on GitHub
by edflsafoiewq on Friday September 28, 2018 @06:01AM
(#18092171)
You can't really compute it in constant time since the number of bits in the nth Fibonacci number is O(n), so you need to take at least that long just to write the result out.
Computing with Binet's formula is also rather tricky. You just need to round φ^n/√5, but how many bits of √5 do you need to use?
Re:Recursive fibonacci benchmark using top languages on GitHub
by toolslive on Friday September 28, 2018 @06:21AM
(#18092232)
true: adding 2 64 bit numbers is constant time for me, but adding 2 4096 bit numbers is not. Eventually, even the simplest operation becomes O(ln n)