Vikrant0 - I have created new universe out of nothing, come have a look at it! Fibonacci in O(logN)In my previous post about Fibonacci series, I discussed about some functions to compute fibonacci numbers. I started with a function of exponential complexity and ended it with a lazy O(N) complexity algorithm. is it possible to optimize it beyond O(N)? I found this beautiful algorithm while going through suggested exercise in SICP Lets look at iterative fibonacci first
This takes N operations for computing fib N. Look carefully at the transformation of a and b in fibiter function.
If we apply transformation T on (a,b) we get new (a',b'). To get N th Fibonacci number we will to apply this transformation N times in pair (1,0). We have to consider T as special case of transformation
with p = 0 & q = 1. (Hats off to the person who discovered this brilliant transformation!). Now Fibonacci computation will look something like this.
once more apply the transformation
this is equivalent to
this gives us p' and q' in terms of p & q
this gives us a handy way to square the transformation T! How does it help us in improving complexity of Fibonacci? That you will understand immediately if you know how to compute exponential of a number using multiplication and squaring. Lets look at how do we compute b raised to power n.
This is going to take n operations for computing nth power of b. But this can be improved further. For example b^4 can be computed by squaring b^2, b^8 can be computed by squaring b^4 etc.
This will compute b^N in O(logN)! This proves that if we know how to multiply and how to square, we can compute Nth power in O(logN) complexity. Use the same technique for applying the transformation we discussed for Fibonacci.
last updated 1 year ago # |
|