Exponential Function Using Recursion

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
double e(int m, int n){
double r;
static double p = 1, f = 1;
if (n==0) {
return 1;
} else {
r = e(m, n-1);
p = p*m;
f = f*n;
return r + p/f;
}
}

int main(int argc, const char * argv[]) {
printf("%lf\n", e(1,10));
return 0;
}

Use horner’s rule

1
2
3
4
5
6
7
8
9
10
11
12
13
14
double e(int m, int n){
static double s = 1;
if(n==0){
return s;
} else {
s = 1 + m*s/n;
return e(m, n-1);
}
}

int main(int argc, const char * argv[]) {
printf("%lf\n", e(1,10));
return 0;
}

Output

1
2
2.718282
Program ended with exit code: 0