Friday, December 17, 2010

DS and Algorithms

How to find the power of a number with log(n) complexity?
Problem : Compute a^n where n belongs to N
Native approach : multiple the base exponent times. Complexity will be O(n).
How can we improve this.
Divide and Conquer method can be used.
a^n =
a^n/2 * a^n/2 if n is even;
a^(n–1)/2 * a^(n–1)/2 ⋅ a if n is odd.
T(n) = T(n/2) + Θ(1) ⇒ T(n) = O(lg n).
C++ Implementation :
double power(int base,int exp){
    if(exp == 0 ){
            return 1;
        }
    if(base == 0){
            return 0;
        }
    if(exp == 1){
            return base;
        }
    if(exp %2 == 0){
            return power(base,exp/2)* power(base,exp/2);
        }
    else{
            return (power(base,(exp-1)/2)*power(base,(exp-1)/2)*base);
        }
    }

Limitations : Negative exponent and base cases are not handled.








No comments:

Post a Comment