Factorial Series in Java (Series #7)

Factorial Series in Java

Question : Write a program to print the following series.

S = 2! + (2! + 3!) - (2! + 3! + 5!) + (2! + 3! + 5! + 7!)......... n terms

The above series is very easy to solve

Logic :-

  • First input number of terms
  • The nth term will contain 'n' number of terms (ex- if n = 2, then it will contain 2 terms i.e. (2! + 3!))
  • calculate the nth term by first finding the first 'n' number of prime numbers
  • Now, calculate factorial of each prime number
  • Add the factorials of all the prime numbers
  • Now if the nth term is odd and not the first then it will be a negative term
  • else it will be a positive term
  • Store the result in the variable accordingly
  • Print the result

Note : To understand the program clearly watch this video : https://youtu.be/CRX9zDJYY4U



Program to print the Series Program :-

Program :-

import java.io.*;
import java.util.*;
class Series7
{
    public static void main(String args[])
    {
        Scanner in = new Scanner(System.in);
        int n,i,sum=0;
        System.out.println("Enter number of Terms : ");
        n= in.nextInt();
        for(i=1;i<=n;i++) //loop for calculating particular term
        {
            int j,p=2,s=0,c=0,x=1,a,f=1;
            while(x<=i) //loop for calculating sum of prime factorials
            {
                for(j=1;j<=p;j++)
                {
                    if(p%j==0)
                    {
                        c++;
                    }
                }
                if(c==2)
                {
                    for(a=1;a<=p;a++) //calculating factor of Prime number
                    {
                        f=f*a;
                    }
                    s=s+f; //storing sum of factorial of prime number
                    f=1;
                    p++;
                    x++;
                    c=0;
                }
                else
                {
                    p++;
                    c=0;
                }
            }// end of while loop
            if(i%2!=0 && i!=1) //calculating series
            {
                sum= sum-s;
            }
            else
            {
                sum= sum+s;
            }
        }// end of for loop
        System.out.println("Sum of Series : "+sum);
    }// end of main method
}//end of class


For Proper Understanding Watch the Video :-






Watch this video : Factorial Series in Java

All the best :)
Keep Learning :)

Comments

Popular posts from this blog

Composite Number in JAVA

Frequency of each digit of a number in Java

Fibonacci Prime Series in JAVA