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

Recursion with integer exponentiation question. basically, this is the code from

ID: 3842139 • Letter: R

Question

Recursion with integer exponentiation question.

basically, this is the code from java book:

// Returns base ^ exponent.
// Precondition: exponent >= 0
public static int pow(int base, int exponent) {
if (exponent == 0) {
// base case; any number to 0th power is 1
return 1;
} else if (exponent % 2 == 0) {
// recursive case 1: x^y = (x^2)^(y/2)
return pow(base * base, exponent / 2);
} else {
// recursive case 2: x^y = x * x^(y-1)
return base * pow(base, exponent - 1);
}
}

I don't understand where x^y = x * x^(y-1) and x^y = (x^2)^(y/2) came from.

the book just states "we know that from mathematics, x^y = x*x^(y-1)" and I have no idea how or what mathematics derive x^y to equate x*x^(y-1) .

same applies to x^y = (x^2)^(y/2).

Explanation / Answer

what mathematics derive x^y to equate x*x^(y-1)

x^y = x*x*x*x*.....*x    y times
x^y = x * (x*x*x* .....*x) y - 1 times
x^y = x* x^(y-1) hope this helps


How x^y = (x^2)^(y/2)

This is the case when y%2 == 0 => y is even

x^y = x*x*x*........x y times
x^y = (x*x)*(x*x)*(x*x)......(x*x) pair all x, so there will be y/2 pairs exactly
x^y = (x^2)*(x^2)*......(x^2) y/2 times
x^y = (x^2)^(y/2) hope this helps

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