Euler’s Constant

Thu, May 21, 2009

C++, Snippets

Calculate Euler’s constant.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdio.h>
/**
 * This code will calculate e
 * as the sum of the infinite series
 * 1/1! + 1/2! + 1/3! + ... + 1/n!
 * g++ e.c
 * ./a.out
 */
int factorial(unsigned int i);

int main() {
    double e = 1.0;
    for (int n = 10; n > 0; n--)
        e += 1.0/factorial(n);
    printf ("e = %lgn", e);
    return 0;
}

int factorial(unsigned int i) {
    if(i == 0 || i == 1)
        return 1.0;
    return i * factorial(i-1);
}

Tags: , , , ,