Thread: Please, help.

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    1
    Rep Power
    0

    Unhappy 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!
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    15
    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
  4. #3
  5. Java Junkie
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jan 2004
    Location
    Mobile, Alabama
    Posts
    4,021
    Rep Power
    1285
    One thing I notice about your code is you're adding the first term twice.

IMN logo majestic logo threadwatch logo seochat tools logo