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
You want to avoid using pow()
, right? So you used power()
instead, leading to a recursive call within the argument list. This led to a segmentation fault.
First of all, let us understand the cause of the problem. I did a pen and paper run of the algorithm and the result is pretty interesting. It turns out that for any values of x and n, after a certain number of recursions one always ends up getting power(1, 2)
. This also means that power(1, 2)
also leads to power (1, 2)
after a certain number of recursions. Thus, this power()
within a power()
leads to an infinite recursion and thus the stack overflow.
Now, to your question. Yes, this can be done without using pow() because pow(a, 2) can simply be written as a*a. So, here is a slight modification to your code:
int power(int x, int n)
{
if (n == 0) return 1;
if (n % 2 == 0) return power(x, n / 2) * power(x, n / 2);
else return x * power(x, n - 1);
}
But then, why do it this way? A more efficient way would be as follows.
int power(int x, int n)
{
if (n == 0) return 1;
if (n % 2 == 0) return power(x * x, n / 2);
else return x * power(x * x, n / 2);
}
This reduces the number of recursions needed, making the code more time and space efficient. Hope this helps!
double result = 1;
int count = 1;
public double power(double baseval, double exponent) {
if (count <= Math.Abs(exponent)){
count++;
result *= exponent<0 ?1/baseval:baseval;
power(baseval, exponent);
}
return result;
}
This works with positive, negative, and 0 value
int pow(int a, int n) {
if(n == 0) return 1;
if(n == 1) return a;
int x = pow(a, n/2);
if(n%2 == 0) {
return x*x;
}
else {
return a*x*x;
}
}