Monday, 3 July 2017

Java Code to find out the exponential constant

Problem:

The exponential growth constant e is characterized by the expression

e = 1/0! + 1/1! + 1/2! + 1/3! + ........

Devise an algorithm to compute e to n terms.

Solution:

package com.myprograms;

import java.util.Scanner;

public class ExponentialConstant {

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter n value");
int n = s.nextInt();
ExponentialConstant exponentialConstant = new ExponentialConstant();
System.out.println("the exponential constant is: " + exponentialConstant.findFactorialSum(n));;
s.close();
}

public int findFactorial(int n){
int product = 1;
for(int i=1; i<= n; i++){
product = product * i;
}
return product;
}

public double findFactorialSum(int n){
double sum = 0.0;
for(int i = 0; i<= n; i++){
sum = sum + (double) 1/findFactorial(i);
}
return sum;
}

}


Output:

enter n value
4
the exponential constant is: 2.708333333333333



No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...