Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Sorry this is so brief, I typed a lot in and accidently hit the back button on m

ID: 3625730 • Letter: S

Question

Sorry this is so brief, I typed a lot in and accidently hit the back button on my browser. I need to write a class in java and a main() tester to raise some number to a power. However, i noticed that when the numbers get large, it becomes combersom to use recursive addiotion. ex 2^8 = (2^2)^2 = (2*2^2)^2. now by sub. let 2*2 = a^2 and (a^2)^2 = , then again by sub, a^2 = c and c^2 = c*c which is some thing we can do easily with recursive addition. How do we deal with the case that the exponent is odd, because we cannot simply sub and then square...

Explanation / Answer

public static int recursion(int base, int power)
{
// base cases
if(power == 0)
return 1;
else if(power == 1)
return base;
// even exponent
else if(power%2 == 0)
{
int r = recursion(base, power/2);
return r*r;
}
// odd exponent
else
return recursion(base, power/2)*recursion(base, power/2+1);
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote