Recursive Exponent Method

33,680

Solution 1

Create an auxiliary method to do the recursion. It should have two arguments: the base and the exponent. Call it with a value of 10 for the exponent and have it recurse with (exponent-1). The base case is exponent == 0, in which case it should return 1. (You can also use exponent == 1 as a base case, in which case it should return the base.)

Solution 2

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.

Solution 3

The following is what my instructor, Professor Penn Wu, provided in his lecture note.

public class Exp
{
public static int exponent(int a, int n)
{
if (n==0) { return 1; } // base
else // recursion
{
a *= exponent(a, n-1);
return a;
}
}
public static void main(String[] args)
{
System.out.print(exponent(2, 10));
}
}
Share:
33,680
Matt Andrzejczuk
Author by

Matt Andrzejczuk

Think differently. Don't follow trends, start them. Pay attention to the old and wise, history doesn't repeat itself exactly, but it usually rhymes. An important quality in leadership is to look for responsibilities, while taking responsibility for what you agreed to do.

Updated on May 06, 2022

Comments

  • Matt Andrzejczuk
    Matt Andrzejczuk about 2 years
    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
    
    • Luiggi Mendoza
      Luiggi Mendoza over 11 years
      There's no base case in your recursive method!
    • Louis Wasserman
      Louis Wasserman over 11 years
      If you need it to stop after ten times, you need to have a variable for how many times it's recursed.
    • Vishy
      Vishy over 11 years
      You need to pass the power as an argument like power(baseName, n); decrease the power by one each time you recurse.