Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

simple question

Status
Not open for further replies.

juliam921

Programmer
May 23, 2002
13
US
I have to calculate the value of e which is equal to

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

i know that the factorial for a value is calculated by:

for( int i = 1; i <=n; i++)
fact = fact * i;

JOptionPane.showMessageDialog(null, &quot;fact = &quot; + fact);

so how do i modify this to calculate the value of e?

i tried the following, but my logic is wrong.

for( int i = 1; i <=n; i++)
fact = fact * i;

e = e + 1/fact ;
JOptionPane.showMessageDialog(null, &quot;e = &quot; + e);

As you can see, I am new to Java. Any help would be appreciated!
-Julia
 
Code:
class cal
      {
       public static void main(String args[])
              {
               int n = 3, fact=1;
               double e = 1.0;
               for (int i=1; i<=n; i++)
                   {
                    fact*=i;
                    System.out.println(fact);
                    e = e + 1/(double)fact; // an integer literal 1 is divided by a double literal fact will give a double result
                    //e = e + 1/fact; //will not give correct result
                    System.out.println(e);
                   }
              }
      }
// here is the rules
//[URL unfurl="true"]http://www.cafeaulait.org/course/week2/19.html[/URL]
 
That logic does not work. I think maybe I need a nested loop. When I do the above, no matter what I put in for n, I get fact = 1, e = 2.0.
 
Code:
float e = 0;
int n = 3;
for(int i = 1; i <= n; ++i)
{
  int fact = 1;
  for( int j = 1; i <=n; ++i)
     fact = fact * j;
  e += 1/(float)fact;
}
There is a better way to get the factorial in constant time... but I ca't remember it.
 
Code:
//correct me if I am wrong
// The result e should be 2.5 if n=3
// There is little typing error in jstreich 's code
float e = 1.0f;
int n = 10;
for(int i = 1; i <= n; ++i)
{
  int fact = 1;
  for( int j = 1; j <=i; ++j)
     fact = fact * j;
  e += 1/(float)fact;
}
 
float e = 1.0f;


What does the f do in the variable value above (1.0f)? Do you need it?

Thanks,
Julia
 
The f is needed.
float e = 1.0; This is invalid statement because Java thinks 1.0 is a double by default, so float e = 1.0f; will assign 1.0 float to e.
 
Oh, I wasn't thinking about it as e, I was thinking about the harmonic series... 1/1, 1/2, 1/3, ..., with the factorial added.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top