Question

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
Was it helpful?

Solution

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.)

OTHER TIPS

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.

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

Shouldn't it have 2 parameter and handle exit condition like below?

public static int exponent(int baseNum, int power) {
   if(power == 0){
      return 1;
   }else{ 
      return baseNum * exponent(baseNum, power-1);  
   }           
}

For recursion function, we need to :

  1. check stopping condition (i.e. when exp is 0, return 1)
  2. call itself with adjusted condition (i.e. base * base^(n-1) )

Here is the code.

public class Test
{
    public static int exponent(int baseNum, int exp)
    {
        if (exp<=0)
            return 1;

        return baseNum * exponent(baseNum, --exp);
    }

    public static void main(String a[])
    {
        int base=2;
        int exp =10;

        System.out.println("The power of "+exp+" in "+base+" is "+exponent(base,exp));
    }

}

Don't forget , for each recursive function , you need a base case. A stop condition` static double r2(float base, int n) {

    if (n<=0) return 1;
    return  base*r2(base,n-1);

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top