Wednesday, October 1, 2014

Pow(x,n)

two methods are provided. The first uses recursion. The second one uses binary code of n. Time complexities are same: O(log n).

//first one
double pow(double x, int n) {
    if (n == 0) return 1.0;
    // Compute x^{n/2} and store the result into a temporary
    // variable to avoid unnecessary computing
    double half = pow(x, n / 2);
    if (n % 2 == 0)
        return half * half;
    else if (n > 0)
        return half * half * x;
    else
        return half * half / x;
}

//second one.  by Codeganker. He also deals with overflow.
double pow(double x, int n) {
    if (n == 0) return 1.0;
    double res=1.0;
    if(n<0)
        x=1.0/x;
    bool isNeg=false;
   
    if(x<0&&n&1==1)
        isNeg=true;
    n=abs(n);
    x=abs(x);
    while(n>0){
        if(n&1==1)
            res*=x;
        x*=x;
        n=n>>1;
    }
    return isNeg?-res:res;
}

No comments:

Post a Comment