Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix the code for " e = 1 + 1/1! + 1/2! + 1/3! + ...... + 1/n! "?

Tags:

c

This is what I came up with:

#include <stdio.h>

int main (void)
{
  int n, i, j;
  float e = 1.0, nFact = 1.0;

  printf ("please enter the number");
  scanf ("%d", &n);

  for (i = 1; i <= n ; i++)
  {
    for (j = 1; j <= i; j++)
    {
      nFact *= j;
    }
    e = e + (1.0 / nFact);
  }

  printf ("The value of 'e' is : %f", e);
  return 0;
}

This is what I get from this code. Input: 3 Output: 2.58333 (which is close to 2.6666...)

But for n=3, e should give 2.6666.. as a value.

Am I doing something wrong here? How can I get the proper output?

like image 994
Monzir Avatar asked Sep 13 '12 09:09

Monzir


3 Answers

You are needlessly calculating the factorial in every iteration. Just replace the inner loop by nFact *= i;.

#include<stdio.h>

int main (void)
{
int n,i,j;
float e=1.0, nFact=1;

printf("please enter the number");
scanf("%d", &n);

for( i =1; i<= n ; i++)
{
    nFact*=i;
    e = e + (1.0/ nFact);
}

printf("The value of 'e' is : %f", e);

return 0;
}
like image 173
Henrik Avatar answered Oct 16 '22 13:10

Henrik


Am i doing something wrong here?

You have forgotten to set the factorial variable to one. So, your variable is getting smaller quickly. This makes (1.0/nFact) even smaller and that is why you get smaller e.

nFact=1.0;     //add this line so it resets to 1.0 everytime a factorial is needed
for( j = 1  ; j <= i; j++)
{
    nFact *= j;
    e = e + (1.0/ nFact);
}
//only single loop is more than enough

You are getting your factorial by O(n) complexity. Why not save the old value and use it in every iteration?(O(1)--->no need the factorial-loop. Just use old value since you are not resetting it. (Just multiply by i)

how can i get the proper output?

After the 11st or 12th iteration, your float would not give enough precision-resolution-minimum step. Double or BıgDecimal seems better if your going for science.

like image 34
huseyin tugrul buyukisik Avatar answered Oct 16 '22 15:10

huseyin tugrul buyukisik


That loop is very inefficient: Note how your inner loop computes the same thing over and over!

Instead, you should keep a running term and update it:

double term = 1;
double result = term;

for (unsigned int i = 1; i != n; ++i)
{
    term /= i;
    result += term;
}

printf("With %u steps we compute %f.\n", n, result);
like image 2
Kerrek SB Avatar answered Oct 16 '22 13:10

Kerrek SB