So the recursive function I'm making takes 2 variables (x
and y
) and calculates x
to the power of y
. Just like the Math.pow
function. y
is positive, so I don't need to worry about negative exponents.
This is my code:
public static int power(int x, int y) {
if (y == 0)
return 1;
else
return x * power(x, y-1);
}
At first it seemed like it worked fine, but then I tried to enter power(50,6)
. I got -1554869184
.
Obviously this is wrong because the correct answer can't be negative.