Categories
Class 10

Euler Number Program in Java

The Euler Number e is used as the base of natural logarithm.

It can be approximated using the formula:
e = 1 + 1 / 1! + 1 / 2! + 1 / 3! + … 1 / n!

Write a program in Java that approximates e using a loop that terminates when the difference between two successive values of e
differ by less than 0.0000001.

class Euler{
    public static void main(String args[]){
        double e = 0.0;
        int i = 0;
        while(true){
            double temp = e;
            e += 1.0 / fact(i);
            if(e - temp < 0.0000001)
                break;
            i++;
        }
        System.out.println("e = " + e);
    }
    public static long fact(int n){
        long f = 1L;
        for(int i = 1; i <= n; i++)
            f *= i;
        return f;
    }
}