Recursive function seems to be looping

Hi

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:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <math.h>
using namespace std;

int pow(int a, int x)
{
	int p;
	
	if (x == 1)
	p = pow (a,1);
	else
	if (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);
	else
	if (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
You have a couple of problems.

First, if x == 1, you recursively call yourself with x = 1.
Second, line 12 checks for even, but what you do is for the odd case.
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 guess it is showing you the recursive call.
p = pow(a, 1)?
why not just p = a?

Edit: Actually, even better would be
1
2
if (x == 1)
    return a;
Last edited on
Topic archived. No new replies allowed.