Search code examples
javabluej

How to find the sum of factorial of all numbers in a series?


I want to create a program to find the sum of factorial of all numbers in a series till 20. I have to find 's' in s = 1 + (1*2) + (1*2*3) + ...(1*2*3...20). I tried a program but it is not working. I am using BlueJ IDE.

int a =1; 
    int s = 0;
    for(int i = 1; i <= 10; i++)
    {
        while (i >0)
        {

            a = a * i;
            i--;
        }
        s = s+a;
    }
    System.out.println(s);

The compiler does not show any error message but when I run the program the JVM(Java Virtual Machine) keeps loading and the output screen does not show up.


Solution

  • You can try this one :

     public class Main 
     {
     public static void main (String[]args)
     {
      int fact = 1;
      int sum = 0;
      int i, j = 1;
      for (i = 1; i <= 20; i++)
      {
        for (j = 1; j <= i; j++)
        {
          fact = fact * j;
      }
      sum += fact;
      System.out.println ("sum = " + sum);
      fact = 1;
      }
     }
    }
    

    Always give proper variable name and Try to avoid to use same variable at different places i.e you have use variable i in outer and inner loop which is not good habit.