How to code the integer power of a numerical value without using library functions

The function double Power(double base, int exponent) is used to find the exponent power of base.

Considerations include: (1) If exponent is negative, the absolute value of the exponent should be calculated, and the | exponent | power of base should be calculated, then the reciprocal number should be taken;

(2) In (1), if base is 0, then the reciprocal will be wrong, so we want to judge whether base is 0.

The code is implemented as follows:

    
    double Power(double base, int exponent){
        //flag is used to mark whether the index is negative
        boolean flag = false;
       //result records the calculated results
        double result = 1;
        if(base == 0 && exponent<0){            
            return 0.0;
        }
        if(exponent == 0) return 1.0;
        if(base == 1) return 1;
        if(exponent < 0){
            flag = true;
            exponent = -exponent;
        }
        for (int i = 0; i< exponent;i++){
            result *= base;
        }
        if(flag == true) return 1.0/result;
        else return result;
    }

Another more efficient method, using recursion to achieve, for example, to solve the 32 power of the base, to solve the 16 power of the base, and then a square can be done, to find the 16 power can first find the 8 power....

public class offertest {
    //flag is used to mark whether the index is negative
    boolean flag = false;
    double Power(double base, int exponent){
        //flag is used to mark whether the index is negative
        boolean flag = false;
        double result = 1;
        if(base == 0&& exponent<0){
            return 0.0
        }
        if(exponent < 0) {
            flag = true;
            exponent = -exponent;
        }
        if(exponent == 0) return 1.0;
        if(base == 1) return 1.0;
        result = PowerWithExponent(base,exponent);
        if(flag == true) return 1.0/result;
        return result;
        
    }
    double PowerWithExponent(double base, int exponent){
        if(exponent == 0) return 1.0;
        if(exponent == 1) return base;
        double result = PowerWithExponent(base,exponent/2);
        result *= result;
        //If the exponent is odd, it needs to be multiplied by base again.
        if(exponent % 2 ==1) result = result * base;
        return result;
    }

 

Posted by mauri_gato on Sun, 06 Oct 2019 15:37:02 -0700