Search

# Java program to calculate exponential e^x by using factorial and exp methods

Java program to calculate exponential of a given formula | Problem Solving in Java | AskTheCode

Problem:

The exponential e^x can be calculated using the formula:

e^x = 1 + x/1! + x^2/2! + x^3/3!+ ... x^n/n!

The factorial of non-negative integer n is written n! And is defined as follows:

n! = n * (n-1) * (n-2) * ... * 1

n! = 1 (if n = 0)

Write a Java program that contains two methods factorial and exp according to the formulas that we mentioned above. The main task for this program is to ask the user to enter a number and calculate its exponential, then display the result.

### Sample input:

Enter a number: 8

### Sample output:

The result is: 1765

Code:

```import java.lang.*;
import java.io.*;

class Calc_Exponential{
public static void main (String[] args) throws IOException{
System.out.print("Enter a number: ");
int result = exp(n);
System.out.print("The result is: "+result);
}

/* Method that returns factorial of a Number*/
static int factorial(int n){
if (n == 1) {
return 1;
}
return n * factorial(n-1);
}

/* Method that calculates the exponential */
static int exp(int n){
int sum = 1;
for (int i = 1; i <= n; i++) {
sum += Math.pow(n, i) / factorial(i);
}
return sum;
}
}```

### Recent Posts

See All

#### Golf CodeChef Solution in Java - AskTheCode

CodeChef May Long Challenge Solution | Golf (LKDNGOLF) solution | AskTheCode Golf (LKDNGOLF) solution Problem: It's a lockdown. You’re bored in your house and are playing golf in the hallway. The hall

#### Solubility - CodeChef Solution in Java and C++| AskTheCode

CodeChef May Long Challenge Solution | Solubility (SOLBLTY) solution | AskTheCode Solubility (SOLBLTY) solution Problem: Suppose for a unit rise in temperature, the solubility of sugar in water increa

#### Valid Paths CodeChef Solution in C++ | AskTheCode

CodeChef May Long Challenge Solution | Valid Paths (VPATH) solution | AskTheCode Valid Paths (VPATH) CodeChef solution Problem: You are given a tree with N nodes numbered from 1 to N. A set S of nodes