Hey everyone. I have to write a program that estimates the value of mathematical constant e by using the following formula and i have to allow the user to enter the amount of terms to calculate. the only problem is i dont really know how to get started with this.

equation : e=1+1/1!+1/2!+1/3!...

i know that i am going to have to use a counter in this..to determine how many terms to calculate...would i create the counter and then ask the user to enter a value for counter? can you do that? i am just lost with this and if somebody could give me a push in the right direction i would appreciate it. Thanks!

Recommended Answers

All 3 Replies

First write a method that calculates the n!. Then use a for loop. How many times you will iterate it's up to you.
At the for loop you will use the classic algorithm for calculating sums. Declare a sum variable and add to it the result you get from inside the loop

sorry but could you please elaborate a little more? i am still confused on how to do it, so far i have this code which works and calculates n!. as for the for statement, where would i stick it? and whatvariables would i use in it?

import java.util.Scanner;
public class Factorials {

	public static void main(String[] args) {
		
		Scanner input = new Scanner(System.in);
		
		int num;
		int nFact;
		
		System.out.println("Please enter a number: ");
		num=input.nextInt();
		
		nFact = fact(num);		
	
		System.out.println(num + "! = " + nFact + ".");	
	}
	 static int fact(int num){
		if(num<=1)
			return 1;
		
		else{
		 return num*fact(num-1);
	 }
	 
	 
	 }
}

Sum = 1+2+3+ .... + i + ...
The pattern is
Sum = Σ(i)

int sum = 0;
for (int i=0;i<N;i++) {
 sum += [B]i[/B]; // whatever is in the parenthesis Σ([B]i[/B])
}

For your sum:
1+1/1!+1/2!+1/3!...
You need to figure out what is the 'i', what is the pattern.

Compare it with the first sum

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.