Taylor Series (Horner)
e^x = 1 + x / 1 + x^2 / 2! + x^3 / 3! + x^4 / 4! + ... n times
This method will be faster, by taking less number of multiplications. First, we can rewrite the formula as:
x = x / 1 + x² / (1 * 2) + x³ / 1 * 2 * 3 + xⓠ/ 1 * 2 * 3 * 4
We can reduce from quadratic O(n²) to linear O(n)
Using iterative loop:
double e(int x, int n) {
double s = 1;
for (n > 0; n--) {
s = 1 + x / n * s;
}
return s;
}
Recursive version:
double e(int x, int n) {
static double s = 1;
if (n == 0)
return s;
s = 1 + x / n * s;
return e(x, n - 1);
}