-3

I need to approximate e using the series: e= 1+ 1/1! +1/2!+..+1/n! which n=100000 this is what i did, but it refused to compile..

public class Test {


  public static void main(String args[]) {
      long e = 0;
      for (int i = 1; i <= 100000; i++) {
   e += 1.0 / factorial(i);       
      }

      System.out.println(e);
   }
   public static long factorial(long number) {
      if (number <= 1) return 1;
      else return number * factorial(number - 1);
   }
}
Yuri Tsoglin
  • 963
  • 4
  • 7
  • 1
    Your title doesn't make sense; this doesn't appear to transmit ten numbers, use sockets, or be in C. As for the Java question, this code compiles just fine for me, but does not run successfully. – nanofarad Oct 11 '17 at 02:06
  • Java doesn't just "refuse" to compile, you get a specific error message, usually pointing to a specific spot in the program. – chrylis -cautiouslyoptimistic- Oct 11 '17 at 02:20

2 Answers2

0

2 problems with your code:

  1. you need to define e as double.
  2. 100000 is way to much iterations and you get StackOverflow your're going to reach maximum precision on the 18's iteration and get 1.7182818284590455. It's not going to change after that.

It's also not e but that's a separate issue. You also need to add one to it if you actually want to get an approximation of e. Or start with double e = 1.

Oleg
  • 6,124
  • 2
  • 23
  • 40
0

I would use doubles instead of longs to prevent any errors.

100000 iterations is definitely not necessary. You can stop after 100 at most.

Since e = 1 + 1/n! start with e=1 or you're going to get 1.718.

A factorial method like this would be much simpler and not have to call itself

public static double factorial(int number) 
  {
  double factorial = 1;
  while (number>1)
  {
      factorial*=number;
      number--;
    }
  return factorial;
 }
faris
  • 692
  • 4
  • 18