Recursion Problem

After thinking so much, i decided to post my problem.

My teacher asked us to make a recursion program where we need to calculate base^exponent(not using power(); from math.h) where exponent!= 1.

im still so confused even though I read many.
((ALL FILES ARE IN A PROJECT))
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
//This is from another file named "formula.h"
 void mypow(int base, int exponent)
{	

float ans=base;
int ctr = 1;
ans=ans*base;
if(exponent > 1)
while(ctr<=exponent){
mypow(base, exponent);
ctr++;               }

printf("%f", ans);
}

//This is the main "main.c"

#include <stdio.h>
#include <stdlib.h>
#include "formula.h"

int main(int argc, char *argv[]) {
	int base, exponent;
	
	printf("enter base: ");
	scanf("%d", &base);
	printf("\nenter exponent: ");
	scanf("%d", &exponent);
	mypow(base, exponent);

}
Last edited on
Let's do a stack trace of your algorithm with say b = 2 and exp = 3
base = 2, exp = 3
ans = 2
ans = ans * base = 4
ctr = 1
exponent > 1 = True
ctr <= exponent = true
mypow(2, 3) =>
base = 2, expo = 3
ans = 2 <- Problem
ctr = 1 <- Problem
exponent > 1 = True
ctr <= exponent = true
mypow(2, 3) => ad infinium

The problem is you're defining a new value of ans and ctr each call. Thus they never change and the recursion goes forever. If you do want to do it this way(there's an easier way) then you would need to pass ans and ctr by reference into the functions and define them outside.

There is a simple fast exponential recursive algorithm but for a naive simple algorithm use the following logic:

a^1 = a
a^x = a*a^(x-1)

So exponent(a, x) = a*exponent(a, x-1)

If you want to use the fast algorithm(I won't go into detail as an exercise):
Base case is the same.
a^(x) = (a*a)^x/2 if x is even
a^(x) = a * (a*a)^(x-1)/2 if x is odd
Last edited on
@Semoirethe
oh ahahah....so thats how it is...sorry for the late reply and thanks
Topic archived. No new replies allowed.