Skip to content
Advertisement

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

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 🙂

Advertisement

Answer

Try with recursion:

int pow(int base, int power){
    if(power == 0) return 1;
    return base * pow(base, --power);
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement