Sunday, May 13, 2007

Fast Exponential

Generally, we can compute exponentials in a linear-recursive way.
For example: exp(b, n) = b * b * ... * b which requires n steps.

But there is a faster approach which makes use of successive squaring, for instance, to compute exp(b, 8):
b^2 = b * b
b^4 = b^2 * b^2
b^8 = b^4 * b^4

This method needs only 3 steps instead of 8, and works fine or exponents that are powers of 2. Of course we can expand this to general usage with the help of the following rules:
b^n = (b^(n/2))^2 if n is even;
b^n = b* (b^(n-1)) if n is odd.

So, we can compute exp(b, n) with time complexity costs O(logn) rather than O(n).

Inspired by this method, you can even find a cleverer algorithm to compute the Fibonacci numbers in a logarithmic number of steps.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home