I’m trying to solve a sample test question and I’m having trouble understanding the last part of the problem. For the first print statement, I get 32. Using that same process I get a completely different value than the one returned by my compiler. The compiler returns 32 then 1024. Using the same logic I used to get 32, I’m confused on how the compiler gets 1024. Could anyone clearly explain what I’m doing wrong?
public static void main(String[] args) {
System.out.println(f(2, 5));
System.out.println(f(2, 10));
}
public static long f(long x, long y) {
if (y == 0) {
return 1;
}
else if (y == 1) {
return x;
}
else {
long z = y / 2;
long e = f(x, z);
if (y % 2 == 0) {
return e * e;
}
else {
return x * e * e;
}
}
}
>Solution :
Just.. walk through it.
f(2, 10)
y is neither 0 nor 1, but is divisible by 2 so the else clause triggers, and the y%2 == 0 clause. e*e is returned, where e is f(2, 5).
f(2, 5)
y is neither 0 nor 1, and is not divisible by 2 so both else clauses trigger. x*e*e is returned, where x is 2 and e is f(2, 2).
f(2, 2)
y is neither 0 nor 1, but is divisible by 2 so the else clause triggers, and the y%2 == 0 clause. e*e is returned, where e is f(2, 1).
f(2, 1)
y is 1, therefore x is returned, which is 2.
Now go backwards
f(2, 1)= 2f(2, 2)=e*e= 4f(2, 5)=2*e*e= 32f(2, 10)=e*e= 1024