Implement the recursive approach to raising a number to a power, as described in
ID: 3769701 • Letter: I
Question
Implement the recursive approach to raising a number to a power, as described in the “Raising a Number to a Power” section near the end of this chapter. Write the recursive power() function and a main() routine to test it.
Please don't MODIFY/ EDIT the main method!!
import java.io.IOException;
class raisePower
{
public static int power(int base, long pow)
{
if(pow==2)
{
return base*base;
}
else if(pow%2 != 0)
{
return base*power(base*base, pow/2);
}
else
{
return power(base*base, pow/2);
}
}
}
public static void main(String[] args) throws IOException
{
PowerCalc calc = new PowerCalc();
long x = 3;
int y = 18;
long p = calc.power(base, pow);
System.out.println(base + " raised to the " + pow + "the power is " + p);
} // end main()
} // end class PowerApp
Explanation / Answer
import java.io.IOException;
class raisePower
{
public static int power(int base, long pow)
{
if(pow==0)
return 1;
else
return (base * power(base,pow-1));
}
}
public static void main(String[] args) throws IOException
{
PowerCalc calc = new PowerCalc();
long x = 3;
int y = 18;
long p = calc.power(base, pow);
System.out.println(base + " raised to the " + pow + "the power is " + p);
} // end main()
} // end class PowerApp