Write a program to compute the value of Euler’s number e, that is used as the base of natural logarithms. Use the following formula? e=1+1/1!+1/2!+1/3!………………1/n!

Below is a Java program that computes the value of Euler’s number using the provided formula:

e=1+1/1!+1/2!+1/3!………………1/n!

The program will prompt the user for the value of and then calculate up to the -th term.​

				
					import java.util.Scanner;

public class EulerNumber {

    // Function to calculate factorial of a number
    public static double factorial(int n) {
        double fact = 1;
        for (int i = 1; i <= n; i++) {
            fact *= i;
        }
        return fact;
    }

    // Function to calculate Euler's number e up to n terms
    public static double calculateE(int n) {
        double e = 1.0;
        for (int i = 1; i <= n; i++) {
            e += 1.0 / factorial(i);
        }
        return e;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Prompt the user to enter the number of terms
        System.out.print("Enter the number of terms: ");
        int n = scanner.nextInt();

        // Calculate Euler's number e
        double e = calculateE(n);

        // Output the result
        System.out.printf("The value of Euler's number e up to %d terms is: %.15f\n", n, e);

        scanner.close();
    }
}

				
			

Explanation:

  1. The program defines a factorial method to compute the factorial of a given number.
  2. The calculateE method computes the value of using the given series formula.
  3. In the main method, the program prompts the user to enter the number of terms .
  4. It calls the calculateE method to compute the value of up to terms.
  5. Finally, it prints the calculated value of with a precision of 15 decimal places.

Sample Output:

				
					Enter the number of terms: 10
The value of Euler's number e up to 10 terms is: 2.718281801146385

				
			

In this example, when the user inputs 10, the program calculates and outputs the value of as approximately 2.718281801146385.

Scroll to Top