Recursive Exponent Method

Matt Andrzejczuk picture Matt Andrzejczuk · Nov 1, 2012 · Viewed 30.4k times · Source
public static int exponent(int baseNum) {
    int temp = baseNum *= baseNum;                

        return temp * exponent(baseNum);             
}

Right now the method above does n * n into infinity if I debug it, so it still works but I need this recursive method to stop after 10 times because my instructor requires us to find the exponent given a power of 10.

The method must have only one parameter, here's some examples of calling exponent:

                System.out.println ("The power of 10 in " + n + " is " + 
                    exponent(n));

So output should be:

The power of 10 in 2 is 1024

OR

The power of 10 in 5 is 9765625

Answer

mu_sa picture mu_sa · Nov 1, 2012

Do something like

public static int exp(int pow, int num) {
    if (pow < 1) 
        return 1; 
    else
        return num * exp(pow-1, num) ;
}

public static void main (String [] args) {     
    System.out.println (exp (10, 5));
}

and do not forget the base case (i.e a condition) which tells when to stop recursion and pop the values from the stack.