November 18th, 2012, 10:19 PM

Please, help.
Hey guys,
I have a little problem here. The program runs and everything is fine except the actual result. The question is:
Design Java code to calculate and print ∑ (n! + 5) / (n+1)! ; n is an integer from 1 to 10.
I have written the code and I it's here:
/**
*Question #2
*/
public class Sum
{
public static void main (String [] args)
{
long a = 1;
long b = 2 * a;
double sum = (a + 5.0) / b;
long n = 3;
while(n<=11)
{
sum = sum + (double)(a + 5.0) / b;
b = n * b;
a = a * (n  1); //probably mistake here
n++;
}//end of a loop
System.out.println("The answer is " + sum);
}
}
I checked on my calculator and the result is 5.611286476
But my output is 8.520377259700176
Please, guys. I don't know where should I go. Help me find my mistake!
November 19th, 2012, 12:10 AM

Hi Daler,
The trick with programming is to keep things simple. Instead of trying to do everything in one go, try separating things out into functions. For example, you are using factorials, so break that out into a function:
Code:
public static long factorial(long x) {
long factorial = 1;
for (int i = 1; i <= x; i++) {
factorial *= i;
}
return factorial;
}
Then you can use that in your main method.
It is generally better to write code that is easily understood (and debugged) than something that is perfectly optomized.
Hope this helps.
slink
November 19th, 2012, 09:04 AM

One thing I notice about your code is you're adding the first term twice.