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

后端 未结 9 1109
一个人的身影
一个人的身影 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:28

    Another implementation with O(Log(n)) complexity

    public static long pow(long base, long exp){        
        if(exp ==0){
            return 1;
        }
        if(exp ==1){
            return base;
        }
    
        if(exp % 2 == 0){
            long half = pow(base, exp/2);
            return half * half;
        }else{
            long half = pow(base, (exp -1)/2);
            return base * half * half;
        }       
    }
    

提交回复
热议问题