-3

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

TiMauzi
  • 190
  • 1
  • 3
  • 16

2 Answers2

1

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.

TiMauzi
  • 190
  • 1
  • 3
  • 16
1

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;
}
MehranB
  • 1,460
  • 2
  • 7
  • 17