Posts Tagged ‘factorial’

Euler’s Constant

21. May 2009

No Comments »

Calculate Euler’s constant.

#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);
}