is program right??

i write a program that calculate the sum of first nine terms like(1/3!+5/4!+9/5!+....) i am not sure that is right or wrong...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 #include<iostream>
using namespace std;
main()
{
	int i,j,f;
	long sum=0.0;
	for(i=1;i<=33;i=i+4)
	{
		f=1;
		for(j=3;j<=12;j++)
		f=f*j;
		sum=sum+f/i;
	}
	cout<<"Sum is:"<<sum<<endl;
}
Last edited on
long sum = 0.0 is equivalent to long int sum = 0.0
(somebody please correct me if I'm wrong!)

So I think you meant to write double sum = 0.0;

I think your logic is faulty. You've got the right idea for the outer for-loop though.

For for(i=1; i<=2; i=i+4) {}
Your program will calculate:
(0+(12!-3!)/1) + (1+(12!-4!)/2)

Taking common factors,
12!-3! + 12!-2! - 4!-2!
12!(3! + 2!) - 4! - 2!
2!( 12!(3!+1) - 4! - 1)

To find the factorial of a number, you need something like this:
fact=1;
for(i=1; i<=num; i++)
fact *= i;

3! would be 3x2x1
4! would be 4x3x2x1

After finding fact do (i/fact)

sum=sum+f/i; would become sum = sum + i/fact;

Avoid explicitly calculating factorials: they grow far too fast.
You actually need 1/factorial, and this can be computed successively in the loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

int main()
{
   const int N = 9;
   double reciprocal = 1.0 / 6.0, series = reciprocal;

   for ( int term = 2; term <= N; term++ )
   {
      reciprocal /= ( term + 2 );               // update 1/factorial
      series += ( 4 * term - 3 ) * reciprocal;  // update partial sum
   }

   cout.precision( 10 );
   cout << "Sum to " << setw( 2 ) << N << " terms is " << series << '\n';
   cout << "Sum to infinity is " << 19.5 - 7 * exp( 1.0 ) << '\n';
}


Sum to  9 terms is 0.4720271164
Sum to infinity is 0.4720272008
lastchance that's awesome.

By the way can you explain how you got 19.5 - 7 * exp(1.0) briefly?
By the way can you explain how you got 19.5 - 7 * exp(1.0) briefly?


See: https://imgur.com/a/Bcz9R2y
What tool did you use to write that image? By the way appreciate it.
It is just word-processed in Microsoft Word (with the newer equation editor) and then screen-captured, @Grime. You wouldn't have read my original handwritten scribble.
Thanks...
Topic archived. No new replies allowed.