I\'m programming for a while now(beginner), and recursive functions are a somewhat abstract concept for me. I would not say I\'m stuck, program works fine, I\'m just wonderi
The code:
int power(int x, int n)
{
if (n == 0) return 1;
if (n % 2 == 0) return power(power(x, n / 2), 2);
else return x * power(x, n - 1);
}
does not work because when n is even power is called with n = 2 which is even and then power is called with n = 2 which is even and then power is called with n = 2 ... until ... stack overflow!
Simple solution:
int power(int x, int n)
{
if (n == 0) return 1;
if (n % 2 == 0) {
if (n == 2) return x * x;
return power(power(x, n / 2), 2);
}
else return x * power(x, n - 1);
}