I'm currently creating a program for an assignment that uses recursive functions to calculate a exponentation algorithm using the repeated squaring method. I'm using the Eclipse debugger, and currently my code is as follows:
#include <iostream>
#include <math.h>
usingnamespace std;
int pow(int a, int x)
{
int p;
if (x == 1)
p = pow (a,1);
elseif (x % 2 == 0)
p = a * pow (a*a , (x-1)/2);
else
p = pow (a*a , x/2);
return p;
}
int main(void)
{
int a, x, p;
cout << "I will compute a^x for you." << endl;
cout << "Please enter a value for a: ";
cin >> a;
cout << "Please enter a value for x: ";
cin >> x;
p = pow(a,x);
cout << a << "^" << x << " = " << p << endl;
}
The issue is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int pow(int a, int x)
{
int p;
if (x == 1)
p = pow (a,1);
elseif (x % 2 == 0)
p = a * pow (a*a , (x-1)/2);
else
p = pow (a*a , x/2);
return p;
}
In this section I have a few if/else statements depending on the value of the exponent (x). However, when I run it through the debugger it runs the function until it hits the appropriate formula (depending on whether x is even or odd) and then suddenly loops back between if (x == 1) and p = pow (a,1). I'm not sure what is wrong here