user3536228
user3536228

Reputation: 73

Fcatorial Sum not working correctly

I am using Dev c++ and my code is in c . I want to program a summ-calculator . that sums the number of terms of the following series

1/1! + 2/2! + 3/3! + .... terms are taken from the input

here is my code but it hangs when i run it

#include<stdio.h>
#include<conio.h>
int main(void)
{
long i,j,facto=1,inp;
double sum=0;
scanf("%ld",&inp);
for (i=0;i<inp;i++)
{
    for (j=i;j>1;j--)
    {
        facto *= j;
    }
    sum += i / facto;
}
printf("%f",sum);

getch();
return 0;
}

Upvotes: 0

Views: 72

Answers (2)

user3451749
user3451749

Reputation:

Change
for (i=0;i<inp;i++) to for (i=1;i<=inp;i++)
And
for (j=i;j>1;j--) to for (j=i;j>=1;j--)
And
sum += i / facto; to sum += i*1.0 / facto;
And
After sum += i*1.0 / facto; put facto =1;

Upvotes: 0

HelloWorld123456789
HelloWorld123456789

Reputation: 5369

You have several problems with the code:

  1. You don't need to have the inner loop at all. This takes up much of the time, and is probably why you don't see the output often (probably the reason for hang ing). Do like this:

    facto = 1;
    for (i=1;i<=inp;i++)
    {
        facto *= i; 
        sum += i / facto;
    }
    
  2. Since both i and facto are ints, i / facto is 0 most of the time. So modify it.

    sum += 1. * i / facto;
    

Upvotes: 1

Related Questions