How to write an algorithm in order to calculate Euler's number

188 Views Asked by At

How does one write an algorithm that calculates the value of e by receiving the natural number N from the user? The following equation needs to be used:

enter image description here

2

There are 2 best solutions below

0
TiMauzi On

I assume you want an algorithm description in something like pseudocode. Then your algorithm could look something like this:

function factorial(x)
begin
   f := 1;
   for i := x downto 1 do
      f := f*i;
   end;
   factorial := f;
end;


procedure euler(n)
begin
    e := 0;
    for i := 1 to n do
        e := e + (1/factorial(i));
    end;
    print e;
end.

Note that I used a Pascal-like pseudocode variant here. This method isn't the quickest, either, since there is an extra loop for every factorial from 1 to n, but I chose this way to show an intuitive way of solving this problem.

3
MehranB On

Here is a simple solution in java:

float result = 1;
int fact = 1;

for (int i = 2; i <= n; i++) {
    fact *= i;
    float fraction = 1f / fact;
    result += fraction;
}