4 ms·
Well, iterative (and smart tail recursive [0]) solutions are going to be roughly O(n) for the nth Fibonacci number, assuming addition is O(1). In bignum territo
by camccann 17y ago
Well, iterative (and smart tail recursive [0]) solutions are going to be roughly O(n) for the nth Fibonacci number, assuming addition is O(1). In bignum territory, addition isn't free, but is still pretty cheap.
The closed form solution involves computing something raised to the power of n, so would be O(log n) assuming nonintegral multiplication is O(1), which is... not so much the case. Given that the (sqrt 5) factors will always be eliminated by the end you can manipulate things to work with only integers, at the expense of complicating the algorithm.
The matrix-based solution, which I had forgotten, is also of the form x^n, so is probably isomorphic to a sufficiently clever handling of Binet's formula that completely avoids the (sqrt 5) terms.
So, yes, good call, the matrix approach is better--you win this round.
[0] The naive un-memoized recursive algorithm, such as the recursive solution in the linked article, is not only not tail-recursive, but manages to have time complexity of precisely O(fib(n)). If that doesn't make you die a little inside, you're made of sterner stuff than I.
- gjm11 17y agoWith a dumb bignum library addition will be O(d) and multiplication will be O(d^2), d being the number of digits; d increases linearly with index, so to compute the n'th Fibonacci number by naive iteration will be O(d^2), whereas doing it by repeated squaring will involve (ignoring lots of constant factors) one size-n multiply, one size-n/2 multiply, one size-n/4 multiply, etc., so also O(d^2). So, same order of magnitude, but it seems quite possible that the constant factor will be worse. And yes, the naive recursive approach is a total disaster. Pretty code, though, and if you have language or library support for memoization you can just write the naive recursive function and demand that it be memoized.