How to write a function that can calculate power in Java. No loops

后端 未结 9 1104
一个人的身影
一个人的身影 2021-01-03 08:28

I\'ve been trying to write a simple function in Java that can calculate a number to the nth power without using loops.
I then found the Math.pow(a, b) class...

9条回答
  •  隐瞒了意图╮
    2021-01-03 09:29

    This one handles negative exponential:

    public static double pow(double base, int e) {
        int inc;
        if(e <= 0) {
            base = 1.0 / base;
            inc = 1;
        }
        else {
            inc = -1;
        }
        return doPow(base, e, inc);
    }
    
    private static double doPow(double base, int e, int inc) {
        if(e == 0) {
            return 1;
        }
        return base * doPow(base, e + inc, inc);
    }
    

提交回复
热议问题