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

Mo Arctic picture Mo Arctic · Oct 17, 2013 · Viewed 57.9k times · Source

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... or method still can't distinguish the two am not so good with theory. So i wrote this..

public static void main(String[] args) {

    int a = 2;

    int b = 31;

    System.out.println(Math.pow(a, b));

    }

Then i wanted to make my own Math.pow without using loops i wanted it to look more simple than loops, like using some type of Repeat I made a lot of research till i came across the commons-lang3 package i tried using StringUtils.repeat
So far I think this is the Syntax:-

public static String repeat(String str, int repeat)
    StringUtils.repeat("ab", 2);

The problem i've been facing the past 24hrs or more is that StringUtils.repeat(String str, int 2); repeats strings not out puts or numbers or calculations.
Is there anything i can do to overcome this or is there any other better approach to creating a function that calculates powers?
without using loops or Math.pow

This might be funny but it took me while to figure out that StringUtils.repeat only repeats strings this is how i tried to overcome it. incase it helps

 public static int repeat(int cal, int repeat){
     cal = 2+2;
     int result = StringUtils.repeat(cal,2);
     return result;
}  

can i not use recursion maybe some thing like this

public static RepeatThis(String a)
{
     System.out.println(a);
     RepeatThis(a);
} 

just trying to understand java in dept thanks for all your comments even if there were syntax errors as long as the logic was understood that was good for me :)

Answer

Vaibhav Fouzdar picture Vaibhav Fouzdar · Dec 27, 2013

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;
    }       
}