The value can be approximated by the following sum:
Write a program that takes a value x as input and outputs this sum for n taken to be each of the values 1 to 10, 50, and 100. Your program should repeat the calculation for new values of x until the user says she or he is through. The expression n! is called the factorial of n and is defined as
n! = 1 * 2 * 3 * ... * n
Use variables of type double to store the factorials (or arrange your calculation to avoid any direct calculation of factorials); otherwise, you are likely to produce integer overflow, that is, integers larger than Java allows.
Program:
// ExpX.java
import java.util.Scanner;
public class ExpX
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int x;
int n;
int k;
double fact;
double result;
char repeat;
do
{
System.out.print("Enter a value of x: ");
x = keyboard.nextInt();
result = 0;
for (n = 0; n <= 100; n++)
{
fact = 1;
for (k = 1; n > 0 && k <= n; k++)
{
fact = fact * k;
}
result += Math.pow(x, n) / fact;
if((n >= 1 && n <= 10) || n == 50 || n == 100)
{
System.out.println("At n = " + n + ", e^" + x + " = " + result);
}
}
System.out.print("\nEnter 'y' or 'Y' to repeat: ");
repeat = keyboard.next().charAt(0);
System.out.println();
}while(repeat == 'y' || repeat == 'Y');
keyboard.close();
}
}
Output:
Enter a value of x: 2
At n = 1, e^2 = 3.0
At n = 2, e^2 = 5.0
At n = 3, e^2 = 6.333333333333333
At n = 4, e^2 = 7.0
At n = 5, e^2 = 7.266666666666667
At n = 6, e^2 = 7.355555555555555
At n = 7, e^2 = 7.3809523809523805
At n = 8, e^2 = 7.387301587301587
At n = 9, e^2 = 7.3887125220458545
At n = 10, e^2 = 7.388994708994708
At n = 50, e^2 = 7.389056098930649
At n = 100, e^2 = 7.389056098930649
Enter 'y' or 'Y' to repeat: y
Enter a value of x: 5
At n = 1, e^5 = 6.0
At n = 2, e^5 = 18.5
At n = 3, e^5 = 39.33333333333333
At n = 4, e^5 = 65.375
At n = 5, e^5 = 91.41666666666667
At n = 6, e^5 = 113.11805555555556
At n = 7, e^5 = 128.61904761904762
At n = 8, e^5 = 138.30716765873015
At n = 9, e^5 = 143.68945656966488
At n = 10, e^5 = 146.38060102513225
At n = 50, e^5 = 148.41315910257657
At n = 100, e^5 = 148.41315910257657
Enter 'y' or 'Y' to repeat: n