Question

So I need to output a sum of factorials like 1!+2!...+n!=sum I found a way to get a single factorial but I don't know how to sum them together. This is my attempt at doing so:

 System.out.println("Ievadiet ciparu");
      Scanner in = new Scanner(System.in);

      n = in.nextInt();
      if ( n < 0 )
         System.out.println("Ciparam jabut pozitivam.");
      else
      {
          while (x>2){
         for ( c = 1 ; c <= n ; c++ )
            fact = fact*c;
         sum=sum+fact;
         n=n-1;
        if (n==0) break;

      }
         System.out.println("Faktorialu summa "+sum);
Was it helpful?

Solution

Rather than have a loop 1-n and calculate each factorial elsewhere, I would accumulate the sum as you calculate the factorials - ie have two local variables; one for factorial and one for the sum:

long factorial = 1, sum = 0;
for (int i = 1; i <= n; i++) {
     factorial *= i;
     sum += factorial;
}

When tested with n = 5, sum is 153, which is correct: 1 + 2 + 6 + 24 + 120

Your problem was that the sum was outside the loop - you just needed braces like here.


Also, your while loop condition x < 2 will never change, so either the loop will never execute (if x > 1) or the loop will never terminate, because x is not changed within the loop.

OTHER TIPS

hmmm my search for finding a recursive(via recursive method calling) version of these code still getting nowhere

`public static long factorialSum(long n){
        long x = n;
        for(int i = 1; i < n; i++){
            x = (n-i)*(1+x);
        }
        return x;
    }`

if you just look at the problem more closely you'll see you can do it in linear time, the trick is in (n-1)! + n! = (n-1)!*(1 + n), to understand this more deeply i recommend add (n-2)! just to see how it grows.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top