Java Program to Find Sum of the Series 1/1! + 2/2! + 3/3! + ……1/N!
Factorial of a number simply returns out the multiplication of that number with all numbers lesser than the number up to 1 over which factorial is applied. Now the question arises of whether the series is convergent or divergent. According to concepts of Infinite series and factorial in mathematics, the series may not converge but it can contain a convergent subsequence.
Illustration:
n! = n * (n-1) × (n-2) × (n-3) × (n-4) × …… × 4 × 3 × 2 × 1
Input : n = 5
Processing : 1/1! + 2/2! + 3/3! + 4/4! + 5/5!
1 + 2/2 + 3/6 + 4/24 + 5/120
Output : 2.708333333333333
Approach :
- Enter the number of terms N.
- Create a function to calculate the sum of series, say, calculateSum.
- In calculateSum function(), create a variable sum which stores the total sum of the series.
- Run a loop N times.
- Call factorial function() to calculate the factorial of a given number.
- Return sum.
Implementation:
Java
import java.io.*;
class GFG {
public static double factorial( int i)
{
if (i == 1 ) {
return 1 ;
}
return i * factorial(i - 1 );
}
public static double calculateSum( int N)
{
double sum = 0 ;
for ( int i = 1 ; i <= N; i++) {
sum = sum + (( double )i / factorial(i));
}
return sum;
}
public static void main(String[] args)
{
int N = 5 ;
System.out.println( "The sum of series upto " + N
+ " terms is : "
+ calculateSum(N));
}
}
|
Output
The sum of series upto 5 terms is : 2.708333333333333
Time Complexity: O(n)
Auxiliary Space: O(n) for call stack
Last Updated :
08 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...