This is a closed form evaluation of the n-th fibonnaci number.
The int cast is because the double isn't precise enough, thus a bit of error value accumulates. Remove it to see how much.
** Time complexity, you might get picky here and we can debate what the time complexity of **n is. In worst case it shouldn't be more than log(n) given that the generic pow is log(n).
HA! I was getting worried that the efficiency bonus goal was actually impossible, but I just had that nagging feeling there was some algorithmic way of solving this without generating each preceding element.
I'm going for the bonus points, no explicit loops nor recursion, and O(1) time*.
This is a closed form evaluation of the n-th fibonnaci number.
The
int
cast is because thedouble
isn't precise enough, thus a bit of error value accumulates. Remove it to see how much.** Time complexity, you might get picky here and we can debate what the time complexity of
**n
is. In worst case it shouldn't be more thanlog(n)
given that the genericpow
islog(n)
.Interesting in javascript this will have precision errors after fib(75).
Probably because of the limitations on floating point math precision.
HA! I was getting worried that the efficiency bonus goal was actually impossible, but I just had that nagging feeling there was some algorithmic way of solving this without generating each preceding element.
Everything is more fun with unicode: