I have implemented a recursive function to find m^n (m raised to the power n).
Now I want to implement the same function but by dividing the problem into two equal parts, like
m^n = m^(n/2) * m^(n/2) = ... (for even n like, m^2, m^4, m^6).
With the implementation below, if I give m = 2 and n = 4, my output is 4 while it should be 16.
public class Recursion {
public static void main(String[] args) {
System.out.println(pow(2, 4));
}
public static long pow(long m,long n) {
if (n > 0)
return m * pow(m, ((n/2) - 1) * pow(m, ((n/2) - 1)));
else
return 1;
}
}
-1in your code but not your formula. The recursion should probably be something likereturn pow(m, n/2) * pow(m, (n + 1)/2);nis odd because the resulting exponent will lose a 0.5m * pow(m, n/2) * pow(m, (n - 1)/2)