28
\$\begingroup\$

We all know that the Euler's number, denoted by \$e\$, to the power of some variable \$x\$, can be approximated by using the Maclaurin Series expansion:

$$e^x=\sum_{k=0}^{\infty}{\frac{x^k}{k!}}=1+x+\frac{x^2}{2!}+\frac{x^3}{3!}+\frac{x^4}{4!}+\dots$$

By letting \$x\$ equal \$1\$, we obtain

$$\sum_{k=0}^{\infty}{\frac{1}{k!}{=\frac{1}{0!}+\frac{1}{1!}+\frac{1}{2!}+\frac{1}{3!}+\frac{1}{4!}+\dots\\=1+1+\frac{1}{2}+\frac{1}{6}+\frac{1}{24}+\dots}}$$

Challenge

Write a program in any language which approximates Euler's number by taking in an input \$n\$ and calculates the series to the \$n\$th term. Note that the first term has denominator \$0!\$, not \$1!\$, i.e. \$n=1\$ corresponds to \$\frac{1}{0!}\$.

Scoring

Program with least amount of bytes wins.

\$\endgroup\$
16
  • 8
    \$\begingroup\$ Given large enough N the results will be the same if using a finite precision floating point number. Is that behaviour acceptable or does the result have to progressively get more accurate as N approaches infinity? \$\endgroup\$ Commented Jun 10, 2016 at 20:12
  • 14
    \$\begingroup\$ Some test cases would be neat. \$\endgroup\$
    – lynn
    Commented Jun 10, 2016 at 20:15
  • 8
    \$\begingroup\$ (This kind of issue is preferably resolved in the sandbox – if you post your challenges there first, golfers will give useful feedback.) \$\endgroup\$
    – lynn
    Commented Jun 10, 2016 at 20:27
  • 3
    \$\begingroup\$ Is x^n the nth term or the (n+1)th? \$\endgroup\$
    – msh210
    Commented Jun 10, 2016 at 20:31
  • 6
    \$\begingroup\$ I personally despise it, but there are people who refer to the term at index 0 as zeroth term. Independently of our thoughts on that matter, the question should be as clear as possible. Also, a few test cases to verify that the solutions are working correctly, would be very helpful. \$\endgroup\$
    – Dennis
    Commented Jun 11, 2016 at 0:04

55 Answers 55

1
2
1
\$\begingroup\$

MATLAB / Octave, 22 bytes

@(x)sum(1./gamma(1:x))

Creates an anonymous function named ans that can be called using ans(N).

This solution computes gamma(x) for each element in the array [1 ... N] which is equal to factorial(x-1). We then take the inverse of each element and sum all elements.

Online Demo

\$\endgroup\$
1
\$\begingroup\$

Perl 5, 37 bytes

Not a winner, but nice and straightforward:

$e=$p=1;$e+=1/($p*=$_)for 1..<>;say$e

Outputs for inputs from 0 to 10:

1
2
2.5
2.66666666666667
2.70833333333333
2.71666666666667
2.71805555555556
2.71825396825397
2.71827876984127
2.71828152557319
2.71828180114638
\$\endgroup\$
1
\$\begingroup\$

R, 17 bytes

sum(1/gamma(1:n))

Quite straightforward, although numerical precision issues are bound to arise at some point in time.

\$\endgroup\$
1
\$\begingroup\$

F#, 87 bytes

let rec f x=if x<2 then 1 else f(x-1)*x
let e N=Seq.sumBy(fun x->1./float(f x)){0..N-1}

Try it online!

A direct implementation of the Maclaurin expansion. Unfortunately over 35 terms the denominator is too small, so the sum becomes infinity.

\$\endgroup\$
1
\$\begingroup\$

JavaScript (ES6), 44 bytes

n=>{for(a=d=i=1;i<=n;a+=1/d)d/=i++;return a}
\$\endgroup\$
1
\$\begingroup\$

Stax, 5 bytes

òo⌠├p

Run and debug it

Produces output as a fraction.

\$\endgroup\$
1
\$\begingroup\$

cQuents, 7 bytes

;1/f_-$

Try it online!

Explanation

;           Series - output sum of first n terms in sequence
            Each term is 
 1/                      1 / 
   f   )                     factorial (           )
    _-                                         - 1
      $                                  index
\$\endgroup\$
1
\$\begingroup\$

Mathematica, 26 bytes

Sum[1/n!,{n,0,Input[]}]//N

Pretty straight forward: takes the sum of the inverse of n factorial, with n starting from 0 and all the way to the desired number. The //N is used to give an approximate value of the fraction yielded by the sum. The code can be checked online , for free, via the wolfram programming labs:

Wolfram Labs

\$\endgroup\$
2
  • \$\begingroup\$ Welcome to the site, and nice first answer! I've edited your post ever so slightly to improve clarity and to format it in the standard manner for answers on the site (# <language name> rather than ** <language> **) \$\endgroup\$ Commented Sep 25, 2019 at 16:15
  • \$\begingroup\$ @cairdcoinheringaahing Thank you very much! I appreciate! \$\endgroup\$
    – Motanovici
    Commented Sep 25, 2019 at 16:17
1
\$\begingroup\$

k4, 16 15 bytes

{+/%*/'1_',\!x}

{             } / lambda
            !x  / enumerate x; (!4 -> 0 1 2 3)
          ,\    / join scan; joins successive elements and returns intermediate results (,0;0 1;0 1 2;0 1 2 3)
       1_'      / 1 drop each; drops leading 0s (();,1;1 2;1 2 3)
    */'         / multiply over each; 1 1 2 6
   %            / reciprocal; 1 1 0.5 0.1666667
 +/             / sum
\$\endgroup\$
1
\$\begingroup\$

Wren, 81 bytes

Fn.new{|N|
var e=0
for(i in 1..N)e=e+1/(1..i).reduce{|a,b|a*b}
return e+1
}

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Keg -rr, 18 15 bytes

11(¿|:¡1$/"+"1+

Try it online!

This took a whole bunch of fiddling to figure out. It works!!

\$\endgroup\$
1
\$\begingroup\$

Ruby, 43 42 bytes

-1 byte by calculating using Rational instead of Float.

->n{(0..n).sum{|i|1/(1..i).reduce(1r,:*)}}

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Factor + math.factorials math.unicode, 27 bytes

[ iota [ n! -1 ^ ] map Σ ]

Try it online!

Explanation:

It's a quotation (anonymous function) that takes an integer from the data stack as input and leaves a ratio approximation of e on the data stack as output.

  • iota Create a range from 0 to the input where the input itself is excluded.
  • [ ... ] map Apply a quotation to each element of a sequence, collecting the results into a new sequence of the same length.
  • n! Take the factorial.
  • -1 ^ Take the reciprocal. Shorter than 1 swap / and recip.
  • Σ Sum a sequence.
\$\endgroup\$
1
\$\begingroup\$

Husk, 5 bytes

ṁo\Πŀ

Try it online!

Calculates the sum of the series as a rational number: TIO header converts this to 9 decimal digits (with an implicit point after the first digit).

\$\endgroup\$
1
\$\begingroup\$

Vyxal, s, 3 bytes

ʁ¡Ė

Try it Online!

Explanation:

     # Implicit input
ʁ    # Range [0, N)
 ¡   # Map factorial over all elements
  Ė  # Map inverse over all elements
     # 's' flag: cumulative sum top of stack and output
\$\endgroup\$
3
  • \$\begingroup\$ you have the 's' flag in the title but say the 'd' flag is a cumulative sum, which one are you using? \$\endgroup\$ Commented Apr 22, 2021 at 1:06
  • 1
    \$\begingroup\$ @ZippyMagician Whoops, my bad. I had tried d first, but s was needed. I forgot and put the wrong flag in the explanation. Fixed. \$\endgroup\$ Commented Apr 22, 2021 at 1:10
  • \$\begingroup\$ Dammit, I was just about to post this! \$\endgroup\$
    – emanresu A
    Commented Sep 2, 2021 at 11:26
1
\$\begingroup\$

Arn -Rmx, 3 bytes

1/f

This can hypothetically be infinitely precise with a large input and the use of the -p, -o, and --stack arguments, as Arn makes use of arbitrarily-precise floating point numbers. Compression doesn't save any bytes here.

Explained

-R transforms input from N to the range [0, N). -m maps the program over the input

1/      Reciprocal of
   f   The factorial function in the global scope (takes `_`)

-x then sums the result

Arn (less boring), 10 bytes uncompressed

+{1/f}\0->

Same concept but without the flags. This is probably 7-8 bytes compressed, but I'm not at my computer right now and so can't check.

\$\endgroup\$
2
  • \$\begingroup\$ Surely this is compressible somehow. 5 bytes feels way too long. \$\endgroup\$
    – lyxal
    Commented Apr 23, 2021 at 0:23
  • \$\begingroup\$ 1.1 makes it 4 bytes, so it’s possible that can be compressed to 3. It’s really hit and miss when it comes to the text compression. \$\endgroup\$ Commented Apr 23, 2021 at 11:32
1
\$\begingroup\$

05AB1E, 5 bytes

L<!zO

Try it online!

L<!zO  # full program
    O  # sum of...
   z   # 1 divided by...
  !    # factorial of...
       # (implicit) each element in...
L      # [1, 2, 3, ...,
       # ..., implicit input...
L      # ]...
       # (implicit) with each element...
 <     # decremented
       # implicit output
\$\endgroup\$
1
\$\begingroup\$

Ruby, 33 bytes

Returns a rational number. If the we can use 0-indexing, ... can be shortened to ...

->n{[k=1,*1...n].sum{|j|1r/k*=j}}

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ I believe you can change 1r/k*=j into k/=j, and set k=1r at the start. \$\endgroup\$ Commented Sep 15, 2021 at 2:04
1
\$\begingroup\$

asm2bf, 133 bytes

Requires a 16-bit interpreter, at least 64 tape cells, integer i/o. This all is faciliated using bfi -d bundled with asm2bf. Fairly slow, overflows at n=6. Takes n in r4. Outputs the result due to a meta consensus.

?A=popr1/outr1
@z incr3
psh1
dup
@a movr2,r3
movr1,1
@b cltr2,2
cjn%c
mulr1,r2
decr2
jmp%b
@c pshr1
psh1
fad
incr3
cltr3,r4
cjn%a
A
A

Example usage:

mov r4, 5
jmp %z

Deobfuscated:

inc r3
push 1
push 1
@mloop
    mov r2, r3
    mov r1, 1
@loop
    clt r2, 2
    cjnz %done
    mul r1, r2
    dec r2
    jmp %loop
@done
    push r1
    push 1
    fadd
    inc r3
    clt r3, r4
    cjnz %mloop
pop r1
out r1
pop r1
out r1

Bonus: optimized brainfuck code:

>>>>>>+++++<+>>>>>>>>>>>>+[<<<<+>>>>>>>[>>]>+<<<[<<]<-]<<<<[>>>>+<<<<-]>>>>>>>[>
>]+[<<]<[<<<<+>>>>>>>[>>]>+<<<[<<]<-]<<<<[>>>>+<<<<-]>>>>>>>[>>]+[<<]<<<<[-]+[<<
<<<<<<<<[-]>[<+<<+>>>-]<<<[>>>+<<<-]>[-]+>>>>>>>>>>>[-]+[<<<<<<<<<<<[<<+>>-]<<[>
>>[<+<+>>-]<<[>>+<<-]<-]>>>->>>++>>>>>>>[-]+<<<<<<<<<<[>>>>>>>+<<<<<<<-]>>>[>>>+
<<<-]>>>[<<<<<<+>>>+>>>>[-<]>]<<[>>>>-<<<<<<<<<<->>>>>>-[<<<+>>>-]<<]>>>[<<<<<<<
+>>>>>>>-]<<<<[-]>>>>>>>]<<<<<<<<<<<[>>>>>>>>>>+>>>>>>>[>>]>+<<<[<<]<<<<<<<<<<<<
<<<-]>>>>>>>>>>[<<<<<<<<<<+>>>>>>>>>>-]>>>>>>>[>>]+[<<]<[<<<<+>>>>>>>[>>]>+<<<[<
<]<-]<<<<[>>>>+<<<<-]>>>>>>>[>>]+[<<]>>[>>]<<-<[<<<<->+>>>-]<-<<-<[>[<+>>>>+<<<-
]>[<+>-]<[>>>[<<+>+>-]<[>+<-]<<-]<[>+<-]>>>>>>[<<<<<[<+>>+<-]<[>+<-]>>>>>>-]<<[<
<<[<+>>>+<<-]>>[<<+>>-]>-]]<[>>[<+>-]>>>>>[<<<<+>>>>-]<<<]<<[-]+[<<]<<<<<<<<<<<[
-]<<+>>>>>>>>>[-]<<<<<<<<<[>>>>>>+<<<<<<-]>[>>>>+<<<<-]>>>>[<<<<<+>+>>>>>[-<]>]<
<[>>>>+<<<<<<<<<->>>>>-[<<<<+>>>>-]<<]>>>[<<<<<<+>>>>>>-]>>>]>>>[-]>>>[>>]<<->[<
<<[<<]<+>>>[>>]>-]<<<[<<]<.[-]>>>[>>]<<->[<<<[<<]<+>>>[>>]>-]<<<[<<]<.

To change the output, tweak the first block of +.

\$\endgroup\$
1
\$\begingroup\$

Java (JDK)

note that you can get better results faster by increasing the precision of MathContext. This would take up one more byte per power of 10 though. This is why I decided to leave it at 9 If you need to include the import java.math.*; that would add another 19 bytes.

Using BigDecimals: 241 bytes

static BigDecimal c(int n){var o=BigDecimal.ONE;var c=o;for(int i=0;i++<n;)o=o.add(c.divide(f(o.valueOf(i)),new MathContext(9)));return o;}static BigDecimal f(BigDecimal n){var o=n.ONE;return n.compareTo(o)<1?o:f(n.subtract(o)).multiply(n);}

Try it online!

Using primitive Number types: 119 bytes

static double c(int n){double v=0;for(int i=0;i<n;)v+=1/f(i++);return v;}static double f(int n){return n<2?1:f(n-1)*n;}

Try it online!

Explanation:

    static double c(int n){
        double v=0;               // value for e
        for(int i=0;i<n;)         // for n-iterations
            v+=1/f(i++);          // add the inverse
                                  // of the factorial
        return v;                 // return value
    }

    static double f(int n){
        return n<2?1:f(n-1)*n;    // recursively calculates the factorial
    }
\$\endgroup\$
1
\$\begingroup\$

Nekomata, 4 bytes

rFŗ∑

Attempt This Online!

rFŗ∑
r       Range
 F      Factorial
  ŗ     Reciprocal
   ∑    Sum
\$\endgroup\$
1
\$\begingroup\$

Go, 85 84 bytes

import."math"
func f(n float64)(S float64){for i:=1.;i<=n;i++{S+=1/Gamma(i)}
return}

Attempt This Online!

\$\endgroup\$
1
1
\$\begingroup\$

x86-64 machine code, 23 bytes

Expects \$n\$ in rcx and leaves the result of the approximation in st0. The FPU stack is assumed to be empty upon subroutine entry, and only has one value—the result—in it on exit.

Clobbers rcx, the FPU stack and flags, and FLAGS.

d9 e8 d9 e8 d9 e8 eb 0a d9 c1 de c3 d9 e8 de c1 dc f9 e2 f4 da e9 c3

Try it online!

Explanation

The algorithm is essentially the same as @Leaky Nun's answer, just ported to x64 assembly.

func:
    fld1 ; load sum to st2 (constant 1.0)
    fld1 ; load term to st1 (constant 1.0)
    fld1 ; load termdiv to st0 (constant 1.0)

    ; first term counts in rcx dec/check too
    jmp func_do_chk

func_loop:
    ; sum += term
    fld st1
    faddp st3, st0
    
    ; termdiv += 1.0
    fld1
    faddp

    ; term /= termdiv
    fdiv st1, st0

    ; loop back up
func_do_chk:
    loop func_loop

    ; dump st0 and st1 to get sum into st0
    fucompp
    ret
\$\endgroup\$
0
\$\begingroup\$

WolframAlpha, 12 bytes

sum1/k!,0..n
\$\endgroup\$
0
\$\begingroup\$

Swift, 71 bytes

print(Set(0...n).reduce(0){$0+1/Float(Set(1...max(1,$1)).reduce(1,*))})

Try it online!

\$\endgroup\$
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.