Search code examples
c#integerconsole-application

Mathematical Constant E


I'm trying to write the formula that solves for e in C#.

e = 1 + (1 / 1!) + (1 / 2!) + (1 / 3!) + ...

I have written this code to solve the problem for the "n!" Fractional numbers.

//n! = n * (n - 1)*(n - 2)*...* 1
//5! = 5 * (5 - 1)*(5 - 2)*(5 - 3)*(5 - 4)*(5 - 5)
//5! = 5 * 4 * 3 * 2 * 1 * 0
//5! = 120

int num = A;
while (num > 0)
{
   A = num;
   for (int i = A - 1; i > 0; i--)
   {
      A *= i;
   }
   Console.WriteLine($"Fractorial of {A}! = {num}\n");
   num--;
}

With the n! variable discovered: I'm confused about how to implement it into the e = 1 + (1/n!) + (1/n!++)

This answer doesn't use the System.Math.E function.


Solution

  • Here's easy code snippet with explanations:

    // How many elements to sum - 
    // the more elements will be used to determine
    // e, the greater precision.
    var precision = 50;
    
    // We use Enumerable.Range(1, precision)
    // to generate sequence 1, 2, 3, ...
    // Then for each element we calculate 1 / x!,
    // Additionally forcing floating point calculations
    // by 1M. This is the main formulae.
    
    var e = 1 + Enumerable.Range(1, precision)
        .Select(x => 1M / Factorial(x))
        .Sum();
    
    // Print number
    Console.WriteLine(e);
    
    // Utility method, that recursively 
    // caluclates factorial.
    long Factorial(long number) => number > 1
        ? number * Factorial(number - 1)
        : 1;