Exponential Power using Recursion
For calculating power A=Bn when base B and exponent n are given, we have the recursive formula:
(a) For Positive exponents
power_positive (a, b) = a * power_positive (a, b-1) when b>0
= 1 when b=0
For example consider a=3 and b=3
power_positive(3, 3) = 3 * power_positive(3,2)
= 3 *(3 * power_positive (3,1))
= 3 *(3 * (3 * power_positive (3, 0))
= 3 *(3 * (3 * 1))
= 3 *(3 * 3)
= 27
(b) For Negative exponents
power_negative(a,b) = power_negative (a, b+1)/a when b<0
= 1 when b=0
For example consider a=2 and b=-3
power_negative(2, -3) = power_negative(2, -2)/2
= (power_negative(2, -1)/2)/2
= ((power_negative(2, 0)/2)/2)/2
= ((1/2)/2)/2
= (1/4)(1/2)
= 1/8
Write a program to find exponent of positive power and negative power by using recursion.
#include<stdio.h>
#include<conio.h>
double power_pn(double a, float b)
{
if(b==0)
return(1);
else if(b<0)
return(power_pn(a,b+1)/a);
else
return(power_pn(a,b-1));
}
void main()
{
double mantissa;
float exp;
clrscr();
printf("Enter mantissa part:");
scanf("%lf",&mantissa);
printf("\nEnter exponent:");
scanf("%f",&exp);
if(exp<0)
printf("\n Mantissa ^ exponent: %lf", power_pn(mantissa,exp));
else
printf("\n Mantissa ^ exponent: %lf", power_pn(mantissa,exp));
getch();
}
Output: Enter mantissa part: 2
Enter exponent: -3
Mantissa ^ exponent: 0.125000