title: Mix pi and e to make pie!

text:
# Question
Title: Mix pi and e to make pie!
Everybody knows *pi* the mathematical constant, the ratio of a circle's circumference to its diameter.

```
3.14159265358979323846264338327950288419716939937510...

```

You probably also know *e* the mathematical constant, the base of a natural logarithm.

```
2.71828182845904523536028747135266249775724709369996...

```

But... do you know *pie*? It is one of the most important constants (to me). It is the digits of *pi* and *e* interleaved.

```
32.1741185298216852385485997094352233854366206248373...

```

As a decimal expansion:

```
3, 2, 1, 7, 4, 1, 1, 8, 5, 2, 9, 8, 2, 1, 6, 8, 5, 2...

```

This is OEIS sequence A001355.

> KEYWORD: nonn,base,**dumb**,easy

It is a very dumb sequence.

## Challenge

Write a **program/function** that takes a **non-negative integer n** and outputs the **nth digit of pie**.

### Specifications

* Standard I/O rules **apply**.
* Standard loopholes are **forbidden**.
* Your solution must work for at least 50 digits of each constant which means it should work for at least a **100 terms of the sequence** (please, *try* not to hardcode :P).
* The output for 2 or 3 is **not a decimal point**.
* Your solution **can either be 0-indexed or 1-indexed** but please specify which.
* This challenge is not about finding the shortest approach in all languages, rather, it is about finding the **shortest approach in each language**.
* Your code will be **scored in bytes**, usually in the encoding UTF-8, unless specified otherwise.
* Built-in functions that compute this sequence are **allowed** but including a solution that doesn't rely on a built-in is encouraged.
* Explanations, even for "practical" languages, are **encouraged**.

### Test cases

These are 0-indexed.

```
Input   Output

1       2
2       1
11      8
14      6
21      4
24      9
31      5

```

In a few better formats:

```
1 2 11 14 21 24 31
1, 2, 11, 14, 21, 24, 31

2 3 12 15 22 25 32
2, 3, 12, 15, 22, 25, 32

```

# Answer
# Mathematica, 50 bytes

1-indexed

```
(Riffle@@(#&@@RealDigits[#,10,5!]&/@{Pi,E}))[[#]]&

```
> 12 votes

# Answer
# Haskell, ~~154~~ ~~147~~ 146 bytes, NO HARDCODING OR USE OF BUILTIN CONSTANTS

This solution calculates *e* and *pi* using infinite series and stores them in arbitrary-precision fixed-point integers (Haskell's built-in `Integer` type and its `Rational` extension).

```
import Data.Ratio
s n=product[n,n-2..1]
r=[0..164]
f n=(show$round$(*10^50)$sum[[2*s(2*k)%(2^k*s(2*k+1)),1%product[1..k]]!!mod n 2|k<-r])!!div n 2

```

Ungolfed:

```
import Data.Ratio

semifact :: Integer -> Integer
semifact n = product [n, n-2..1]

pi_term :: Integer -> Rational
pi_term i = semifact (2*i) % (2^i * semifact (2*i+1))

--requires 164 terms to achieve desired precision
pi_sum :: Rational
pi_sum = 2 * (sum $ map (pi_term) [0..164])

--requires 40 terms to achieve desired precision
e_sum :: Rational
e_sum = sum [1 % product [1..k] | k<-[0..40]]

-- 51 digits are required because the last one suffers from rounding errors
fifty1Digits :: Rational -> String
fifty1Digits x = show $ round $ x * 10^50

pi51 = fifty1Digits pi_sum
e51  = fifty1Digits e_sum

-- select a string to draw from, and select a character from it
pie_digit n = ([pi51, e51] !! (n `mod` 2)) !! (n `div` 2)

```

0-indexed. Accurate for input 0-99, inaccurate for input 100-101, out-of-bounds otherwise.

Explanation:

Calculates *pi* using this infinite series. Calculates *e* using the classical inverse factorial series. Theoretically these aren't the ideal formulas to use, as they aren't very terse in terms of bytecount, but they were the only ones I could find that converged quickly enough to make verification of accuracy feasible (other sums required hundreds of thousands if not millions of terms). In the golfed version, *e* is calculated to a much higher precision than necessary in order to minimize bytecount. Both constants are calculated to slightly more digits than necessary to avoid rounding errors (which are responsible for the awkward tail of incorrect values).

The constants are calculated as arbitrary precision integer ratios (`Rational`), then multiplied by 10^50 so that all necessary digits remain intact when the ratio is converted to an (arbitrary precision) integer (`Integer`). This also avoids the issue of avoiding the decimal point in the numbers' string representations, which the function alternatively draws characters from.
> 9 votes

# Answer
# Taxi, 749 bytes

```
'3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919' is waiting at Writer's Depot.Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to The Underground.Go to Writer's Depot:n 1 l 1 l 2 l.Pickup a passenger going to Chop Suey.Go to Chop Suey:n 3 r 3 r.[a]Pickup a passenger going to Narrow Path Park.Go to The Underground:s 1 r 1 l.Switch to plan "b" if no one is waiting.Pickup a passenger going to The Underground.Go to Narrow Path Park:n 4 l.Go to Chop Suey:e 1 r 1 l 1 r.Switch to plan "a".[b]Go to Narrow Path Park:n 4 l.Pickup a passenger going to Post Office.Go to Post Office:e 1 r 4 r 1 l.

```

Try it online!

Trying to compute pi or e programmatically in Taxi would be a nightmare, although I'm sure it can be done. Thus, it's *far* shorter to just hardcode the first 100 digits in the sequence. It feels pretty cheap but it's definitely the shortest Taxi code that meets the challenge.

It hard-codes the sequence as strings, takes in `n`, then iterates `n` down and removes the first character in the string each time. When `n=0`, output the first character. This is one-indexed.

Un-golfed / formatted:

```
'3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919' is waiting at Writer's Depot.
Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 1st right.
Pickup a passenger going to The Underground.
Go to Writer's Depot: north 1st left 1st left 2nd left.
Pickup a passenger going to Chop Suey.
Go to Chop Suey: north 3rd right 3rd right.
[a]
Pickup a passenger going to Narrow Path Park.
Go to The Underground: south 1st right 1st left.
Switch to plan "b" if no one is waiting.
Pickup a passenger going to The Underground.
Go to Fueler Up: south.
Go to Narrow Path Park: north 4th left.
Go to Chop Suey: east 1st right 1st left 1st right.
Switch to plan "a".
[b]
Go to Narrow Path Park: north 4th left.
Pickup a passenger going to Post Office.
Go to Post Office: east 1st right 4th right 1st left.

```
> 8 votes

# Answer
# 05AB1E, 10 bytes

```
žsтžtøJþsè

```

Explanation:

```
žs          Get the first input digits of pi
  тžt       Get 100 digits of e
     ø      Zip them together
      J     Join into a string
       þ    Remove non-digits
        sè  0-indexed index of input in the resulting list

```

0-indexed.

Try it online!
> 6 votes

# Answer
# Python 2, 88 bytes

*-4 bytes thanks to the base conversion idea of @EriktheOutgolfer.*

```
lambda n:`int("SVBPXJDZK00YCG3W7CZRA378H4AM5553D52T52ZKAFJ17F4V1Q7PU7O4WV9ZXEKV",36)`[n]

```

Try it online!

# Python 2 \+ sympy, 92 bytes

0-indexed. Thanks to Rod for reminding me to switch to `from sympy import*`, which I formerly forgot.

```
lambda n:sum([('3','2')]+zip(`N(pi,50)`,`N(E,50)`[:47]+'6996')[2:],())[n]
from sympy import*

```

Try it online!

# Python 2, 114 bytes

~~I honestly think the shortest solution is hardcoding, since Python doesn't have useful built-ins.~~

```
lambda n:"3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919"[n]

```

Try it online!

# Python 2, 114 bytes

Equivalent solution by @totallyhuman.

```
'3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919'.__getitem__

```

Try it online!
> 6 votes

# Answer
# Python 3, ~~83~~ 80 bytes

0-indexed.

```
lambda n:('%d'*51%(*b' )4bD4&6UcF^#!U+B>0%"WK\<>0^GO9~1c]$O;',))[n]

```

Try it online!

There are some non-printable characters in there that can't be seen properly in a browser.

This works by building the tuple `(32, 17, 41, 18, 52, ...)` from the ASCII codes of the characters in the hardcoded bytestring. The tuple is converted to the string `'3217411852...'`, from which we select the right digit.
> 5 votes

# Answer
# Polyglot, 108 bytes

```
n=>"3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919"[n]

```

Works in:

* C#
* JavaScript

---

I think this is the shortest you can do in C# seeing as it is 252 bytes to find the Nth decimal of pi.
> 4 votes

# Answer
# Seed, 6015 bytes

```
105 [encoded data, 6011 characters]

```

The Seed equivalent to my Befunge answer. Like I mentioned there, the Befunge program this outputs does not work on TIO because TIO seems to have internal line wrapping at 80 characters.
> 4 votes

# Answer
# Java 8, ~~420~~ ~~417~~ ~~413~~ ~~404~~ ~~380~~ 358 (calculated) & ~~115~~ 110 (hardcoded) bytes

Calculated (**~~420~~ ~~417~~ ~~413~~ ~~404~~ ~~380~~ 358**):

```
import java.math.*;n->{int i=1,x=99;BigDecimal e,f=e=BigDecimal.ONE;BigInteger p,a=BigInteger.TEN.pow(x);for(p=a=a.add(a);i<x;)e=e.add(e.ONE.divide(f=f.multiply(f.valueOf(i++)),new MathContext(x,RoundingMode.HALF_UP)));for(i=1;a.compareTo(a.ZERO)>0;)p=p.add(a=a.multiply(a.valueOf(i)).divide(a.valueOf(i+++i)));return n==1?50:((n%2<1?p:e)+"").charAt(-~n/2);}

```

Try it here.
Prove it outputs correct result for required 100 items.

Hardcoded: (**~~115~~ 110 bytes**):

```
"3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919"::charAt

```

Try it online.

0-indexed

-9 and -5 bytes thanks to *@Nevay*.
-24 bytes thanks to *@ceilingcat*.

> * Your solution must work for at least 50 digits of each constant which means it should work for at least a **100 terms of the sequence** (please, *try* not to hardcode :P)
> * Built-in functions that compute this sequence are **allowed** but including a solution that doesn't rely on a built-in is encouraged

You've asked for it.. ;)

Java's built-in `Math.PI` and `Math.E` are doubles, which have a max precision of just 16. Therefore, we'll have to calculate both values ourselves using `java.math.BigInteger` and/or `java.math.BigDecimal`.
Since I've already calculate PI before in another challenge, I've used that same code using `BigInteger`. The algorithm for Euler's number uses `BigDecimal` however.
The resulting `p` and `e` are therefore: `31415...` and `2.718...`.

Could probably golf it by only using `BigDecimal`, but was giving some incorrect answers for PI, so I now use both `BigDecimal` and `BigInteger`.

**Explanation:**

```
import java.math.*;           // Required import for BigDecimal and BigInteger
n->{                          // Method with integer as parameter and char as return-type
  int i=1,                    //  Start index-integer at 1
      x=99;                   //  Large integer we use three times
  BigDecimal e,               //  Euler's number
             f=e=BigDecimal.ONE;
                              //  Temp BigDecimal (both `e` and `f` start at 1)
  BigInteger p,               //  PI
             a=BigInteger.TEN.pow(x);for(p=a=a.add(a);
                              //  Temp BigInteger (where both `p` and `a` starts at 10^99*2)

       i<x;)                  //  Loop (1) 99 times (the higher the better precision)
    e=e.add(                  //   Add the following to `e`:
       e.ONE.divide(f=f.multiply(f.valueOf(i++)),
                              //    First change `f` by multiplying it with `i`
        new MathContext(x,RoundingMode.HALF_UP))))
                              //    And then add 1/`f` to `e`
                              //    (RoundingMode is mandatory for BigDecimal divide)
  for(i=1;                    //  Reset `i` back to 1
      a.compareTo(a.ZERO)>0;) //  Loop (2) as long as `a` is not 0
    p=p.add(                  //   Add the following to `p`:
       a=a.multiply(a.valueOf(i))
                              //    First change `a` by multiplying it with `i`,
          .divide(a.valueOf(i+++i)));
                              //    and dividing it by `2*i+1`
                              //    And then add this new `a` to `p`
  // We now have `p`=31415... and `e`=2.718...
  return n==1?                // If the input (`n`) is 1:
          50                  //  Return 2
         :                    // Else:
          ((n%2<1?            //  If `n` is divisible by 2:
             p                //   Use `p`
            :                 //  Else:
             e)               //   Use `e` instead
    +"")                      //  Convert BigDecimal/BigInteger to String:
        .charAt(-~n/2);}      //  And return the `(n+1)//2`'th character in this string

```
> 4 votes

# Answer
# Excel, 113 bytes

1-indexed

```
=MID("3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919",A1,1)

```

`PI()` is only accurate up to 15 digits. Similar for `EXP(1)`.

~~60~~ 42 byte solution that works for Input `<=30` (-18 bytes thanks to @Adam)

```
=MID(IF(ISODD(A1),PI(),EXP(1)/10)/10,A1/2+3,1)

```
> 3 votes

# Answer
# 05AB1E, 14 bytes

```
žssžt‚øJ'.Ks<è

```

Try it online!

---

This answer is 0-indexed.

```
žs              # pi to N digits.
  sžt           # e to N digits.
     ‚øJ        # Interleave.
        '.K     # No decimal points.
           s<è  # 0-indexed digit from string.

```
> 2 votes

# Answer
# Python 2 \+ SymPy, ~~70~~ 63 bytes

```
lambda n:int(N([pi,E][n%2],50)*10**(n/2)%10)
from sympy import*

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 13 bytes

```
Éi<;žtë;žs}þθ

```

Try it online!

Similar to Magic's answer, but kinda different.

Explanation:

```
Éi<;žtë;žs}þθ Supports 9842 digits of e and 98411 digits of π
É             a % 2
 i    ë   }   if a==1
  <            a - 1
   ;           a / 2
    žt         e to a digits
              else
       ;       a / 2
        žs     π to a digits
           þ  keep chars in [0-9] in a
            θ a[-1]

```
> 2 votes

# Answer
# Japt, 55 bytes

```
" ®v4bØUî6UcF^#ß&6$Îø%\"Wí;<>0^GO9G1c]$O;"cs gU

```

Test it online! Contains a few unprintables.

Works by replacing each character in the string with its charcode, then returning the digit at the correct index. The string was generated by this program:

```
r"..(?=[^0]0)|25[0-5]|2[0-4].|1..|.(?=[^0]0)|..|."_n d

```

Test it online!
> 2 votes

# Answer
# Julia, 63 bytes

1-indexed

```
a(n)=replace(string(BigFloat(n%2>0?π:e)),'.',"")[ceil(Int,n/2)]

```

Converts pi or e to a string, removes the decimal place, and then calls the appropriate digit. Returns a character representation of the digit.
> 2 votes

# Answer
# Seed, ~~5852~~ 5794

Based on TehPers Befunge answer.

```
105 [encoded data, 5790 characters]

```
> 2 votes

# Answer
# Malbolge Unshackled (20-trit rotation variant), 3,64E6 bytes

Size of this answer exceeds maximum postable program size (eh), so the code is located in my GitHub repository (note: Don't copy the code using CTRL+A and CTRL+C, just rightclick and click "Save destination element as...").

## How to run this?

This might be a tricky part, because naive Haskell interpreter will take ages upon ages to run this. TIO has decent Malbogle Unshackled interpreter, but sadly I won't be able to use it (limitations).

The best one I could find is the fixed 20-trit rotation width variant, that performs very well, **calculating (pretty much) instantly**.

To make the interpreter a bit faster, I've removed all the checks from Matthias Lutter's Malbolge Unshackled interpreter.

```
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char* translation = "5z]&gqtyfr$(we4{WP)H-Zn,[%\\3dL+Q;>U!pJS72Fh"
        "OA1CB6v^=I_0/8|jsb9m<.TVac`uY*MK'X~xDl}REokN:#?G\"i@";

typedef struct Word {
    unsigned int area;
    unsigned int high;
    unsigned int low;
} Word;

void word2string(Word w, char* s, int min_length) {
    if (!s) return;
    if (min_length < 1) min_length = 1;
    if (min_length > 20) min_length = 20;
    s[0] = (w.area%3) + '0';
    s[1] = 't';
    char tmp[20];
    int i;
    for (i=0;i<10;i++) {
        tmp[19-i] = (w.low % 3) + '0';
        w.low /= 3;
    }
    for (i=0;i<10;i++) {
        tmp[9-i] = (w.high % 3) + '0';
        w.high /= 3;
    }
    i = 0;
    while (tmp[i] == s[0] && i < 20 - min_length) i++;
    int j = 2;
    while (i < 20) {
        s[j] = tmp[i];
        i++;
        j++;
    }
    s[j] = 0;
}

unsigned int crazy_low(unsigned int a, unsigned int d){
    unsigned int crz[] = {1,0,0,1,0,2,2,2,1};
    int position = 0;
    unsigned int output = 0;
    while (position < 10){
        unsigned int i = a%3;
        unsigned int j = d%3;
        unsigned int out = crz[i+3*j];
        unsigned int multiple = 1;
        int k;
        for (k=0;k<position;k++)
            multiple *= 3;
        output += multiple*out;
        a /= 3;
        d /= 3;
        position++;
    }
    return output;
}

Word zero() {
    Word result = {0, 0, 0};
    return result;
}

Word increment(Word d) {
    d.low++;
    if (d.low >= 59049) {
        d.low = 0;
        d.high++;
        if (d.high >= 59049) {
            fprintf(stderr,"error: overflow\n");
            exit(1);
        }
    }
    return d;
}

Word decrement(Word d) {
    if (d.low == 0) {
        d.low = 59048;
        d.high--;
    }else{
        d.low--;
    }
    return d;
}

Word crazy(Word a, Word d){
    Word output;
    unsigned int crz[] = {1,0,0,1,0,2,2,2,1};
    output.area = crz[a.area+3*d.area];
    output.high = crazy_low(a.high, d.high);
    output.low = crazy_low(a.low, d.low);
    return output;
}

Word rotate_r(Word d){
    unsigned int carry_h = d.high%3;
    unsigned int carry_l = d.low%3;
    d.high = 19683 * carry_l + d.high / 3;
    d.low = 19683 * carry_h + d.low / 3;
    return d;
}

// last_initialized: if set, use to fill newly generated memory with preinitial values...
Word* ptr_to(Word** mem[], Word d, unsigned int last_initialized) {
    if ((mem[d.area])[d.high]) {
        return &(((mem[d.area])[d.high])[d.low]);
    }
    (mem[d.area])[d.high] = (Word*)malloc(59049 * sizeof(Word));
    if (!(mem[d.area])[d.high]) {
        fprintf(stderr,"error: out of memory.\n");
        exit(1);
    }
    if (last_initialized) {
        Word repitition[6];
        repitition[(last_initialized-1) % 6] =
                ((mem[0])[(last_initialized-1) / 59049])
                    [(last_initialized-1) % 59049];
        repitition[(last_initialized) % 6] =
                ((mem[0])[last_initialized / 59049])
                    [last_initialized % 59049];
        unsigned int i;
        for (i=0;i<6;i++) {
            repitition[(last_initialized+1+i) % 6] =
                    crazy(repitition[(last_initialized+i) % 6],
                        repitition[(last_initialized-1+i) % 6]);
        }
        unsigned int offset = (59049*d.high) % 6;
        i = 0;
        while (1){
            ((mem[d.area])[d.high])[i] = repitition[(i+offset)%6];
            if (i == 59048) {
                break;
            }
            i++;
        }
    }
    return &(((mem[d.area])[d.high])[d.low]);
}

unsigned int get_instruction(Word** mem[], Word c,
        unsigned int last_initialized,
        int ignore_invalid) {
    Word* instr = ptr_to(mem, c, last_initialized);
    unsigned int instruction = instr->low;
    instruction = (instruction+c.low + 59049 * c.high
            + (c.area==1?52:(c.area==2?10:0)))%94;
    return instruction;
}

int main(int argc, char* argv[]) {
    Word** memory[3];
    int i,j;
    for (i=0; i<3; i++) {
        memory[i] = (Word**)malloc(59049 * sizeof(Word*));
        if (!memory) {
            fprintf(stderr,"not enough memory.\n");
            return 1;
        }
        for (j=0; j<59049; j++) {
            (memory[i])[j] = 0;
        }
    }
    Word a, c, d;
    unsigned int result;
    FILE* file;
    if (argc < 2) {
        // read program code from STDIN
        file = stdin;
    }else{
        file = fopen(argv[1],"rb");
    }
    if (file == NULL) {
        fprintf(stderr, "File not found: %s\n",argv[1]);
        return 1;
    }
    a = zero();
    c = zero();
    d = zero();
    result = 0;
    while (!feof(file)){
        unsigned int instr;
        Word* cell = ptr_to(memory, d, 0);
        (*cell) = zero();
        result = fread(&cell->low,1,1,file);
        if (result > 1)
            return 1;
        if (result == 0 || cell->low == 0x1a || cell->low == 0x04)
            break;
        instr = (cell->low + d.low + 59049*d.high)%94;
        if (cell->low == ' ' || cell->low == '\t' || cell->low == '\r'
                || cell->low == '\n');
        else if (cell->low >= 33 && cell->low < 127 &&
                (instr == 4 || instr == 5 || instr == 23 || instr == 39
                    || instr == 40 || instr == 62 || instr == 68
                    || instr == 81)) {
            d = increment(d);
        }
    }
    if (file != stdin) {
        fclose(file);
    }
    unsigned int last_initialized = 0;
    while (1){
        *ptr_to(memory, d, 0) = crazy(*ptr_to(memory, decrement(d), 0),
                *ptr_to(memory, decrement(decrement(d)), 0));
        last_initialized = d.low + 59049*d.high;
        if (d.low == 59048) {
            break;
        }
        d = increment(d);
    }
    d = zero();

    unsigned int step = 0;
    while (1) {
        unsigned int instruction = get_instruction(memory, c,
                last_initialized, 0);
        step++;
        switch (instruction){
            case 4:
                c = *ptr_to(memory,d,last_initialized);
                break;
            case 5:
                if (!a.area) {
                    printf("%c",(char)(a.low + 59049*a.high));
                }else if (a.area == 2 && a.low == 59047
                        && a.high == 59048) {
                    printf("\n");
                }
                break;
            case 23:
                a = zero();
                a.low = getchar();
                if (a.low == EOF) {
                    a.low = 59048;
                    a.high = 59048;
                    a.area = 2;
                }else if (a.low == '\n'){
                    a.low = 59047;
                    a.high = 59048;
                    a.area = 2;
                }
                break;
            case 39:
                a = (*ptr_to(memory,d,last_initialized)
                        = rotate_r(*ptr_to(memory,d,last_initialized)));
                break;
            case 40:
                d = *ptr_to(memory,d,last_initialized);
                break;
            case 62:
                a = (*ptr_to(memory,d,last_initialized)
                        = crazy(a, *ptr_to(memory,d,last_initialized)));
                break;
            case 81:
                return 0;
            case 68:
            default:
                break;
        }

        Word* mem_c = ptr_to(memory, c, last_initialized);
        mem_c->low = translation[mem_c->low - 33];

        c = increment(c);
        d = increment(d);
    }
    return 0;
}

```
> 2 votes

# Answer
# Nim, ~~124~~ 97 bytes

```
import sugar
t(x=>($(7*"""L?J$rg$"79n*i.71&<B@[>)!Y8l:.pUo4GZ9c0a%"""[x/%2].ord))[x%%2+1])

```

Attempt This Online!

*-27 thanks to @Steffan*
> 2 votes

# Answer
# Python 3 + SymPy, 109 Bytes

0-indexed Try it online!

```
from mpmath import*
mp.dps=51
print(''.join(['32']+[str(pi)[i]+str(e)[i]for i in range(2,51)])[int(input())])

```

Beat hardcoding by 5 bytes!! But could probably be better. But beating hardcoding makes me feel good :)
> 1 votes

# Answer
# Pyth, 35 bytes

```
@.i`u+/*GHhyHyK^T99rJ^2T0Z`sm/K.!dJ

```

Test suite

Since Pyth doesn't have built-in arbitrary precision pi and e constants, I calculate them directly.

Calculating pi:

```
u+/*GHhyHyK^T99rJ^2T0

```

This uses the following recurrence continued fraction to compute pi: `2 + 1/3*(2 + 2/5*(2 + 3/7*(2 + 4/9*(2 + ...))))`. I got it from another PPCG answer. It is derived in equations 23-25 here.

I calculate it from the inside out, ommitting all terms beyond the 1024th, since the later terms have little effect on the number, and I maintain 99 digits of precision to make sure the first 50 are correct.

Calculating e:

```
sm/K.!dJ

```

I sum the reciprocals of the first 1024 numbers, to 99 digits of precision.

Then, I convert both numbers to strings, interlace them, and index.
> 1 votes

# Answer
# Python 2, 82 bytes

```
lambda n:`7*ord('L?J$rg$"79n*i.71&<B@[>)!Y8l:.pUo4GZ9c0a%'[n/2])`[n%2+1]

```

Try it online!

Contains some unprintable ASCII characters. flornquake saved two bytes.
> 1 votes

# Answer
**MATLAB, 93 Bytes**

```
n=input('');
e=num2str(exp(1));
p=num2str(pi);
c=[];
for i=1:length(p)
 c=[c p(i) e(i)];
end;
c(n)

```

A simple explanation is that this first converts e and pi to strings, then goes through a for loop concatenating the digits. Here, c is pie, p is pi, and e is e.

I have also broken this up into several lines for readability, but the actual code is all on one line with minimal spacing.
> 1 votes

# Answer
# C# + BigDecimal, ~~377~~ 372 bytes

```
d=>{if(d%2<1){d/=2;int l=++d*10/3+2,j=0,i=0;long[]x=new long[l],r=new long[l];for(;j<l;)x[j++]=20;long c,n,e,p=0;for(;i<d;++i){for(j=0,c=0;j<l;c=x[j++]/e*n){n=l-j-1;e=n*2+1;r[j]=(x[j]+=c)%e;}p=x[--l]/10;r[l]=x[l++]%10;for(j=0;j<l;)x[j]=r[j++]*10;}return p%10;}else{CognitioConsulting.Numerics.BigDecimal r=1,n=1,i=1;for(;i<99;)r+=n/=i++;return(r+"").Remove(1,1)[d/2]-48;}}

```

*Saved 5 bytes thanks to @Kevin Cruijssen.*

No TIO link because of the external library, unfortunately C# doesn't have a built in `BigDecimal` class so this external one will have to do. Probably some golfing still possible but no time right now.

Full/Formatted Version:

```
namespace System.Linq
{
    class P
    {
        static void Main()
        {
            Func<int, long> f = d =>
            {
                if (d % 2 < 1)
                {
                    d /= 2;

                    int l = ++d * 10 / 3 + 2, j = 0, i = 0;
                    long[] x = new long[l], r = new long[l];

                    for (; j < l;)
                        x[j++] = 20;

                    long c, n, e, p = 0;

                    for (; i < d; ++i)
                    {
                        for (j = 0, c = 0; j < l; c = x[j++] / e * n)
                        {
                            n = l - j - 1;
                            e = n * 2 + 1;
                            r[j] = (x[j] += c) % e;
                        }

                        p = x[--l] / 10;
                        r[l] = x[l++] % 10;

                        for (j = 0; j < l;)
                            x[j] = r[j++] * 10;
                    }

                    return p % 10;
                }
                else
                {
                    CognitioConsulting.Numerics.BigDecimal r = 1, n = 1, i = 1;

                    for (; i < 99;)
                        r += n /= i++;

                    return (r + "").Remove(1,1)[d/2] - 48;
                }
            };

            for (int i = 0; i < 100; ++i)
            {
                Console.Write(f(i));
            }
            Console.WriteLine();

            Console.ReadLine();
        }
    }
}

```
> 1 votes

# Answer
# brainfuck, 402 bytes

```
--->+>->+>>+>+>>->->+>+>+>-->->+>+>>>->->+>+>>+>+>->+>>+>+>>+>->->>-->>>->+>>+>->->->->+>+>>->+>->+>>->>-->->>>->>>+>->->->->>->>+>-->+>+>+>>+>>>+>->->>+>>->->+>+>->>+>->->>+>->->++[[>+++<-]<+++]>>+>->+>>+>->+>+>+>+>+>+>+>+>->+>->+>>->->->>+>->->->->+>>->>>>+>+>+>>>+>>->+>>->+>->>->+>->+>>->>+>+>>+>+>+>->>>+>+>>>>+>->+>+>->+>+>>>->>>+>>>>+>->>>+>>>>->->->->->>+>,[<[-]>[<+>-]<-]++++[<+++++++++++>-]<.

```

Try it online!

Input as character code (e.g. "A" = 65)

Try it online with digit input!

code:

```
build a value list (3217411852... reversed and each digit incremented by four)
--->+>->+>>+>+>>->->+>+>+>-->->+>+>>>->->+>+>>+>+>->+>>+>+>>+>->->>-->>>->+>>
+>->->->->+>+>>->+>->+>>->>-->->>>->>>+>->->->->>->>+>-->+>+>+>>+>>>+>->->>+>
>->->+>+>->>+>->->>+>->->++[[>+++<-]<+++]>>+>->+>>+>->+>+>+>+>+>+>+>+>->+>->+
>>->->->>+>->->->->+>>->>>>+>+>+>>>+>>->+>>->+>->>->+>->+>>->>+>+>>+>+>+>->>>
+>+>>>>+>->+>+>->+>+>>>->>>+>>>>+>->>>+>>>>->->->->->>+

>,                      get input
[                       while input > 0
  <[-]                      set next previous cell = 0
  >[<+>-]                   copy input cell to that cell
  <-                        and decrement it
]
++++[<+++++++++++>-]    add 44 to it
<.                      print it

```
> 1 votes

# Answer
# Vyxal `H`, ~~8~~ 7 bytes

```
∆I₁∆ĖYi

```

Try it Online!

-1 thanks to tybocopperkettle

Interleaves the first 100 digits of pi and e, then prints the value at the index
> 1 votes

# Answer
# Ruby, 52 bytes

Uses `-rbigdecimal/math` flag to require BigMath.

```
->n{BigMath.send([:PI,:E][n%2],n*2).to_s(?E)[n/2+2]}

```

Attempt This Online!

## Explanation

Ungolfed:

```
->n{
  BigMath.send([:PI, :E][n%2], n*2)
    .to_s(?E)[n/2+2]
}

```

`[:PI, :E][n%2]` chooses which method to send to BigMath, `PI` or `E`. We call that method with `n*2` as the precision argument because of a quirk when n=1 (it returns an Integer instead of a BigDecimal, and the former doesn’t take a string argument to `to_s`).

`to_s(?E)` converts the number to a string in engineering notation, then we get the `n/2+2`th character (+2 to skip over the `0.`), which is the digit we want.
> 1 votes

# Answer
# Neim, 45 bytes

```
(₃β{Nhj\CΓℚφᚺK$mᚠ"2oξ:{rm(/ᛂ})

```

neim isn't made for decimal numbers

Try it online!
> 0 votes

# Answer
# Befunge, 105 bytes

```
3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919&0g,@

```

Does not work on TIO because it seems to wrap lines internally at 80 characters for some reason. You can get it to work on TIO by putting each digit on a new line, and having the `&0g,@` after the `3` on the first line.
> 0 votes

# Answer
# JavaScript (ES6) + mathjs, 78 bytes

```
(n,m=math.create({number:"BigNumber"}))=>`${n%2?m.e:m.pi}`.match(/\d/g)[n/2|0]

```

Zero indexed and works up to 128 numbers (max input of 127).

## Test Snippet

```
let f=
(n,m=math.create({number:"BigNumber"}))=>`${n%2?m.e:m.pi}`.match(/\d/g)[n/2|0]
```

```
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.16.0/math.min.js"></script>
<input type=number min=0 value=0 oninput="O.innerHTML=this.value.length>0?f(+this.value):''"><pre id=O>3
```
> 0 votes

# Answer
# MATLAB (w/ Symbolic Toolbox), ~~89~~ 82 bytes

By making use of the Symbolic Toolbox, this answer provides an output without hardcoding the values of pi and e.

As a fun bonus this code as an input can take either a single index, or an array of indices and will simultaneously provide the output value for all index values provided (e.g. providing 1:10 will output the first 10 values).

```
a=char(vpa({'exp(1)';'pi'},51));
a(a=='.')=[];
n=input('');
a(9+fix(n/2)+56*mod(n,2))

```

<sup>(new lines added for readability, not required for execution so not included in byte count)</sup>

Unfortunately the Octave version used by TIO doesn't support symbolic inputs to the `vpa` function, so can't provide at TIO link.

In MATLAB indexing into the return vector from a function is not possible in the same way as with Octave which means this is a full program rather than just an anonymous function. The program will ask for an input `n` during execution - this is a one indexed value for which element is required. At the end of the program the value is implicitly printed.

For the program we use the `vpa` function which provides to 51 decimal places the value of `pi` and `exp(1)` (e). This is done symbolically to allow theoretically infinite precision. To expand for more than 100 elements, simply increase the value `51` in the code to increase the range.

Wrapping `vpa` in `char` (i.e. `char(vpa(...))` ) is necessary to convert the output of the function to a string rather than a symbolic value. The resulting output is the string:

```
matrix([[2.71828182845904523536028747135266249775724709369996], [3.14159265358979323846264338327950288419716939937511]])

```

This includes both e and pi to 51 decimal places - enough to allow 100 digits of our output (we have to do a little extra dp than required to avoid printing out rounded values)

In order to index in to this mess, we need to at least get rid of the decimal points so that both strings of digits are contiguous. Originally I used a simple regex replacement of anything which is not a digit with nothing. However I can save 7 bytes by only getting rid of the decimal point using the code:

```
a(a=='.')=[];

```

resulting string is now:

```
matrix([[271828182845904523536028747135266249775724709369996], [314159265358979323846264338327950288419716939937511]])

```

This contains all the digits we need with both pi and e chunks in consecutive indexes.

We can then convert the supplied index such that odd numbers access the pi chunk and even numbers access the e chunk using the calculation:

```
9+fix(n/2)+56*mod(n,2)

```

Accessing that (those) index (indices) in the above string will provide the correct output.
> 0 votes

# Answer
# Google Sheets, 47 Bytes

> *Note: due to the length of constants stored in Excel and Google Sheets, this solution is only accurate to 20 digits, accordingly*

Anonymous Worksheet function that takes input from cell `A1` and outputs that digit of Pie to the calling cell

```
=Mid(.1*If(IsOdd(A1),Pi(),.1*Exp(1)),3+A1/2,1

```

## Hardcoded Version, 112 Bytes

This version fully meets the program specification, but is generally not fun.

Anonymous Worksheet function that returns the nth digit in the **1-indexed** list of pie

```
=Mid("3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919",A1,1
```
> 0 votes

# Answer
# Axiom, 148 bytes

```
g(x,n)==floor(numeric(x)*10^n)::INT rem 10
f(n:NNI):NNI==(m:=digits((n+4)::PI);x:=n quo 2;if n rem 2=1 then r:=g(%e,x)else r:=g(%pi,x);digits(m);r)

```

0 based array. Results

```
(10) -> [f(i) for i in 0..20]
   (10)  [3,2,1,7,4,1,1,8,5,2,9,8,2,1,6,8,5,2,3,8,5]
                                            Type: List NonNegativeInteger
(11) -> f(100001)
   (11)  6
                                                    Type: PositiveInteger

```
> 0 votes

# Answer
# BFASM, 142 bytes

```
stk 0
org 0
txt "3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919"
in_ r1
rcl r2,r1
out r2

```

Takes input as ascii character, gives output in form of digit.
> 0 votes

# Answer
# brainfuck, 5971 bytes

Direct translation of my other bfasm answer.

```
+>+[<[>>+>+<<<-]>>[<<+>>-]>[[-]>>>>>>>>>>>>>>>>>+++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++>>++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<,>[-]<[<+>>>>>>>>>>+>>>>>+<<<<<<<<<<<<<<-]<[>+<-]>>>>>>>>>>>>>>>[[>>]+[<<]>>-]+[>>]<[<[<<]>+<<<<<<<<<<<<+>>>>>>>>>>>>>[>>]<-]<[<<]>[>[>>]<+<[<<]>-]>[>>]<<[-<<]><<<<<<<<<<<<.<<<]<<<[>>+>+<<<-]>>[<<+>>-]>[[-]<<<[-]>[-]>>]<<]

```

Try it online!
> 0 votes

# Answer
# C (tcc), 145 bytes

Naive solution

```

int main(void) {
	putchar("3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919"[getchar()]);
}

```

Try it online!
> 0 votes

---
Tags: code-golf, number, sequence, pi
---


title: What year will it be in n seconds?

text:
# Question
Title: What year will it be in n seconds?
You are given an integer `n` as input, and, regardless of the current date, must return the calendar year (Gregorian calendar, other calendars not allowed) taking place `n` seconds from now.

## Rules

* You may **not** assume that the current year is 2021. In other words, imagine a user testing your solution in five years.
* Standard loopholes forbidden.
* Shortest answer in **bytes** wins.
* Built-in date functions are allowed.
* You must also support negative numbers.
* **On the topic of the year zero: Your answer must follow the ISO specifications, meaning there *is* a year zero.**
* You may assume that the input is always an integer **within bounds of your language number system**.
* If your language's date functions take leap seconds into account, then follow your language, otherwise do not take leap seconds into account.

## Examples (in this case, measured at the time of writing, which is February 15, 2021)

```
100000000000 -> 5190
1000 -> 2021
54398643 -> 2022
54398643234 -> 3744
-100000000000 -> -1148

```

# Answer
> 21 votes
# Ohm v2, 5 bytes

```
υ!+υy

```

Try it online!

**Explanation**:

```
υ!+υy
υ!     get the current timestamp in seconds
  +    sum with the implicit input
   υy  get the year from the resulting timestamp

```

# Answer
> 14 votes
# Bash, 16 bytes

```
date -d$1sec +%Y

```

Try it online!

### Credits

* Saved 12 bytes thanks to @manatwork

# Answer
> 13 votes
# PHP, 27 bytes

```
<?=date(Y,time()+$argv[1]);

```

Try it online!

# Answer
> 10 votes
# 05AB1E, 116 bytes

```
"`т‰0Kθ4ÖUD2Qi\28X+ë<7%É31α}"Vžežfžg)IŽª+·÷ÄF©IdiY.V‹i®¬>0ë®1¾ǝDÅsD12‹i>1ë\1Dǝ¤>2}}ǝëć©ić©i<D_-12š31šë®<šDY.Všë®<š]θ

```

Here we go again..

Try it online or try it only with custom specified starting date. (Pretty slow for large inputs, so won't be able to output the larger test cases with the current date.)

**Explanation:**

Since 05AB1E doesn't have any date builtins (except for the current day/time), I've calculated things manually before. I've used the code of going to the next day from this answer of mine, which in turns also uses the leap year calculation of this answer of mine.
Since this challenge also asks to go back in time, I've modified the program accordingly to support that as well.

Step 1: Create a function to calculate the amount of days in a month for a given year/month:

```
"`т‰0Kθ4ÖUD2Qi\28X+ë<7%É31α}"  # Push this string
                             V # Pop and store it in variable `Y`

 `                             # Pop the list and push all values separated to the stack
                               # (the year will be at the top; month below it)
  т‰                           # Take the divmod-100 of the year
    0K                         # Remove the 0s
      θ                        # Pop and push its last item
       4Ö                      # Check if it's divisible by 4
         U                     # Pop and store this in variable `X`
                               # (X=1 for leap years; X=0 for non-leap years)
          D                    # Duplicate the current month
           2Qi                 # If it's equal to 2 (thus February):
              \                #  Discard the duplicated month
               28X+            #  Push 28 + isLeapYear from variable `X`
             ë                 # Else:
              <                #  Decrease the month by 1
               7%              #  Modulo-7
                 É             #  Modulo-2
                  31α          #  Absolute difference with 31
             }                 # Close the if-else statement

```

Step 2: Now we determine the current date, and loop an amount of times depending on the input:

```
že                             # Push the current day
  žf                           # Push the current month
    žg                         # Push the current year
      )                        # Wrap all three into a list
       I                       # Push the input-integer
        Žª+                    # Push compressed integer 42300
           ·                   # Double it to 84600 (60*60*24)
            ÷                  # Integer-divide the input by 84600
             Ä                 # Take its absolute value
              F                # And loop that many times:

```

Step 3: If the input was positive, calculate the next date:

```
©                              #  Store the current date in variable `®` (without popping)
 Idi                           #  If the input is non-negative:
    Y.V                        #   Execute string `Y` as 05AB1E code to get the amount
                               #   of days for the current month/year
       ‹i                      #   If this is smaller than the current days:
         ®                     #    Push the current date again
          ¬                    #    Get its first item (the days)
           >                   #    Increase the day by 1
            0                  #    Push index 0
        ë                      #   Else:
         ®                     #    Push the current date again
          1                    #    Push day=1
           ¾                   #    Push index 0
            ǝ                  #    Insert days=1 at index 0 into the date
             D                 #    Duplicate it
              Ås               #    Pop and push its middle item (the month)
                D              #    Duplicate that month
                 12‹i          #    If it's smaller than 12:
                     >         #     Increase the month by 1
                      1        #     Push index 1
                    ë          #    Else:
                     \         #     Discard the duplicated month
                      1        #     Push month=1
                       D       #     Push index 1
                        ǝ      #     Insert month=1 at index 1 into the date
                         ¤     #     Push its last item (the year)
                          >    #     Increase the year by 1
                           2   #     Push index 2
                    }          #    Close the if-else statement
        }                      #   Close the if-else statement
         ǝ                     #   Insert the value at the given index into the date

```

Step 4: If the input was negative instead, calculate the previous date:

```
ë                              #  Else (the input is negative):
 ć                             #   Extract head; push [month,year] and day separated
  ©                            #   Store the day in variable `®` (without popping)
   i                           #   If day == 1:
    ć                          #    Extract head; push [year] and month separated
     ©                         #    Store the month in variable `®` (without popping)
      i                        #    If month == 1:
       <                       #     Decrease the [year] by 1
        D                      #     Duplicate it
         _                     #     Check if it's equal to 0 (1 if 0; 0 otherwise)
          -                    #     Subtract that (so we go from year 1 to -1)
           12š31š              #     Prepend 12 and 31: [31,12,year-1-(year-1==0)]
      ë                        #    Else:
       ®<š                     #     Prepend month-1 to the [year] list
          D                    #     Duplicate it
           Y.V                 #     Execute string `Y` as 05AB1E code to get the amount
                               #     of days for this month/year
              š                #     Prepend this to the [month-1,year] list
   ë                           #   Else:
    ®<š                        #    Prepend day-1 to the [month,year] list

```

Step 5: After the loop, extract the year to output:

```
]                              # Close both the if-else and loop
 θ                             # Pop the date, and only leave its last item (the year)
                               # (after which it is output implicitly as result)

```

See this 05AB1E tips of mine (section *How to compress large integers?*) to understand why `Žª+` is `42300`.

# Answer
> 7 votes
# Ruby, 21 bytes

```
->n{[*Time.now+n][5]}

```

Try it online!

Shorter by a byte than the more obvious `->n{(Time.now+n).year}`.

# Answer
> 7 votes
# Octave / MATLAB, 27 bytes

```
@(x)datestr(x/86400+now,10)

```

Try it online!

### How it works

```
@(x)                          % Define anonymous function with input x
            x/86400           % Divide input by 86400, to convert to days
                    now       % Current time in days since "January 0, 0000"
                   +          % Add
    datestr(           ,10)   % Convert to string with format 10, which is year

```

# Answer
> 6 votes
# JavaScript (ES6), 42 bytes

```
n=>new Date(+new Date+n*1e3).getFullYear()

```

Try it online!

# Answer
> 6 votes
# PowerShell, ~~32~~ ~~26~~ 23 bytes

```
date|% *dds* @args|% y*

```

Try it online!

-3 bytes thanks to mazzy and ZaelinGoodman

# Answer
> 6 votes
# Python 3, ~~74~~ ~~72~~ 65 bytes

```
lambda x:(date.today()+timedelta(0,x)).year
from datetime import*

```

Try it online!

-7 bytes thanks to @Eric

# Answer
> 6 votes
# jq, ~~20~~ 15 characters

```
now+.|gmtime[0]

```

Sample run:

```
bash-5.0$ jq 'now+.|gmtime[0]' <<< 100000000000
5190

```

Try it online!

# Answer
> 5 votes
# Japt, <sup>~~12~~</sup> 10 bytes

```
ÐKj +Ue3)i

```

Try it

-2 bytes from AZTECCO.

This transpiles to the following JS:

```
new Date(K.j() + U * 1e3).i()

```

where `K.j()` is the current time converted to milliseconds, `U` is the input, and `.i()` gets the year from the date constructor.

# Answer
> 5 votes
# R, 12 bytes

```
Sys.time()+n

```

This returns a full date, the year is at the beginning of the string. This is according to the rules, which didn't say to print *just* the year; and this is not in the list of "standard loopholes" by the time of this answer.

To print *just* a year, R would need 25 bytes:

```
format(Sys.time()+n,"%Y")

```

# Answer
> 3 votes
# IBM/Lotus Notes Formula Language, ~~34~~ 32 Bytes

```
@Year(@Adjust(@Now;0;0;0;0;0;i))

```

Takes input from a field named `i`. Unfortunately, Formula only supports 32 bit signed integers so it is restricted to a maximum input of +/- 2,147,483,647.

There is no TIO for Formula so here are a couple of screenshots:

# Answer
> 3 votes
# MATL, 11 bytes

```
12L/Z'+10XO

```

Try it out at MATL Online

**Explanation**

```
        % Implicitly grab input as an integer (seconds)
12L     % Push the literal 86400 to the stack (seconds in a day)
/       % Divide the input (in seconds) by the seconds in a day to convert to days
Z'      % Get the current time in days as a float
+       % Add the current time and the seconds in the future together
10XQ    % Determine the year of this date
        % Implicitly display the result

```

# Answer
> 2 votes
# Julia, 38 bytes

```
using Dates
f(x)=Year(now()+Second(x))

```

Try it online!

# Answer
> 2 votes
# Raku, 28 bytes

```
{DateTime.new($_+time).year}

```

Try it online!

# Answer
> 2 votes
# AWK, 30

```
$1=strftime("%Y",$1+systime())

```

Try it online!

* 5 bytes saved thanks to @manatwork.

# Answer
> 2 votes
# Python 3, 51 bytes

```
lambda x:gmtime(time()+x).tm_year
from time import*

```

Try it online!

# Answer
> 2 votes
# GNU coreutils (16 bytes)

```
date +%Y -d$1sec

```

Saved 4 bytes, thanks to @ovs.

# Answer
> 2 votes
# MySQL, 35 bytes

`select year(now()+interval [input] second)`

# Answer
> 2 votes
# Java (JDK), 57 bytes

```
n->java.time.LocalDateTime.now().plusSeconds(n).getYear()

```

Try it online!

Beats the `Date` API (71 bytes):

```
n->new java.util.Date(System.currentTimeMillis()+n*1000).getYear()+1900

```

Try it online!

Note that this one returns the year in absolute form (no negative year).

And I don't even speak about the Calendar API.

# Answer
> 1 votes
# APL (Dyalog Unicode), 20 bytes (SBCS)

Full program, prompting for `n` from stdin.

```
⊃⊃20 ¯1⎕DT⎕+20⎕DT'J'

```

`20⎕DT'J'` get current local\* (**J**uliett) **D**ate**T**ime as UNIX time (code 20; seconds from beginning of 1970)

`⎕+` prompt for `n` and use that to increment the UNIX time.

`20 ¯1` interpret as UNIX times (code 20) and convert to an array of time stamps (code -1)

extract the first (and only) time stamp

extract the first element (the year)

Try APL! (first and last case scaled down by a factor of 10 to avoid hitting date-time limits, 1 January 0001 though 28 February 4000; turned into function for ease of use)

* could also have `'Z'` (**Z**ulu) to use the current UTC time instead of local time.

# Answer
> 1 votes
# C# (.NET Core), 98 bytes

```
public class E{public static void m(double x){Console.WriteLine(DateTime.Now.AddSeconds(x).Year);}

```

Try it online!

Didn't count the `using System;` and calling function in `Main()`, if they needed to be added, please inform me!

# Answer
> 1 votes
# Visual Basic .NET (VBC), 89 bytes

```
public class E
Shared sub m(x)
Console.WriteLine(DateTime.Now.AddSeconds(x).Year)
end Sub

```

Try it online!

# Answer
> 1 votes
# VBScript, 52 bytes

```
MsgBox Year(DateAdd("s",Wscript.Arguments(0),Now())

```

# Answer
> 1 votes
# Mathematica, 43 bytes

```
IntegerPart@DatePlus[#/86400]["YearExact"]&

```

Try it online!

Thanks to @LegionMammal978 for hinting that `DatePlus[#/86400][[1,1]]&` fails for negative years

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 34 bytes

```
x=>DateTime.Now.AddSeconds(x).Year

```

Try it online!

# Answer
> 1 votes
# AppleScript function, 46

```
to y(s)
(current date+s/60*minutes)'s year
end

```

### Test driver:

```
repeat with sec in {100000000000, 1000, 54398643, 54398643234, -100000000000}
    log y(sec)
end repeat

```

Save the function and the test driver as text to `nseconds.applescript`, then run in the terminal:

```
osascript nseconds.applescript

```

Or run in the AppleScript Editor app.

# Answer
> 1 votes
# T-SQL, 42 bytes

```
select year(dateadd(s,a,getdate()))from t;

```

Uses the standard input method for T-SQL of taking input from a table. You can create a suitable table like this:

```
create table t (a int not null);
insert into t values (1000000000), (1000), (54398643), (-1000000000);

```

Note that T-SQL is limited to 32-bit integers for the number of seconds. To avoid that and allow the resulting year to vary between 0 and 9999 costs 6 bytes:

```
select year(dateadd(d,a/86400,getdate()))from t;

```

Don't forget to declare `a` as `bigint` if you do this. (Note that hours is represented by `hh` so it's no shorter, and minutes won't let you reach 9999.)

# Answer
> 1 votes
# Moonscript, 38 30 bytes

```
(x)->os.date("%Y",os.time()+x)

```

Try it online!

-8 bytes thanks to ASCII-only

# Answer
> 1 votes
# Perl 5 `-p`, 23 bytes

```
$_=gmtime$^T+$_;s/.* //

```

Try it online!

# Answer
> 1 votes
# Python 3, 53 bytes

```
from time import*
lambda n:ctime(time()+n).split()[4]

```

Try it online!

# Answer
> 1 votes
# J-uby, 17 bytes

```
:+&Time.now|:year

```

Attempt This Online!

# Answer
> 0 votes
# Red, ~~48~~ 32 bytes

```
func[s][d: now d/9: d/9 + s d/2]

```

Try it online!

# Answer
> 0 votes
# \+ lubridate, 57 bytes

```
library(lubridate)
(function(x)isoyear(now()+seconds(x)))

```

Try it online! (But the library is not installed on Tio ...)

# Answer
> 0 votes
# Lua, 34 bytes

```
print(os.date('%Y',os.time()+...))

```

Try it online!

# Answer
> 0 votes
# Excel, 21 bytes

```
=YEAR(NOW()+A1/86400)

```

Input is in cell `A1`. Excel dates count by days so we divide by the number of seconds in a day.
Valid dates are in the range 1900-01-00 (that's not a typo) to 9999-12-31.
The screenshot below was taken at 2021-02-16 14:45 UTC.

# Answer
> 0 votes
# Factor, 24 bytes

```
[ seconds hence year>> ]

```

Try it online!

* `seconds` Convert the input to a duration in seconds.
* `hence` The time from now indicated by the duration.
* `year>>` A timestamp is returned by `hence`; we just want the year.

---
Tags: code-golf, date
---


# Question
Title: Output ISO8601 date string from seconds and nanoseconds
One reason why ISO8601 is the best date string format, is that you can simply append as much precision as you like. Given 2 integers representing seconds and nanoseconds that have passed since `1970-01-01T00:00:00`, return an ISO8601 string as described below.

**Output:**

The standard output format without timezone looks like this:

`1970-01-01T00:00:00.000001`

The date is encoded as "year, month,day" with 4,2,2 digits respectively, separated by a "-". The time of day is encoded as "hour, minute, seconds" with 2,2,2 digits respectively. Then, optionally a dot with exactly 6 digits of precision can follow, encoding microseconds that have passed after the given date+(time in hours+minutes+seconds) since. This is only appended if it'd be not equal to 000000. See examples below

Yes, we are allowed to append 6 digits(microseconds) of precision and theoretically more are simply appendable, though not defined further in the standard.

**Input:**

You'll get 2 integers(seconds, nanoseconds). For the sake of simplicity, let's constrain them to be within `0 <= x < 10^9` both. Make sure to discard/round down any precision beyond microseconds.

**Examples:**

```
Input: 616166982 , 34699909     Output: 1989-07-11T13:29:42.034699
Input: 982773555 , 886139278    Output: 2001-02-21T16:39:15.886139
Input: 885454423 , 561869693    Output: 1998-01-22T07:33:43.561869
Input: 0         , 100000       Output: 1970-01-01T00:00:00.000100
Input: 0         , 1000         Output: 1970-01-01T00:00:00.000001
Input: 0         , 999          Output: 1970-01-01T00:00:00
Input: 999999999 , 999999999    Output: 2001-09-09T01:46:39.999999

```

**Task:**

Provide a function that takes in 2 integers as described in the Input section and returns a String as described in the Output section.

For details and limitations for input/output please refer to the default input/output rules.

This is codegolf: Shortest solution in bytes wins.

# Answer
> 5 votes
# Bash \+ sed, ~~37~~, ~~59~~, 50 bytes

~~```
printf '%(%FT%T)T.%06d' $1 $[$2/1000]

```~~
```
printf "%(%FT%T)T.%06d" $1 ${2::-3}|sed s/\\.0*$//

```

Try it online!

8 bytes saved thanks to @DigitalTrauma

# Answer
> 3 votes
# Perl 5 (`-p` `-MPOSIX+strftime` `-Minteger`), ~~55~~, ~~51~~, 60 bytes

Thanks to @Abigail for giving me the idea to change the input format. + 9 bytes to handle the microseconds=0 case.

~~```
$_=(strftime"%FT%T",gmtime$_).sprintf".%06d",<>/1e3

```~~
```
$_=(strftime"%FT%T",gmtime$_).sprintf".%06d",<>/1e3;s;\.0+$;

```

Try it online!

# Answer
> 3 votes
# Wolfram Language (Mathematica), 91 bytes

```
DateString[6!3068040+#2,"ISODateTime"]<>If[#>999,"."<>IntegerString[⌊#/1000⌋,10,6],""]&

```

Try it online!

Mathematica supports milliseconds, but not microseconds.

# Answer
> 3 votes
# C (gcc), ~~108~~ 106 bytes

Saved 2 bytes thanks to ceilingcat!!!

```
#import<time.h>
o[9];f(s,n)long s;{strftime(o,99,"%FT%T",gmtime(&s));printf((n/=1e3)?"%s.%06d":"%s",o,n);}

```

Try it online!

Inputs seconds and nanoseconds as integers and outputs the formatted date/time to `stdout`.

# Answer
> 3 votes
# Japt, ~~32~~ 28 bytes

Takes input as a pair of strings, with the nanoseconds first. Can save (at least) 4 bytes if we can include leading `0`s with the nanoseconds.

```
ùT9 ¯6
pU=n g)iÐV*A³ s3 ¯UÄ9

```

Try it

Or, to "translate" that to JavaScript:

```
U=>V=>(
    U=U.padStart(9,0).slice(0,6),
    U.repeat(U=Math.sign(parseInt(U))).replace(/^/,new Date(V*10**3).toISOString().slice(0,U+19))
)

```

```
ùT9 ¯6\npU=n g)iÐV*A³ s3 ¯UÄ9     :Implicit input of strings U=nanoseconds & V=seconds
ù                                 :Left pad U
 T                                :  With 0
  9                               :  To length 9
    ¯6                            :Slice to length 6
      \n                          :Reassign to U
        p                         :Repeat U
         U=                       :  Reassign to U
           n                      :  Convert to integer
             g                    :  Get sign
              )                   :End repeat
               i                  :Prepend
                Ð                 :  Create Date object from
                 V*               :    V multiplied by
                   A              :    10
                    ³             :    Cubed
                      s3          :  To ISO String
                         ¯U       :  Slice to length U
                           Ä9     :    +19

```

# Answer
> 2 votes
# Groovy, ~~62 60~~ 68 bytes

```
f={s,n->"${java.time.Instant.ofEpochSecond(s,n|1)}"[0..25]-~/\.0+$/}

```

Try it online!

## Explanation

The Java `ofEpochSecond(epochSecond, nanoAdjustment)` method returns the `Instant` corresponding to the given seconds and nanoseconds (exactly what we want for this challenge). The nanoseconds are bitwise-ORed with `1` to ensure we never end up with exactly 0 or 1\_000\_000 nanoseconds, while still maintaining the same 6-digit rounding behavior.

`"${...}"` converts the `Instant` to a `GString` consisting of the `String` value of the instant. The `toString` representation of an `Instant` is in ISO-8601 format: "2011-12-03T10:15:30.000000001Z". It automatically excludes extra decimal places past 0/3/6 decimal places (seconds/milliseconds/microseconds) if the remaining digits are 0, hence the earlier bitwise-OR.

`"${value}"[0..25]` returns characters 0 through 25 of the string, which is up through the sixth decimal place.

`-~/\.0+$/` subtracts the first instance of the regex pattern `\.0+$` from the resulting string; namely, a decimal place followed by all zeros, followed by the end of the string. This will only match if the string ends in `.000000`, and the code is one character shorter than subtracting `'.000000'`.

# Answer
> 2 votes
# Groovy, 63 bytes

```
f={s,n->sprintf('%tFT%1$tT.%06d',s*1000L,n/1E3as int)-~/\.0+$/}

```

Try it online!

A different Groovy approach using format strings (inspired by other similar answers).

# Answer
> 1 votes
# Python 3.8 (pre-release) 106, 81 bytes

```
lambda a,b:datetime.fromtimestamp(a+b//1e3/1e6).isoformat()
from datetime import*

```

Try it online!

# Answer
> 1 votes
# JavaScript (V8), ~~83 94 ...~~ 78 bytes

```
s=>n=>new Date(s*1e3).toJSON(n=0|n/1e3).slice(0,20-!n)+`${n+1e6}`.slice(n?1:7)

```

Try it online!

* Thanks to @Neil for the great help!
* Saved another 5 thanks to @Arnauld

# Answer
> 1 votes
# APL (Dyalog Unicode) 18.0, 53 bytes (SBCS)

Full program. Prompts for nanoseconds, then seconds.

```
(¯7×0=f)↓⊃'%ISO%.ffffff'(1200⌶)20 1⎕DT⎕+1E¯6×f←⌊⎕÷1E3

```

Try it online! (polyfills for  and `⎕DT` because TIO still uses 17.1)

`⎕÷1E3` divide input nanoseconds by 1000

`f←` assign to `f`

`1E¯6×` multiply by 0.000001

`⎕+` add input seconds to that

`20 1⎕DT` convert from UNIX time (seconds since 1970) to Dyalog Date Number (days since 1989-12-31)

`'%ISO%.ffffff'(1200⌶)` format according to ISO with six-digit fractional second precision

disclose (because a "string" is an enclosed character vector)

`(``)↓` drop the following number of characters

`0=f` one if `f` is zero

`¯7×` seven from the rear if so (lit. negative seven multiplied by that)

# Answer
> 1 votes
# Excel, ~~102~~ 101 bytes

```
=TEXT(25569+A1/86400,"yyy-mm-ddThh:mm:ss")&SUBSTITUTE(LEFT(TEXT(B1/10^9,"."&REPT(0,9)),7),".000000",)

```

Input is seconds in `A1` and nanoseconds in `B1`.

There are two major pieces to this:

---

`TEXT(25569+A1/86400,"yyy-mm-ddThh:mm:ss")`
`25569` is the numerical equivalent of 1970-01-01 in Excel which measures from 1900-01-00 as zero.
`A1/86400` converts seconds into days.
`"yyyy-mm-ddThh:mm:ss"` formats the result, giving us the majority of the desired output.

---

`SUBSTITUTE(LEFT(TEXT(B1/10^9,"."&REPT(0,9)),7),".000000",)`
`TEXT(B1/10^9,"."&REPT(0,9))` converts from an integer of nanoseconds to a decimal of seconds.
`LEFT(TEXT(~),7)` gives the decimal point with the leading 6 digits.
`SUBSTITUTE(LEFT(~),".000000",)` accounts for a \<1,000 nanoseconds by dropping the result.

---

Aside: Given how friendly Excel is with dates, it makes sense - but is still annoying - that it takes more bytes to deal with `.000000` than it does to deal with `1970-01-01T00:00:00`. I found alternate approaches with less bytes but they only work if we can round the nanoseconds or display zero values. Alack and alas.

# Answer
> 1 votes
# Raku, 46 bytes 40 chars, 42 bytes

```
{(~DateTime.new($^a+$^b divⅯ/1e6)).chop}

```

Try it online!

Saved a few bytes by using a non-digit numeral (which could be replaced by others like , but others like  or  add an extra byte), which allowed the space removed after `div`. Only trick here was needing to force the round down, and stringify the `DateTime` to be able to `.chop`. There may in fact be a bug here in that Rakudo's implementation rounds up, and if we consider it as such, then it can be further golfed to

```
{(~DateTime.new($^a+$^b/1e9)).chop}

```

Which would only be 35 chars/bytes.

# Answer
> 1 votes
# J-uby, 42 bytes

Uses `-rtime` flag to get `Time#iso8601`.

```
~(~(:at&Time)&:nsec)|~:iso8601&6|~:[]&26&0

```

Attempt This Online!

## Explanation

```
~(~(:at & Time) & :nsec) |  # Time.at(secs, nsecs, :nsec), then
~:iso8601 & 6 |             # ISO-8601 w/ 6 fractional digits, then
~:[] & 26 & 0               # Get first 26 chars (drop time zone)

```

---
Tags: code-golf, date
---


title: How many times, are they multiples?

text:
# Question
Title: How many times, are they multiples?
You are given three parameters: start(int), end(int) and list(of int);

Make a function that returns the amount of times all the numbers between **start** and **end** are multiples of the elements in the **list**. example:

```
start = 15; end = 18; list = [2, 4, 3];
15 => 1 (is multiple of 3)
16 => 2 (is multiple of 2 and 4)
17 => 0
18 => 2 (is multiple of 2 and 3)
result = 5

```

The function should accept two positive integer numbers and an array of integers as parameters, returning the total integer number. Assume that start is less \<= end.

examples:

```
Multiple(1, 10, [1, 2]); => 15
Multiple(1, 800, [7, 8]); => 214
Multiple(301, 5000,[13, 5]); => 1301

```

The shortest solution is the victor!!! May he odds be ever in your favor...

# Answer
> 12 votes
# 05AB1E, 5 bytes

```
ŸÑ˜åO

```

Try it online!

---

### Explanation

```
Ÿ       - the numbers between start and end
 Ñ      - get their divisors
  ˜     - deep flatten this list
   å    - find the instances of the elements in the list in these divisors
    O   - Sum this

```

# Answer
> 10 votes
# Haskell, 33 bytes

```
(a#b)x=sum[1|0<-mod<$>[a..b]<*>x]

```

Try it online!

Explanation:

```
(a#b)x                            --take two values a and b and the list x
                      [a..b]      --generate the range a, a+1, ... , b
                mod<$>[a..b]      --partially apply "mod" to each entry of the list
                mod<$>[a..b]<*>x  --apply the partially applied functions to all values of the list x
          [1|0<-mod<$>[a..b]<*>x] --generate a new list with a one for every zero in the previously computed list
(a#b)x=sum[1|0<-mod<$>[a..b]<*>x] --sum it all up

```

# Answer
> 10 votes
# JavaScript (Node.js), 44 bytes

```
(a,x,y)=>a.map(n=>t+=y/n-(~-x/n|0)|0,t=0)&&t

```

Try it online!

---

# Python 2, 38 bytes

```
lambda a,x,y:sum(y/i-~-x/i for i in a)

```

Try it online!

\\$ \sum \_{i \in list} \lfloor \frac{end}{i} \rfloor - \lfloor \frac{start-1}{i} \rfloor \\$

The answer seems trivial and naive. So am I misunderstand something?

# Answer
> 7 votes
# Perl 6, 21 bytes

```
{sum $^a..$^b X%%@^c}

```

Try it online!

### Explanation

```
{                   }   # Anonymous codeblock returning
 sum                    # The sum of
     $^a..$^b           # How many numbers in the range a to b
              X%%       # Are divisible by any of
                 @^c    # The third parameter

```

# Answer
> 7 votes
# MATL, 5 bytes

```
:i\~z

```

Inputs are a cell array containing the `start` and `end` values, and then a column vector defining `list`.

Try it online! Or verify all test cases.

### Explanation

```
:    % Range, with implicit input: cell array {start, end}. This gives the range
     % from start to end
i    % Input: list of numbers in the form of a column vector
\    % Modulo, with boradcast. This gives a matrix with each number in the range
     % modulo each number in the list
~    % Logical negation
z    % Number of nonzero entries. Implicit display

```

# Answer
> 6 votes
# Python 3, 54 bytes

```
lambda s,e,L:sum(n%l<1for n in range(s,e+1)for l in L)

```

Try It Online!

# Answer
> 5 votes
# , 35 bytes

```
function(a,b,l)sum(b%/%l-(a-1)%/%l)

```

Try it online!

Implementation of tsh's method by Giuseppe. 3 bytes shorter than the previous version:

# , ~~45~~ 38 bytes

-7 bytes thanks to Nick Kennedy and Xi'an.

```
function(a,b,l)sum(!outer(a:b,l,`%%`))

```

Try it online!

Boils down to summing the values of `!(x %% y)` for `x` in `a:b` and `y` in `l` (`%%` is \\$mod\\$ in R, so `x %% y == 0` iff `x` is a multiple of `y`).

# Answer
> 5 votes
# APL+WIN, ~~20~~ 15 bytes

5 bytes saved thanks to Adam.

Prompts for end integer, start integer and then list:

```
+/,0=⎕∘.|⎕↓0,⍳⎕

```

Try it online! Courtesy of Dyalog Classic

Could be reduced to 9 bytes if we could enter two lists and not have to generate the first:

```
+/,0=⎕∘.|⎕

```

# Answer
> 5 votes
# C++ (clang), ~~113~~ ~~110~~ ~~109~~ ~~108~~ ~~106~~ ~~100~~ ~~93~~ ~~99~~ ~~91~~ 89 bytes

```
using I=int;I s;void f(I a,I b,I*l,I z,I&s){for(s=0;a<=b;++a)for(I i=z;i--;)s+=a%l[i]<1;}

```

Try it online!

Saved 3 bytes thanks to @AZTECCO!!!
Saved ~~6~~ 13 bytes thanks to @bznein!!!
~~Added 6~~ Saved 8 bytes thanks to @AZTECCO (and now it's playing by the rules)!!!

# Answer
> 4 votes
# Ruby, 41 bytes

```
->a,e,l{l.sum{|x|(a..e).count{|r|r%x<1}}}

```

Try it online!

# Answer
> 4 votes
# JavaScript (ES6), 47 bytes

Takes input as `(list, start)(end)`.

```
(a,x,s=0)=>g=y=>y<x?s:g(y-1,a.map(c=>y%c||s++))

```

Try it online!

# Answer
> 4 votes
# K (oK), 16 bytes

```
{+//~z!\:x_!1+y}

```

Try it online!

## Explanation:

```
{+//~z!\:x_!1+y} - function with 3 arguments [x;y;z] <- (start; end; list)
           !1+y  - a list 0 to end (inclusive)
         x_      - drop the first start numbers
     z!\:        - find the modulo of each number in the range start..end with each of list
    ~            - negate (0 becomes 1, non-zero becomes 0)
 +//             - reduce by addition and converge (repeat until result stops changing)

```

# , 22 bytes

```
1#.1#.0=[|/(}.i.,])/@]

```

Try it online!

## Explanation:

The verbs (functions) in  can take one (right) or two (left and right) arguments. The left argument is the `list`, the right one - a list of the `start` and `end` numbers.

```
           (       )/@     insert the verb in () between the elements of
                      ]    the right argument (start and end)
                 ,         append
               i.          a list 0..end-1
                  ]        to the right argument (end)
             }.            drop start elements
          |/               insert modulo verb between the above list and
         [                 the left argument (the list)
       0=                  compare each with 0
    1#.                    sum by base 1 conversion
 1#.                       sum by base 1 conversion
                           (we do it twice, because the result of |/ is a table)

```

# Answer
> 3 votes
# Python 2, 54 bytes

```
f=lambda n,m,l:m/n and sum(n%i<1for i in l)+f(n+1,m,l)

```

Try it online!

# Answer
> 3 votes
# APL (Dyalog Extended), 9 bytesSBCS

Full program, prompting for **end**, **start**, **list**, from stdin.

```
≢⍸=⎕|\⎕…⎕

```

Try it online!

prompt for **end**

`⎕…` prompt for **start** and generate progression vector

`⎕|\` prompt for \**list\* and make division remainder table

`=` Boolean mask indicating where equal to zero

get the indices of the Trues

tally them

# Answer
> 3 votes
# Bash, 40 bytes

```
eval set !\$[{$1..$2}%{$3}]+;echo $[$*0]

```

Try it online!

# Answer
> 3 votes
# APL(NARS), chars 13, bytes 26

```
{+/∊0=⍺∣../⍵}

```

⍺ it is the list of divisors, ⍵ it is the range. Test:

```
  1 2{+/∊0=⍺∣../⍵}1 10
15
  7 8{+/∊0=⍺∣../⍵}1 800
214
  13 5{+/∊0=⍺∣../⍵}301 5000
1301
  13 5 3 11{+/∊0=⍺∣../⍵}301 5000
3294

```

# Answer
> 2 votes
# Jelly, 7 bytes

```
r/ḍ@€FS

```

Try it online!

A dyadic link taking a list of `[start, end]` as the left argument and the list of possible divisors as the right argument. Returns an integer indicating the total number of possible divisions.

# Answer
> 2 votes
# Java (JDK), ~~115~~ 67 bytes

```
(s,e,d)->{int t=0;for(;s<=e;s++)for(int j:d)t+=s%j<1?1:0;return t;}

```

*48 bytes saved thanks to Olivier*

Try it online!

First time golfing in Java, so this is a new experience for me.

# Answer
> 1 votes
# Icon, 59 bytes

```
procedure f(a,b,l)
n:=0
(a to b)%!l<1&n+:=1&\z
return n
end

```

Try it online!

# Answer
> 1 votes
# Japt `-x`, ~~7~~ 6 bytes

```
rõ ïvV

```

Try it

```
rõ ïvV     :Implicit input of arrays U=[start,end] and V=list
           > e.g., U=[15,18] V=[2,4,3]
r          :Reduce U by
 õ         :  Inclusive range
           > [15,16,17,18]
   ï V     :Cartesian product with V
           > [[15,2],[15,4],[15,3],[16,2],[16,4],[16,3],[17,2],[17,4],[17,3],[18,2],[18,4],[18,3]]
    v      :Reduce each pair by testing the divisibility of the first by the second
           > [0,0,1,1,1,0,0,0,0,1,0,1]
           :Implicit output of sum of resulting array
           > 5

```

# Answer
> 1 votes
# Python 54 bytes

```
lambda K,M,H:sum(n%l<1for n in range(K,M+1)for l in H)

```

# Answer
> 1 votes
# Kotlin, 69 bytes

```
{s:Int,e:Int,l:List<Int>->(s..e).toList().sumBy{v->l.count{v%it==0}}}

```

Try it online!

# Answer
> 1 votes
# Husk, 6 bytes

```
#0×`%…

```

Try it online! Nothing very special.

# Answer
> 1 votes
# Vyxal `d`, ~~5~~ 4 bytes

```
ṡ$vḊ

```

*-1 byte thanks to @lyxal*

Try it online!

Explanation:

```
ṡ     # Range from a to b
 $    # Swap (last input is now on top)
  vḊ  # For each in the range, test for divisibility with the last input
      # Deep flatten and sum with the d flag

```

# Answer
> 0 votes
# Charcoal, 11 bytes

```
Ｉ⁻Σ÷ηζΣ÷⊖θζ

```

Try it online! Link is to verbose version of code. Explanation:

```
    η       Second input (End)
     ζ      Third input (List)
   ÷        Vectorised integer division
  Σ         Sum
         θ  First input (Start)
        ⊖   Decremented
          ζ Third input (List)
       ÷    Vectorised integer division
      Σ     Sum
 ⁻          Subtract
Ｉ           Cast to string
            Implicitly print

```

# Answer
> 0 votes
# Pyth, 15 bytes

```
/.nm%LdeQ}.*PQ0

```

Try it online!

Takes input as `start, end, list`

Explanation:

```
         }        # Inclusive range
          .*      # Splat (list becomes list of arguments)
            PQ    # All but the last element of the input
                  # --> inclusive range from start to end
   m              # map each number of that
     L eQ         # to a map of each member of Q[-1] = list
    % d           # remainder modulo member (2, 4, 3 in example)
                  # --> List of lists of remainders
 .n               # flatten
/              0  # count zeroes

```

# Answer
> 0 votes
# Perl 5 (`-ap`), 33 bytes

```
for$i(<>..<>){$i%$_||$\++for@F}}{

```

Try it online!

# Answer
> 0 votes
# C# (Visual C# Interactive Compiler), 54 bytes

```
(a,b,l)=>l.Where(x=>a%x<1).Count()+(++a>b?0:f(a,b,l));

```

Try it online!

Recursive approach

# Answer
> 0 votes
# SimpleTemplate, 86 bytes

Yeah, kinda long, but it works!
Receives 2 numbers (in any order) and an array/string of 1-digit numbers (e.g.: `"243"`), passed to the `render()` method of the compiler.

```
{@fori fromargv.0 toargv.1}{@eachargv.2}{@ifi is multiple_}{@incR}{@/}{@/}{@/}{@echoR}

```

Displays the result or nothing, if none is

---

**Ungolfed**

```
{@set count 0}
{@for i from argv.0 to argv.1}
    {@each argv.2 as number}
        {@if i is multiple of number}
            {@inc by 1 count}
        {@/}
    {@/}
{@/}
{@echo count}

```

Should be mostly straightforward.

---

You can try it on http://sandbox.onlinephpfunctions.com/code/b26cd7f75e0c4676038573c4274180891a890895

Change line 986 to test the golfed and ungolfed versions, and line 988 to get the input.

# Answer
> 0 votes
## Mathematica, 52 bytes

```
f[s_,e_,l_]:=(q=Quotient;Total[q[e,#]-q[s-1,#]&/@l])

```

This uses the simplification formula from @tsh

A less clever solution at 66 bytes but more directly following the OP:

```
f[s_,e_,l_]:=Total[Length@Intersection[Divisors@#,l]&/@Range[s,e]]

```

# Answer
> 0 votes
# Excel VBA, 77 Bytes

Immediate window function that takes *start* from `[A1]`, *end* from `[B1]`, and *list* from column `C` (`[C:C]`). Output is directed to the immediate window.

`[C:C].SpecialCells(2)` is used to iterate `j` over only the cells in Column `C` which contain a value, as non-valued cells produce an error.

```
For i=[A1]To[B1]:For Each j In[C:C].SpecialCells(2):s=s-(i/j=i\j):Next j,i:?s

```

---
Tags: code-golf, math, division
---


# Question
Title: It's Just Rocket Science, Part 2 - Centrifuge
You've gotten out of Earth's gravity well \- good for you! However, you're feeling a bit uncomfortable in zero-gravity, and you want to replicate 1 \\$g\\$ of force in a centrifuge. Use the equation for force in a centrifuge: $$\text{RCF} = \frac{r\_\text{m} \\, \left(\frac{2 \pi N\_\text{RPM}}{60}\right)^2}{g}$$ Where

* \\$\text{RCF}\\$ is "relative centrifugal force", or the force relative to 1 \\$g\\$; in this case we want this to be \\$1\\$.
* \\$r\_\text{m}\\$ is the radius of the centrifuge in meters. You can take this, or a similar quantity - for example, taking it in millimeters.
* \\$N\_\text{RPM}\\$ is the rotational speed in revolutions per minute. You're going to output this.
* \\$g\\$ is the local gravitational field of Earth \- for this challenge, use the standard value of \\$9.80665\\;\text{m}/\text{s}^2\\$.

In alternate form, when \\$\text{RCF} = 1\\$: $$N\_\text{RPM} = \dfrac{60\sqrt{\dfrac{g}{r\_\text{m}}}}{2\pi}.$$

To clarify: take the radius of the centrifuge, output rotational speed in RPMs, with precision to 6 significant digits. Scoring is standard for . Test cases (calculated using SpinCalc):

```
1 -> 29.904167719726267
10 -> 9.456528152601877
50 -> 4.229087956071661
87 -> 3.206063305621029
100 -> 2.9904167719726273
103 -> 2.946545199338184
167 -> 2.314053973112157
200 -> 2.1145439780358304
224 -> 1.9980562507828685
250 -> 1.8913056305203755
264 -> 1.8404742955585696
300 -> 1.726517928287568
328 -> 1.651181438643768
400 -> 1.4952083859863137
409 -> 1.4786659280153986
1000 -> 0.9456528152601877
2000 -> 0.6686775183186282
10000 -> 0.2990416771972627

```

# Answer
# Python, 24 bytes

```
lambda r:29.904167/r**.5

```

## Attempt This Online!

## Explanation

The expression we're trying to calculate is

$$N\_\text{RPM} = \dfrac{60\sqrt{\dfrac{g}{r\_\text{m}}}}{2\pi}.$$

If we rearrange terms, we can turn this into

$$N\_\text{RPM} = \dfrac{60\dfrac{\sqrt{g}}{\sqrt{r\_\text{m}}}}{2\pi} = \dfrac{60\sqrt{g}}{2\pi\sqrt{r\_\text{m}}} = (\dfrac{60\sqrt{g}}{2\pi})\frac{1}{\sqrt{r\_\text{m}}}$$

Since we know \\$g = 9.80665\\$ (it's constant), we can calculate the value of the \\$(\dfrac{60\sqrt{g}}{2\pi})\\$ term, getting approximately \\$29.904167\\$. In other words,

$$N\_\text{RPM} \approx 29.904167\frac{1}{\sqrt{r\_\text{m}}}$$
> 4 votes

# Answer
## Python, ~~53~~ ~~52~~ ~~41~~ 39 bytes

```
lambda a:30*(9.80665/a)**0.5/3.14519265

```

Try it online!

* -2 bytes thanks to The Thonnu
> 3 votes

# Answer
# Jelly, ~~16~~ ~~15~~ 13 bytes

```
8825.985÷½÷ØP

```

Attempt This Online!

This is my first Jelly answer, so it can almost certainly be golfed.

* -1 byte thanks to MehanAlavi
> 2 votes

# Answer
# Go, 64 bytes

```
import."math"
func f(r float64)float64{return 29.904167/Sqrt(r)}

```

Attempt This Online!
> 2 votes

# Answer
# Raku, 16 bytes

```
29.904167/*.sqrt

```

Try it online!

I searched in vain for some short combination of Unicode characters whose numerical values could be combined in some way to get a number very close to the constant factor here. Oh well!
> 2 votes

# Answer
# Factor, 21 bytes

```
[ -.5 ^ 29.904167 * ]

```

Try it online!

Port of 97.100.97.109's Python answer.
> 2 votes

# Answer
# Vyxal, 13 bytes

```
29.9041677?√/

```

Try it Online!
> 2 votes

# Answer
# x86 32-bit machine code, 16 bytes

```
68 98 90 5F 44 D9 04 24 D8 74 24 08 D9 FA 58 C3

```

Try it online!

Following the `cdecl` calling convention, this takes \\$r\_{\mathrm{m}}\\$ on the stack and returns \\$N\_{\mathrm{RPM}}\\$ on the FPU register stack.

In assembly:

```
f:  .byte 0x68                  # Push a 4-byte value onto the stack:
    .single 894.259247009518535 #  this value, which equals (60/2π)²·g.
    fld DWORD PTR [esp]         # Put that value onto the FPU register stack.
    fdiv DWORD PTR [esp + 8]    # Divide it by the value given.
    fsqrt                       # Take the square root.
    pop eax                     # Pop the value added to the stack.
    ret                         # Return.

```
> 1 votes

# Answer
# K (ngn/k), 13 bytes

```
29.9041677%%:

```

Try it online!

Dead simple. Doesn't display correctly with all numbers correct up to all precision, but that isn't a requirement anyway.

Explanation:

```
29.9041677%%:    Main program. Takes implicit input
            :    Takes input from the right side
           %     Square root
          %      Divide with
29.9041677       Literal number "29.9041677"

```
> 1 votes

# Answer
# Charcoal, 21 bytes

```
Ｉ∕₂∕⁸⁸²⁵·⁹⁸⁵Ｎ≕math.pi

```

Try it online! Link is to verbose version of code. Calculates the answer as accurately as possible. Explanation: The constant `8825.985` arises from the following calculation:

$$ \frac{60\sqrt{\frac{g}{r\_\text{m}}}}{2\pi}=\frac{30\sqrt{\frac{g}{r\_\text{m}}}}\pi=\frac{\sqrt{\frac{900g}{r\_\text{m}}}}\pi $$

```
    ⁸⁸²⁵·⁹⁸⁵            Literal number `8825.985`
   ∕                    Divided by
            Ｎ           Input number
  ₂                     Take the square root
 ∕                      Divided by
             ≕math.pi   Python variable `math.pi`
Ｉ                       Cast to string
                        Implicitly print

```

13 bytes by porting @adam's approximation:

```
Ｉ∕²⁹·⁹⁰⁴¹⁶⁷₂Ｎ

```

Try it online! Link is to verbose version of code.
> 0 votes

# Answer
# 05AB1E, 12 bytes

```
tz•1Íãǝ•*6°/

```

Port of *@97.100.97.109*'s Python answer.

Try it online or verify all test cases.

A port of the Jelly answer would be 1 byte longer:

```
•‡»µ•₄/I/tžq/

```

Try it online or verify all test cases.

**Explanation:**

```
t              # Take the square root of the (implicit) input
 z             # Calculate 1 divided by this value
  •1Íãǝ•*      # Multiply it by compressed integer 29904167
         6°/   # Divide it by 1000000 (6**10)
               # (after which the result is output implicitly)

•‡»µ•          # Push compressed integer 8825985
     ₄/        # Divide it by 1000: 8825.985
       I/      # Divide it by the input
         t     # Take the square root of that
          žq/  # Divide it by PI (3.141592653589793)
               # (after which the result is output implicitly)

```

See this 05AB1E answer of mine (section *How to compress large integers?*) to understand why `•1Íãǝ•` is `29904167` and `•‡»µ•` is `8825985`.
> 0 votes

# Answer
# Japt, 11 bytes

Port of the Python solution.

```
29.904#§/U¬

```

Try it
> 0 votes

---
Tags: code-golf, math
---


title: It's Just Rocket Science

text:
# Question
Title: It's Just Rocket Science
Write a program/function that finds the amount of fuel needed to escape Earth's gravity well given the exhaust velocity of the fuel and the amount of mass to transport using the Tsiolkovsky rocket equation: $$\Delta v = v\_\text{exhaust}\ln\dfrac{m\_\text{start}}{m\_\text{end}}$$ where

* \\$\Delta v\\$ is the change in velocity from start to finish (in this case, escape velocity is about 11.2 km/s, so you will use that)
* \\$v\_\text{exhaust}\\$ is the exhaust speed of the fuel (you will be given this)
* \\$m\_\text{start}\\$ is the starting mass of the ship (i.e. including fuel)
* \\$m\_\text{end}\\$ is the ending mass of the ship (i.e. excluding fuel) (you will also be given this)

Equivalently, you have to calculate \\$m\_\text{start}-m\_\text{end},\\$ which is the mass of the fuel.

The mass you need to get away from Earth will be given in kg\*, and the exhaust speed in km/s with precision in the tenths. Return the mass of fuel in kg\*. You can take input in any acceptable format, including (but not limited to):

* Mass as integer, exhaust speed as double/float
* Mass as integer, exhaust speed as integer representing tenths (for example, 24 would represent 2.4)
* Mass as string, exhaust speed as string

Output at least with precision to the integer (that is, when rounded to the nearest integer, your answer should be correct), and in any reasonable format (integer, float, string). Standard loopholes apply. Scoring is shortest answer per language wins, as is standard .

Sample implementation in Python:

```
import math

DELTA_V = 11.2

def fuel(mass: int, exhaust_speed: float) -> float:
    ratio = math.exp(DELTA_V / exhaust_speed) # m_start / m_end
    return mass * (ratio - 1)

```

Try it online!

Test cases (note that they aren't exact):

```
(0, 1) -> 0
(1, 2.4) -> 105.34267539816554
(100, 2.4) -> 10534.267539816554
(100, 100) -> 11.851286064504517
(1000, 4) -> 15444.646771097048
(597, 4) -> 9220.454122344938
(597, 4.2) -> 7994.973908804485

```

## Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
# Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

## ```
var QUESTION_ID=252264;
var OVERRIDE_USER=114332;
var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}}
```

```
body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table>
```

* Technically, you can use any unit, as long as it's the same for input and output - it doesn't really matter.

# Answer
> 8 votes
# Raku, ~~19~~ 18 bytes

```
*×(e**(11.2/*)-1)

```

*saved one byte by using the built-in constant e instead of the exp function*

Try it online!

This is a "WhateverCode" expression, a short way of defining an anonymous function where the lone asterisks mark where the function arguments will go.

# Answer
> 6 votes
# Factor, 24 bytes

```
[ 11.2 swap / e^ 1 - * ]

```

Attempt This Online!

```
       ! 1 2.4
11.2   ! 1 2.4 11.2
swap   ! 1 11.2 2.4
/      ! 1 4.666666666666667
e^     ! 1 106.3426753981655
1      ! 1 106.3426753981655 1
-      ! 1 105.3426753981655
*      ! 105.3426753981655

```

# Answer
> 5 votes
# JavaScript (ES7), 22 bytes

### Approximation

Expects `(ending_mass)(exhaust_speed)`.

```
m=>s=>m*73130**(1/s)-m

```

Try it online!

This is:

$$m\times \left(e^{11.2}\right)^{1/s}-m$$

with \\$e^{11.2}\approx 73130\\$

Maximum error for the test cases: \\$\approx0.027\\$

---

# JavaScript (ES6), 25 bytes

*-1 by using tenths for the exhaust speed, as pointed out by @CommandMaster*

### Exact formula

Expects `(ending_mass)(exhaust_speed)` where the exhaust speed is expressed in tenths.

```
m=>s=>m*Math.exp(112/s)-m

```

Try it online!

# Answer
> 3 votes
# Fig, \\$11\log\_{256}(96)\approx\\$ 9.054 bytes

```
*{^mE\x11.2

```

Try it online!

Forgot to mention that it expects exhaust speed first and then mass.

```
*{^mE\x11.2  : Full program
     \x11.2  : Divides 11.2 by first input
  ^mE        : e^result
 {           : Decrement
*            : Multiply given only one argument so second input is implied

```

# Answer
> 3 votes
# Rust, ~~28~~ 27 bytes

```
|m,v:f64|m*(11.2/v).exp()-m

```

Attempt This Online!

* -1 byte by @Steffan

# Answer
> 3 votes
# Python, 31 bytes

```
lambda m,e:m*(1+7e-9/e)**16e8-m

```

Attempt This Online!

Avoids the math import by using \\$e^x\approx(1+x/n)^n\\$ for large n.

# Answer
> 2 votes
# Jelly,  ~~9~~  8 bytes

-1 by taking the exhaust velocity in 10ths - thanks Kevin Cruijssen!

```
112÷Æe’×

```

A dyadic Link that accepts the exhaust velocity on the left, in tenths, and the mass on the right and yields the fuel mass.

**Try it online!**

### How?

```
112÷Æe’× - Link: number v, number m
112      - 112
   ÷     - divide by v
    Æe   - Exp(that)
      ’  - decrement
       × - multiply by m

```

# Answer
> 2 votes
# Desmos, 20 bytes

```
f(m,v)=me^{11.2/v}-m

```

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 2 votes
# , 50 bytes

I does not have exponentiation, so e^x is approximated with the Taylor series.

```
*H 1/(inf. i+1p2f *.r)*(11.2/].  *p inf.i H]). +.r

```

# Answer
> 1 votes
# Go, 64 bytes

```
import."math"
func f(m,v float64)float64{return m*Expm1(11.2/v)}

```

Attempt This Online!

# Answer
> 1 votes
# 05AB1E, ~~11~~ 9 bytes

```
žrƵBI/m<*

```

Inputs in the order: \\$v\_{exhaust}, m\_{end}\\$, where \\$v\_{exhaust}\\$ is taken as an integer representing tenths.

Try it online or verify all test cases.

**Explanation:**

```
žr         # Push constant e: 2.718281828459045
  ƵB       # Push compressed integer 112
    I/     # Divide it by the first input (exhaust speed as tenths)
      m    # Take e to the power this
       <   # Decrease it by 1
        *  # Multiply it to the second (implicit) input (mass)
           # (after which the resulting fuel mass is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `ƵB` is `112`.

# Answer
> 1 votes
# MathGolf, ~~10~~ 8 bytes

```
8D*╠e▬(*

```

Inputs in the order: \\$v\_{exhaust}, m\_{end}\\$, where \\$v\_{exhaust}\\$ is taken as a ***float*** representing tenths (e.g. `24.0`).

Try it online.

**Explanation:**

```
8D*       # Multiply 8 by 14: 112
   ╠      # Divide it by the first (implicit) input-float (exhaust speed as tenths)
    e▬    # Push e (2.718281828459045) to the power this
      (   # Decrement it by 1
       *  # Multiply it to the second (implicit) input-integer (mass)
          # (after which the entire stack is output implicitly as resulting fuel mass)

```

: `/` is used for both integer division (if both arguments are integers) and regular division (if either or both arguments are floats). So I can't take the first input \\$v\_{exhaust}\\$ as tenths as an integer.

# Answer
> 1 votes
# C (gcc), 29 bytes

```
#define f(m,v)m*exp(11.2/v)-m

```

Try it online!

*Update:* Removed typdef and unnecessary includes. Thanks to @AZTECCO

# Answer
> 1 votes
# BQN, ~~14~~ ~~13~~ 12 bytes

*Edit: -1 byte thanks to faun locke*
*Edit 2: -1 byte by taking input in tenths of km/s (thanks to Kevin Cruijssen's comment)*

```
⊣×1-˜⟜⋆112⊸÷

```

Try it at BQN REPL

Exhaust speed given as an integer representing tenths of km/s.

Or as a function for 1 more byte: `{×1-˜⋆112÷}` (try it)

```
        11.2⊸÷   # 11.2 divided by right arg
       ⋆         # exponent of that
   1-˜⟜          # one minus that
 ⊣×              # times left arg

```

# Answer
> 1 votes
# Python, 27 Bytes

```
lambda m,e:m*73130**(1/e)-m

```

Try it online

# Answer
> 1 votes
# Vyxal, ~~9~~ 8 bytes

```
⁺»?/∆e‹*

```

Try it Online!

# Answer
> 0 votes
# Python, ~~45~~ 43 bytes

```
lambda m,e:m*math.exp(11.2/e)-m
import math

```

Attempt This Online!

Uninteresting answer.

---

-2 bytes from @att

# Answer
> 0 votes
# Charcoal, 18 bytes

```
Ｉ×Ｎ⊖Ｘ≕math.e∕¹¹·²Ｎ

```

Try it online! Link is to verbose version of code. Explanation:

```
  Ｎ                 First input as a number
 ×                  Multiplied by
     ≕math.e        Python variable `math.e`
    Ｘ               Rasied to power
             ¹¹·²   Literal number `11.2`
            ∕       Divided by
                 Ｎ  Second input as a number
   ⊖                Decremented
Ｉ                   Cast to string
                    Implicitly print

```

# Answer
> 0 votes
# Japt, 9 bytes

Takes mass as the first input and speed, represented as tenths, as the second.

```
nU*Me#p/V

```

Try it

```
nU*Me#p/V     :Implicit input of integers U=mass & V=speed
n             :Subtract U from
 U*           :  U multiplied by
   Me         :  Euler's Constant raised to the power of
     #p       :    112
       /V     :    Divided by V

```

# Answer
> 0 votes
# MATLAB, 45 bytes

```
function y=fuel(m,v) y=m*(exp(11.2/v)-1); end

```

---
Tags: code-golf, math
---