This is the Java Program to Find the Sum of the Series 1/1!+1/2!+1/3!+…1/N!.
Given a number n, write a Java Program to Find the Sum of the Series 1/1!+1/2!+1/3!+…1/N!.
Start a loop from 1 to n, and add the factorial of the reciprocal of the loop variable to the sum.
The factorial of the loop variable can be calculated using a nested loop.
Here is the source code of the Java Program to Find the Sum of the series 1/1!+1/2!+1/3!+…1/N!. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.
//Java Program to Find the Sum of the series 1/1!+1/2!+1/3!+...1/N!
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Series82 {
// Function to calculate and display the sum of the series.
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n;
try{
System.out.println("Enter the number of terms in the series");
n = Integer.parseInt(br.readLine());
}catch (Exception e){
System.out.println("An error occurred");
return;
}
double sum = 0;
double i;
int j;
long fac;
for(i=1; i<=n;i++){
fac =1;
for(j=2; j<=i;j++){
fac*=j;
}
sum +=(1.0d/fac);
}
System.out.println("The sum is " + sum);
}
}
In the function main(), firstly the variable n is entered, then the loop for(i=1; i<=n;i++), is used to sum the reciprocal of the factorial of the loop variable. The loop for(j=2; j<=i;j++) is used to calculate the factorial of i.
Time Complexity: O(n2).
Case 1 (Simple Test Case): Enter the number of terms in the series 34 The sum is 1.7182818284590455
Sanfoundry Global Education & Learning Series – Java Programs..
- Practice Programming MCQs
- Check Java Books
- Check Programming Books
- Apply for Computer Science Internship
- Practice BCA MCQs