2012/12/16

Recursive & Iterative Way to compute X to the power N - O(LogN)


  • xn/2­·xn/2­ if n is even, or
  • x(n-1)/2·­x(n-1)/2·x, if n is odd.

Recursive:

Recursive-Power(x, n):
  if n == 1
    return x
  if n is even
    y = Recursive-Power(x, n/2)
    return y*y
  else
    y = Recursive-Power(x, (n-1)/2)
    return y*y*x

Iterative:

int powFast(int b, int e) {
    int p = 1;   
    while (e > 0) {
        if(e%2 != 0) {
            p = p*b;  
        } 
        e = e / 2;
        b = b * b;
    }
    return p;
}

Reference:
http://www.catonmat.net/blog/mit-introduction-to-algorithms-part-two/
http://stackoverflow.com/questions/4303046/how-can-i-implement-iterative-version-logn-base-to-power

No comments:

Post a Comment