# Question
Title: Create \$n\$ sublists with the powers of two (1, 2, 4, 8, 16...)
## Challenge:

Given the input number `n`. It should give me nested sublists of `n` layers with the power of two numbers for each level. Each power of two value will be in separate sublists.

## Notes:

* `n` will always be greater than 0
* I am using the example output with Python Lists. You can use any type of sequence in your own language.
* Your output must be one-indexed, add one to `n` if your output is zero-indexed.
* Your output sequence must be nested.

## Test cases:

```
n = 1: [1]
n = 2: [1, [2]]
n = 3: [1, [2, [4]]]
n = 4: [1, [2, [4, [8]]]]
n = 5: [1, [2, [4, [8, [16]]]]]
n = 6: [1, [2, [4, [8, [16, [32]]]]]]
n = 7: [1, [2, [4, [8, [16, [32, [64]]]]]]]

```

This is , so the shortest code in bytes wins!

The power of twos are these values `1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048...`, each values is double of the previous value.

# Answer
> 7 votes
# Factor \+ `math.polynomials`, 47 bytes

```
[ 2 powers reverse 1 cut [ swap 2array ] each ]

```

Try it online!

```
        ! 4
2       ! 4 2
powers  ! { 1 2 4 8 }
reverse ! { 8 4 2 1 }
1       ! { 8 4 2 1 } 1
cut     ! { 8 } { 4 2 1 }
        ! { 8 } 4              <<first iteration of each>>
swap    ! 4 { 8 }
2array  ! { 4 { 8 } }
        ! { 4 { 8 } } 2        <<second iteration>>
swap    ! 2 { 4 { 8 } }
2array  ! { 2 { 4 { 8 } } }
        ! { 2 { 4 { 8 } } } 1  <<third>>
swap    ! 1 { 2 { 4 { 8 } } }
2array  ! { 1 { 2 { 4 { 8 } } } }

```

# Answer
> 5 votes
# Vyxal, ~~9~~ 6 bytes

```
(d1$"ꜝ

```

Try it Online!

Uses the fact that stack languages can have their input placed on the stack before execution

Proof the meta proposal was +6 at the time of posting

## Explained

A port of Jelly

```
(d1$"ꜝ
(      # repeat input times
 d     # double
  1$"  # [1, that]
     ꜝ #  keep only truthy items

```

# Answer
> 5 votes
# \>\<\>, 47 bytes

```
1i:?v~~l?^;
/$-1/
/on$o"[,":
\2*$:}10./"]"o~60.

```

Try it!

Generates trailing commas at the end of lists, some languages allow that so that should be OK. Takes input as a char code.

Uses the length of the stack to keep track of how many `]` to generate at the end.

# Answer
> 5 votes
# Python 3, 44 bytes

```
e=lambda n,i=1:[i,e(n-1, i*2)]if n>0 else[i]

```

Try it online!

# Answer
> 4 votes
# Jelly, 7 bytes

```
Ḥ1,¹ƇƲ¡

```

Try it online!

-2 bytes thanks to caird coinheringaahing (use STDIN to avoid needing the leading `0`, and a shorter way of filtering the `0`)

```
Ḥ1,¹ƇƲ¡    Main Link (input in STDIN, so argument starts at 0)
      ¡    repeat N times
Ḥ          double the current list
 1,        pair with 1
   ¹Ƈ      filter by identity; remove falsy elements (filter out the 0 in the first step)

```

# Answer
> 4 votes
# Ruby, ~~36~~ 34 bytes

```
->n{*r=k=2**n;n.times{r=k/=2,r};r}

```

Try it online!

# Answer
> 4 votes
# 05AB1E, 7 bytes

```
F·Xs‚ZK

```

Try it online!

Port of lyxal's Vyxal answer.

* -1 thanks to Kevin Cruijssen

### Explanations:

```
F·Xs‚ZK   # Implicit input (n)
F         # for i in range(a):
 ·        #  Double
  Xs‚     #  Get [1, that] (X defaults to 1)
     ZK   #  Push the list without the maximum

```

Previous 8 byte answer:

```
L<o`¸¹G‚   # Implicit input (n)
L<         # range(0, n)
  o        # 2 to the power of each
   `¸      # Dump onto stack, putting the last one in a list
     ¹G    # n-1 times:
       ‚   #  Pair

```

Previous 13 byte answer:

```
<Do¸sE¹<N-o‚R   # Implicit input (n)
<               # Reduce n by 1
 Do¸            # Duplicate and push [2**(n-1)] to the stack
    sE          # Swap and loop through range(0, n-1):
      ¹<N-      #  Subtract from n-1
          o     #  Raise 2 to the power of this number
           ‚R   #  Pair and reverse

```

# Answer
> 4 votes
# , 44 bytes

```
f=\(n,k=1,`+`=list)`if`(n-1,k+f(n-1,k*2),+k)

```

Attempt This Online!

# Answer
> 3 votes
# JavaScript (Node.js), 31 bytes

```
f=(x,i=1)=>--x?[i,f(x,i*2)]:[i]

```

Try it online!

# Answer
> 3 votes
# Pyth, 20 bytes

```
L+[^2b)?qtQbY[yhb)y0

```

Try it online!

```
L                      # Function y with input as b
 +                     # Append
  [^2b)                # List with 2^b as only element
       ?               # Ternary operator
        qtQb           # If b is equal to input - 1
            Y          #  empty list (when condition is true)
             [yhb)     # Call function y with input b+1 and put inside a list (when condition is false)
                  y0   # Call function y with input 0

```

# Answer
> 3 votes
# Pip, 28 bytes

```
FiR,a{YlAEyPE EiUi=a?Y Hy0}y

```

Try It Online!

FiR,a{YlAEyPE EiUi=a?Y Hy0}y
FiR,a{                    }    Loop through [a, 0]
      YlAEyPE Ei               Set y (initially "") to y + 2**i wrapped in a list
                Ui=a?Y Hy0     Remove the empty string if it is the first iteration

```
</code></pre>

# Answer
> 3 votes
# MATL, 12 bytes

```
:qWP"@XhP]&D

```

Try it at **MATL online**!

```
:       % Implicit input, n. Range [1 2 ... n]
q       % Subtract 1, element-wise
W       % Powers of 2, element-wise
P       % Flip. Gives [2^(n-1) 2^(n-2) ··· 1]
"       % For each number in that vector
@       % Push current number
  Xh    %   Concatenate all stack contents into a cell array
  P     %   Flip
]       % End
&D      % String representation. Implicit display

```

# Answer
> 3 votes
# Knight (v2), 35 bytes

```
;=l,=c/^2=pP2;W=p-EpT=l+,=c/c 2,lDl

```

Try it online!

Looks golfable.

# Answer
> 3 votes
# K (ngn/k), 17 bytes

```
{(x-1)(1,,2*)/,1}

```

Try it online!

##### Explanation:

```
{(x-1)(1,,2*)/,1}
              ,1  start with list one
 (x-1)       /    do n-1 times
      (1,,2*)     1 joined with double the current value enlisted

```

# Answer
> 3 votes
# Python 3, 68 bytes

```
def f(n):
	for i in range(n):l=i and[l[0]//2,l]or[2**n//2]
	return l

```

Try it online!

# Answer
> 2 votes
# Python 3, ~~48~~ ~~42~~ 40 bytes

```
f=lambda n,c=1:n>1and[c,f(n-1,c+c)]or[c]

```

Try it online!

*-6 bytes thanks to l4m2*

*-2 bytes thanks to The Thonnu*

# Answer
> 2 votes
# Charcoal, 14 bytes

```
ＦＮ≔Φ⟦¹⊗υ⟧κυ⭆¹υ

```

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

```
ＦＮ

```

Repeat `n` times...

```
≔Φ⟦¹⊗υ⟧κυ

```

... double the predefined empty list and prepend a `1` (but on the first pass filter out the list as it is empty).

```
⭆¹υ

```

Pretty-print the final list.

# Answer
> 2 votes
# Retina, 36 bytes

```
"$&"{`\d+
$.(*2*
.+
[1, $&]
, \d+]
]

```

Try it online! Link includes test cases (because fortunately I was able to use `$&` instead of `$+`). Explanation:

```
"$&"{`

```

Repeat the program `n` times (because `n` is the input).

```
\d+
$.(*2*

```

Double all of the integers.

```
.+
[1, $&]

```

Wrap the list with `1` in a sublist.

```
, \d+]
]

```

Remove the original input.

# Answer
> 2 votes
# sclin, 19 bytes

```
[1]"2*1rev ,";1- *#

```

Try it here! Takes the argument from the next line. If outputting as an infinite sequence were allowed, then something like `1,,"2*1rev ,"itr` would be 16 bytes.

For testing purposes:

```
; n>o
1,,"2*1rev ,";1- *#
7

```

## Explanation

Prettified code:

```
[1] ( 2* 1rev , ) ;1- *#

```
* `[1]` starting with 1-length array of 1
* `(...) ;1- *#` repeat (next line) - 1 times...
    + `2* 1rev ,` vectorized-multiply by 2 and prepend 1

# Answer
> 2 votes
# Raku, 23 bytes

```
[1],{[1,2 «*«$_]}...*

```

Try it online!

This is an expression for the infinite sequence of arrays. The magic is in the `«*«` operator, which multiplies each element of an arbitrarily-deeply nested structure by a number.

# Answer
> 2 votes
# Pip `-p`, ~~18~~ 14 bytes

```
FI[EiUi<a&REa]

```

Try It Online!

-4 bytes thanks to @DLosc

Recursively builds the nested lists. `FI` is used to filter out the `0` in the last list, otherwise `[1;[2;[4;0]]]` would be output.

# Answer
> 2 votes
# Pip `-p`, 12 bytes

```
LaYFI[1y*2]y

```

Try It Online!

### Explanation

Same idea as hyper-neutrino's Jelly answer:

```
LaYFI[1y*2]y
              a is command-line argument; y is "" (implicit)
La            Loop a times:
       y*2      Multiply y by 2 (-> 0 if it's "", element-wise if it's a list)
     [1   ]     Put 1 and that value in a list
   FI           Filter, removing falsey values (in this case, 0)
  Y             Yank, assigning the result back to y
           y  After the loop, autoprint the final value of y

```

# Answer
> 2 votes
# MathGolf, 6 bytes

```
Æ∞1\αç

```

Port of *@lyxal*'s Vyxal answer.

Try it online.

**Explanation:**

```
Æ       # Loop the (implicit) input amount of times,
        # using the following five characters as inner code-block:
 ∞      #  Double all current values (the stack contains a 0 by default)
  1\α   #  Pair it with a leading 1
     ç  #  Falsey filter to remove the 0
        # (after the loop, the entire stack is output implicitly as result)

```

# Answer
> 1 votes
# Julia 1.0, 21 bytes

```
!n=[n<2||[1,2*!~-n];]

```

Try it online!

using  instead of `!` would save a character, since `a√b` is parsed as `a*√b` (which doesn't work for `!`). But of course the byte count would be higher.

# Answer
> 1 votes
# FunStack alpha, 40 bytes

```
Pair 1 Double over iterate Wrap 1 At Dec

```

Try it at Replit: pass the input number as a command-line argument and enter the program on stdin.

### Explanation

First, we generate the infinite sequence of such nested lists:

```
Pair 1

```

Given `x`, turn it into `[1, x]`.

```
Double

```

Multiply by 2 (applies itemwise over lists).

```
over

```

Given two arity-1 functions, this modifier works the same as `compose` but is 3 bytes shorter. The composed function is "Multiply the argument by 2 and pair 1 with the result."

```
iterate

```

Repeatedly apply this function and return the infinite list of results...

```
Wrap 1

```

... starting at `[1]`.

The resulting infinite list is a value at the left side of the program, so it gets pushed onto the argument list. Then:

```
At

```

Get the nth element, where n is...

```
Dec

```

... the first program argument, decremented (since indexing is 0-based).

# Answer
> 1 votes
# CJam, 14 bytes

```
{,W%{2\#]W%}%}

```

Anonymous code block that pops a number from the stack and pushes the nested array.

The header reads the input. The footer executes the block and prints the string representation of the array.

Port of my MATL answer.

**Try it online!**

### Code explanation

```
{,W%{2\#]W%}%}

{            }   e# define code block
 ,               e#   range (0-based)
  W%             e#   reverse array
    {      }%    e#   map this code block over the array
     2\#         e#     exponential with case 2
        ]        e#     pack all stack contents into an array
         W%      e#     reverse array

```

# Answer
> 1 votes
# Japt, ~~11~~ 9 bytes

```
o!²ÔòÎr!p

```

Try it

Explanation:

```
o!²ÔòÎr!p
o         # For X in [0...n-1]:
 !²       #  2 to the power of X
   Ô      # Reverse that array
    òÎ    # Partition between every non-zero element
      r   # Reduce:
       !p #  Push the previous result at the end of the next item

```

# Answer
> 1 votes
# Mathematica 39 bytes

With `n=5`

```
s=Nothing;Do[s={2^--i,s},{i,n,1,-1}];s

```

> {1, {2, {4, {8, {16}}}}}

# Answer
> 1 votes
`awk` solution - different solutions for `mawk-1/2` and `gawk/nawk` :

```
jot 16 |

```

> ```
> mawk 'function __(_){return $_=--_?_+=_=__(_):!_}__(NF=$_)' OFS=,
>
> ```

> ```
> nawk
> gawk 'func __(_){return $++_=--_?__(_)/_*(_+_):!_}__(NF=$-_)' OFS=,
>
>  * "function" is normally preferred, but this is Pebble Beach…
>
> ```

```
1
1,2
1,2,4
1,2,4,8
1,2,4,8,16
1,2,4,8,16,32
1,2,4,8,16,32,64
1,2,4,8,16,32,64,128
1,2,4,8,16,32,64,128,256
1,2,4,8,16,32,64,128,256,512
1,2,4,8,16,32,64,128,256,512,1024
1,2,4,8,16,32,64,128,256,512,1024,2048
1,2,4,8,16,32,64,128,256,512,1024,2048,4096
1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192
1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384
1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768
1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536

```

Different solutions needed stemming from their different order of precedence of something not clearly specified in `POSIX` -

* `mawk`s go ***strictly*** left-to-right, even for assignments,

— so `$_ = ...` is equivalent to `$(func-input-val) = ...`,
* while `gawk/nawk` handles all of RHS first, with LHS taking on final value of `_`

To make nesting sublists out of that :

```
 for __ in $(jot 7); do

    echo " $__ :: $( echo "$__"  |

       mawk 'function __(_){ORS="]"ORS;return $_=\
             --_?_+=_=__(_):!_}$!__(NF=$(OFS=",["))="["$_'

    )"
 done

 1 :: [1]
 2 :: [1,[2]]
 3 :: [1,[2,[4]]]
 4 :: [1,[2,[4,[8]]]]
 5 :: [1,[2,[4,[8,[16]]]]]
 6 :: [1,[2,[4,[8,[16,[32]]]]]]
 7 :: [1,[2,[4,[8,[16,[32,[64]]]]]]]

```

# Answer
> 1 votes
# Scala, 70 bytes

Try it online!

```
def e(n:Int,i:Int=1):List[Any]={if(n>0)List(i,e(n-1,i*2))else List(i)}

```

# Answer
> 1 votes
# Lua, 59 bytes

```
load"a={1}b=a for i=2,...do b[2]={2^i/2}b=b[2]end return a"

```

Try it online!

Ungolfed version:

```
function f(n)
    a={1}b=a
    for i=2,n do
        b[2]={2^i/2}
        b=b[2]
    end
    return a
end

```

# Answer
> 1 votes
# Haskell, 74 bytes

```
data L=L Int [L] deriving Show
c(a:b)=L a[c b|b/=[]]
f n=c$(2^)<$>[0..n-1]

```

Try it online!

# Answer
> 0 votes
# Wolfram Language (Mathematica), 22 bytes

```
Nest[{1,2#}&,{1},#-1]&

```

Try it online!

-9 bytes from @att

# Answer
> 0 votes
# Thunno 2 `r`, 5 bytes

```
{Ḍ1,æ

```

Try it online!

Port of lyxal's Vyxal answer. Takes input on the stack. This default was +11/-5 at the time of posting (Wayback Machine).

#### Explanation

```
{Ḍ1,æ  # Implicit input
{      # Repeat input no. times:
 Ḍ     #  Double (vectorises)
  1,   #  Pair with 1
    æ  #  Only keep non-zero
       # Implicit output

```

# Answer
> 0 votes
# Haskell, 64 bytes

```
data L=L Int[L]deriving Show
m!1=L m[]
m!n=L m[(m*2)!(n-1)]
(1!)

```

Attempt This Online!

Based on Roman Czyborra's answer. I'm using the same output format, which doesn't feel correct because there's an extra empty list…

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


title: Approximate my atomic weight

text:
# Question
Title: Approximate my atomic weight
Each element on the periodic table of the elements has an atomic weight. For example, boron (element 5) has an atomic weight of 10.81. Your challenge is to write a program which takes as input the atomic number of an element and outputs its atomic weight.

Your program only needs to support elements up to and including element 118 (oganesson), the current (as of December 2022) highest known element.

Your score is calculated using the formula:

\\$(1+b)\times(1+m)\\$

where \\$b\\$ is your program's length in bytes and \\$m\\$ is the mean-squared error of your estimates.

## List of weights

These are the weights your program must output for a given atomic number. If I input `1` I should get `1.0079`, `2` should give me `4.0026`, etc.

```
1.0079
4.0026
6.941
9.0122
10.811
12.0107
14.0067
15.9994
18.9984
20.1797
22.9897
24.305
26.9815
28.0855
30.9738
32.065
35.453
39.948
39.0983
40.078
44.9559
47.867
50.9415
51.9961
54.938
55.845
58.9332
58.6934
63.546
65.39
69.723
72.64
74.9216
78.96
79.904
83.8
85.4678
87.62
88.9059
91.224
92.9064
95.94
98
101.07
102.9055
106.42
107.8682
112.411
114.818
118.71
121.76
127.6
126.9045
131.293
132.9055
137.327
138.9055
140.116
140.9077
144.24
145
150.36
151.964
157.25
158.9253
162.5
164.9303
167.259
168.9342
173.04
174.967
178.49
180.9479
183.84
186.207
190.23
192.217
195.078
196.9665
200.59
204.3833
207.2
208.9804
209
210
222
223
226
227
232.0381
231.0359
238.0289
237
244
243
247
247
251
252
257
258
259
262
261
262
266
264
277
268
281
282
285
286
289
290
293
294
294

```

*The scoring calculation was last updated December 15th 2022 at 5:50 pm UTC. Any answers posted before then use an old version of the scoring calculation, and, while not required, are encouraged to update their scores.*

# Answer
> 12 votes
# Wolfram Language (Mathematica), score \\$(1+29)(1+2.52543) = 105.763\\$

```
#~ElementData~"AtomicWeight"&

```

If the builtin fits…! Doesn't work on tio.run because it requires access to Wolfram's servers or something like that. Gives each output as a quantity-with-units rather than a raw number.

For whatever reason, Mathematica has different ideas about the atomic weights of elements #104–109 than the OP, differing by 6, 8, 3, 6, 7, and 10, respectively. Without those errors, this function's score would be just over 31.

I love the fact that CursorCoercer's answer beats this builtin!

# Answer
> 11 votes
# Nibbles, ~~3~~ 6 bytes (12 nibbles), score ~~118.37~~ 85.62

```
*^^$41-39~

```

```
  ^$41          # input to 41st power
 ^    -39       # get integer value of 39th root
*        ~      # and multiply by 2

```

Mean-square-error = 11.23

---

### Nibbles, 67 bytes (134 nibbles), score 70.26

Uninventive port of MarcMush's 119-byte answer (now improved; see edits): upvote that instead of this. See screenshot here.

```
-/*13$5=$`D16 110123444657688996ac998aabbdbdaaa9b9bacdddddedeccba7a9a89accdbb9a999a999889787876669b1324251404253534659b9e3f5667798ac

```

# Answer
> 10 votes
# Julia, score <sup>~~139~~ ~~129~~</sup> 115.83

\\$ score = (1+97) \cdot (1+0.1820) = 115.8387 \\$

```
x->2.6x-b"$/;GG=_HS_k`TITTklllb`>IIS`VJIHIHH=<=0G$/FI*+0<Hj"[-~x>>1]÷11^(-~x%2)%11*1.5

```

Attempt This Online!

the error of `x->2.6x`, devided by 1.5 and rounded to the nearest integer is comprised between 0 and 10. This allows to store 2 errors in a ASCII character (0-127) like a base-11 number. This way, all errors are less than 0.75, giving a quite good mean squared error (0.18)

**previous answers:**

# Answer
> 9 votes
# Jelly, 3 bytes, score 338.70775620762714

```
5H×

```

Try it online!

Multiplies the input by \\$\frac{5}{2}\\$

# Answer
> 9 votes
# Pyth, score = \\$(1+6) \cdot (1+13.1372) \approx 98.9605\\$

```
y*@Q20

```

Try it online!

Uses the formula \\$ 2\cdot n^{1.05} \\$. Verify the score and compare to the integer divide by two, multiply by 5 (would be 4 bytes in pyth) method on Desmos

### Explanation

```
y*@Q20Q    # Add implicit Q
           # Q = eval(input()) implicitly
y          # 2 times
 *    Q    # Q times
  @Q20     # the 20th root of Q

```

# Answer
> 7 votes
# Python 3, score = \\$(1 + 789) * (1 + 0) = 790\\$

```
lambda n:[1.0079,4.0026,6.941,9.0122,10.811,12.0107,14.0067,15.9994,18.9984,20.1797,22.9897,24.305,26.9815,28.0855,30.9738,32.065,35.453,39.948,39.0983,40.078,44.9559,47.867,50.9415,51.9961,54.938,55.845,58.9332,58.6934,63.546,65.39,69.723,72.64,74.9216,78.96,79.904,83.8,85.4678,87.62,88.9059,91.224,92.9064,95.94,98,101.07,102.9055,106.42,107.8682,112.411,114.818,118.71,121.76,127.6,126.9045,131.293,132.9055,137.327,138.9055,140.116,140.9077,144.24,145,150.36,151.964,157.25,158.9253,162.5,164.9303,167.259,168.9342,173.04,174.967,178.49,180.9479,183.84,186.207,190.23,192.217,195.078,196.9665,200.59,204.3833,207.2,208.9804,209,210,222,223,226,227,232.0381,231.0359,238.0289,237,244,243,247,247,251,252,257,258,259,262,261,262,266,264,277,268,281,282,285,286,289,290,293,294,294][n-1]

```

Try it online!

Prints the exact values.

# Python 3, score = \\$(1 + 16) * (1 + 12.83) \approx 235.18\\$

```
lambda n:2.6*n-8

```

Try it online!

Verify the score here

* **Thanks to MarcMush for cutting down the score from 473 to 237.**
* **Thanks to Neil for cutting down the score from 237 to 235.**

# Answer
> 7 votes
# MATLAB, score 144.247 (from @Neil)

```
@(n)1.6*n^1.1

```

# MATLAB, score 161.092

```
@(n)1.7*n^1.087

```

Using the best fit for \\$a\*n^b\\$.

---

# MATLAB, score 206.683

```
@(n)n.^(0:3)*[5/4;1.77;.0154;-7.77e-5]

```

Using the best fit for \\$a+bn+cn^2+dn^3\\$.

# Answer
> 6 votes
# Vyxal, 776 bytes, score = 0

```
⟨1.0079|4.0026|6.941|9.0122|10.811|12.0107|14.0067|15.9994|18.9984|20.1797|22.9897|24.305|26.9815|28.0855|30.9738|32.065|35.453|39.948|39.0983|40.078|44.9559|47.867|50.9415|51.9961|54.938|55.845|58.9332|58.6934|63.546|65.39|69.723|72.64|74.9216|78.96|79.904|83.8|85.4678|87.62|88.9059|91.224|92.9064|95.94|98|101.07|102.9055|106.42|107.8682|112.411|114.818|118.71|121.76|127.6|126.9045|131.293|132.9055|137.327|138.9055|140.116|140.9077|144.24|145|150.36|151.964|157.25|158.9253|162.5|164.9303|167.259|168.9342|173.04|174.967|178.49|180.9479|183.84|186.207|190.23|192.217|195.078|196.9665|200.59|204.3833|207.2|208.9804|209|210|222|223|226|227|232.0381|231.0359|238.0289|237|244|243|247|247|251|252|257|258|259|262|261|262|266|264|277|268|281|282|285|286|289|290|293|294|294⟩i

```

Try it Online!

Prints the exact average for each element, so each \\$(p\_{el} - w\_{el})\\$ = 0, meaning the fraction sums to `0/118`, and multiplication gives score = 0

The scoring of this answer was correct at 2:27pm 15 Dec 2022 UTC. If by some chance the question has been edited to make the score invalid, I won't be available to change it for another 8 or so hours. Therefore, if the score is invalidated, I'll update this when I can.

# Answer
> 6 votes
# Charcoal, 10 bytes, score 113.33712413095091

```
Ｉ×¹·⁶ＸＮ¹·¹

```

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

```
      Ｎ     Input integer
     Ｘ      Raised to power
       ¹·¹  Literal number `1.1`
 ×          Multiplied by
  ¹·⁶       Literal number `1.6`
Ｉ           Cast to string
            Implicitly print

```

# Answer
> 5 votes
# GolfScript, score = (0 + 1) * (10550.87 + 1) = 10551.87, 0 bytes

Not sure what's wrong

# Answer
> 5 votes
# Perl 5, 179 bytes, score 186

```
sub f{my$s;map$s+=/C|D/?hex:$_,("0x3221223xxxx5-11533xx051532414x12232323243436-142421x1525242224233324232433201Cx15-17-17-1404151x-114-2D-9Dxxx10"=~s/x/13/gr=~/-?./g)[1..pop];$s}

```

Try it online!

...to compute score.

```
sub f {
  my $s;                   #sum
  map $s += /C|D/?hex:$_,  #convert C and D to 12 and 13, one char per int
    (                      #string of closest integer diff between each weight:
      ("0x3221223xxxx5-11533xx051532414x12232323243436-142421x152".
       "5242224233324232433201Cx15-17-17-1404151x-114-2D-9Dxxx10")
      =~ s/x/13/gr         #"13" is frequent, decompress all "x" into "13"
      =~ /-?./g            #split into 118 negative and positive ints,
                           #...one char each with a - in front for negative ints
    )[1..pop];             #sum diffs only up to given input N popped from @_
   $s                      #return sum
}

```

# Answer
> 5 votes
# Pip, 11 bytes, score ≈ 103.034

```
1.6*aE1.1

```

Try It Online!

Score calculation

Better score thanks to @Neil

Blatantly stole the best fit for \\$a∗n^b\\$ from @97.100.97.109's answer, but adapted for a better score. The full list can be calculated here

# Answer
> 5 votes
## Pyt, 9 bytes, score ~141.372

```
37*ᵮ₄₅^2*

```

Port of CursorCoercer's Pyth answer

# Answer
> 4 votes
## Python 3: Length = 16, Error ≈ 12.97, Score ≈ 237.48

A simple linear approximation.

```
lambda x:2.6*x-9

```

# Answer
> 4 votes
# \[Bash + qalc\], 47 bytes, Score 169.036

```
LANG=en qalc -t "atom($1;mass)/u"|sed s/±.*//

```

qalc is a CLI based interface of qalculate!, which allows us to extract certain properties of atoms `atom(...;mass)` will provide us the atomic mass of the n-th element. We divide the result by `u` to get a numeric value without unit (`u`). The result may have an uncertainty, notated by `±...`, so we use `sed` to remove such parts. The decimal separator will depend on your locale. While comma could be disabled by setting an option it is shorter to change the locale in case. `-t` or `--terse` is required to prevent printing of the input query, thus the use of `LANG=en`. If we do not care for portability and assume a decimal point locale we can omit the first 8 bytes. If we do not care about uncertainties printed in the output we can remove the last 13 bytes.

Further if we assume the input has been injected before by `variable q ...` we can directly use `LANG=en qalc -t -f file` to achieve:

# \[qalc\], 14 bytes, 52.824

```
atom(q;mass)/u

```

Note that this method differs somewhat from the given list for some period 7 block d elements, namely Lawrencium-Meitnerium or 103-109. This is because qalculate gives us the usual standard value, which is the mass of most stable known isotope. These elements are incredibly unstable and will decay in at most a few seconds. Thus they do not have some sort of "natural average" atomic weight, as they do not exist in nature. The values given in this list belong to less stable isotopes of these elements. If we adapt the list the score would of course improve drastically to 54.324 or 16.976.

# Answer
> 3 votes
# Japt, 2 bytes, score 101.61232686228814

```
Ñ½

```

Try it

Score calulation

Logically identical to this Jelly answer (and some others), but shockingly 1 byte shorter for a decent score.

Explanation:

`Ñ` and `½` are "shortcuts" in Japt, meaning they get expanded before transpiling. `Ñ` becomes `*2`, while `½` becomes `.5`. As a result, this effectively becomes the program `*2.5`, which mulitplies the input by 2.5.

# Answer
> 3 votes
# Desmos, 27 bytes, score ≈ 149.312

```
f(x)=211sin(.0132x-.87)+162

```

Try it on Desmos! A sine wave solution, created by optimizing the following regression:

```
asin([1...118]b+c)+d~[1.0079,4.0026,6.941,9.0122,10.811,12.0107,14.0067,15.9994,18.9984,20.1797,22.9897,24.305,26.9815,28.0855,30.9738,32.065,35.453,39.948,39.0983,40.078,44.9559,47.867,50.9415,51.9961,54.938,55.845,58.9332,58.6934,63.546,65.39,69.723,72.64,74.9216,78.96,79.904,83.8,85.4678,87.62,88.9059,91.224,92.9064,95.94,98,101.07,102.9055,106.42,107.8682,112.411,114.818,118.71,121.76,127.6,126.9045,131.293,132.9055,137.327,138.9055,140.116,140.9077,144.24,145,150.36,151.964,157.25,158.9253,162.5,164.9303,167.259,168.9342,173.04,174.967,178.49,180.9479,183.84,186.207,190.23,192.217,195.078,196.9665,200.59,204.3833,207.2,208.9804,209,210,222,223,226,227,232.0381,231.0359,238.0289,237,244,243,247,247,251,252,257,258,259,262,261,262,266,264,277,268,281,282,285,286,289,290,293,294,294][1...118]

```

The regression yields values of `211.205`, `0.0131883`, `-0.871366`, and `162.758` for `a`, `b`, `c`, and `d`, respectively.

---
Tags: code-challenge, approximation
---


title: Magic OEIS formulae (Robbers' thread)

text:
# Question
Title: Magic OEIS formulae (Robbers' thread)
This is the robbers' thread. See the cops' thread here.

In this cops and robbers challenge, the cops will be tasked with writing an algorithm that computes some function of their choice, while the robbers will try to come up with their algorithm. The catch is, the 'algorithm' must be a *single* closed-form mathematical expression. Remarkably, a function that determines whether a number is prime has been shown to be possible using only Python operators.

## Robbers

Your goal as the robber is to crack the cops' submissions. To begin, pick any submission from the cops' thread that isn't marked as *safe* and is less than a week old. The submission should contain an OEIS sequence and a byte count representing the length of the intended expression. To submit a crack, write a single closed-form expression that takes an integer `n`, and provably computes the `n`th term of this sequence. You only need to handle `n` for which the sequence is defined.

In addition, pay attention to the offset of the OEIS sequence. If the offset is `0`, the first term should be evaluated at `n=0`. If the offset is `1`, it should be evaluated at `n=1`.

The specification for the closed-form expression is described in detail in the cops' thread.

Your expression must be **at most twice** the length of their expression to be considered a crack. This is to ensure that you can't crack their submission with an overly long expression. Bonus points if you are able to match or reduce their byte count.

## Scoring

Your score is the number of answers you have cracked, with more cracks being better.

## Example Crack

> ### A000225, 6 bytes, cracks @user's answer
>
> ```
> 2**n-1
>
> ```

# Answer
# A000120, 86 bytes, cracks @xnor's answer

```
4**n**2*2**n/(2*4**n-1)*(4**n**2*2**n/(2*4**n-1)&4**n**2/(4**n-1)*n)>>2*n*n-n-1&2**n-1

```

Try it online!

I was hoping I could do something with \\$v\_2(\binom{2n}{n})\\$, but it was too long because I needed to copy the expression for \\$\binom{2n}{n}\\$ multiple times, so I just used bitwise operators to separate the bits of \\$n\\$, and then using multiplication we can count the number of \\$1\\$s.
> 4 votes

# Answer
# Python 2, 161 bytes

```
(((8**n**2/(8**n-1)**2*(8**n**4/(8**n**2-1)**2)+8**n**4/(8**n-1)*(8**n/2-1-n)&~(8**n**4/(8**n-1)*(8**n/2)))+8**n**4/(8**n-1)>>n*3-1)&8**n**4/(8**n-1))%(8**n-1)+1

```

Try it online!

https://codegolf.stackexchange.com/a/264066/76323
> 4 votes

# Answer
# Python 2, 29 bytes

```
4**(n*-~n)%(16**n+~4**n)%4**n

```

Try it online!

Cracks Command Master's Fibonacci numbers A00045 with `/` banned.
> 4 votes

# Answer
# Python 2, 25 bytes

```
(1<<2*n*n-2)%((4<<2*n)-3)

```

Attempt This Online!

cracks @xnor's powers of 3.
> 3 votes

# Answer
# A007953, 151 bytes, cracks @dingledooper's answer

```
10*n+((10**n*16**n**3/(10*16**n**2-1)*((n*16**n+~n)*16**n**2+1)/(16**n-1)**2+16**n**3/(16**n-1)*(16**n/2+~n)>>4*n-1&16**n**3/(16**n-1))%(4**n-1)-n*n)*9

```

Try it online!

Uses the formula (for \\$d=10\\$) $$s\_{d}(n) = d n-(d-1)\sum\_{k=0}^\infty {\left\lfloor \frac{n}{d^k} \right\rfloor}$$ calculating the sum by counting the numbers which can be formed as \\$a 10^b\\$ with \\$1 \leq a \leq n\\$ and \\$0 \leq b \leq n\\$ and are less than \\$n\\$ (for each particular \\$b\\$, there will be \\$\left\lfloor \frac{n}{10^b} \right\rfloor\\$ such numbers).

At first I tried to calculate it with a smarter approach, by looking at \\$\sum\_{i=0}^n {(10^{2n-1})^i n}\\$ and then reinterpreting it as a base \\$10^{n}\\$ number, but while the even digits sum to the number you want, the odd digits have junk and you can't use bitwise operators to get rid of it since the base isn't a power of two.
> 2 votes

# Answer
# Python 2, 206 bytes

```
(((~16**k)**2-(((8**(4*k<<8*k)/~-8**(4*k<<4*k)*(8**(4*k*(16**k+2))/(~-4096**k)**3)+8**(4*k<<4*k)/~-4096**k*(8**(4*k<<8*k)/~-8**(4*k<<4*k))**3>>8*k-1)&(8**(4*k<<8*k)/~-4096**k))%~-4096**k))*5**~-k>>7*k-1)%10

```

Attempt This Online!

cracks @Command Master's decimals of pi (I think)

Times out at k=3, so I couldn't really test it that much.

It makes an ortho grid and counts points outside a circle of radius R=16\**k with centre just between grid points.

I have no proof but as the error is O(1/R) this should converge faster than 1 digit per step.
> 2 votes

# Answer
# Python 2, 6 bytes, cracks @The Empty String Photographer's answer

`999>>9`

tio
> 1 votes

# Answer
# Python 2, 157 bytes

```
((128**(N*~-(2*10**~-N))/~-128**N*2*(16*128**~-N-100**~-N)+128**(N*-~(2*10**~-N))/(~-128**N)**3*-~128**N)>>7*N-3&128**(N*~-(2*10**~-N))/~-128**N)%~-128**N%10

```

Attempt This Online! cracks @CommandMaster's decimals of \\$\sqrt 2\\$

Updated using a suggestion by @CommandMaster.

Works by counting integer squares below 2,200,20000,2000000,...
> 1 votes

---
Tags: sequence, code-challenge, restricted-source, cops-and-robbers
---


# Question
Title: Output the smallest increasing sequence where each term is coprime to preceding 3 terms
This sequence is defined as

* Starts with 1, 2, 3
* The next element of the sequence is the first number greater than the previous three that is co-prime with each of the previous *3* elements in the sequence.
    + In other words, if the previous 3 elements are `a`, `b`, `c`, then the next is the first integer `n>c` such that `gcd(a,n)=gcd(b,n)=gcd(c,n)=1`.

This sequence on OEIS: OEIS

All elements below 100:

```
1,2,3,5,7,8,9,11,13,14,15,17,19,22,23,25,27,28,29,31,
33,34,35,37,39,41,43,44,45,47,49,52,53,55,57,58,59,61,
63,64,65,67,69,71,73,74,75,77,79,82,83,85,87,88,89,
91,93,94,95,97,99,

```

You can either:

* Take a number as input, then output the Nth element in the sequence. Either 0 or 1 based is fine.
* Take a number as input, then output the first N elements in this sequence.
* Take no input, output the sequence infinitely.

Inspired by a discussion in chat

# Answer
> 12 votes
# Python 3, ~~78~~ 77 bytes

*-1 byte thanks to @Bubbler!*

Prints the 0-indexed `n`-th term of the sequence. Who needs `gcd` anyway?

```
lambda n:sum((v+(t+b''+v+t)*n)[:n])+1
v=b''*3
t=(b''+v[1:]+v[6:])*3

```

Try it online!

If we look at the differences between each term in the sequence, they become periodic after the 7th term, repeating every 125th term. The periodic string is:

```
22112231221122112222112231221122112222112231221122112222112241142112211221122312211221122221122312211221122221122312211221122

```

The code simply attempts to construct this periodic string, plus the non-periodic bit at the beginning. It helps that the string naturally contains a lot of repetition, making compression relatively short.

By the way, the unprintables in ASCII are `41142`, `1122`, and `3` in order of appearance.

# Answer
> 7 votes
# Python, ~~81~~ 79 bytes

```
from math import*
*a,d=1,
while 1:a+=[d][:gcd(prod(a[-3:]),d)<2!=print(d)];d+=1

```

Attempt This Online! Prints the sequence indefinitely.

# Answer
> 6 votes
# K (ngn/k), ~~43~~ 41 bytes

```
{{{y+/1<y(|!\)/x,y}[x*y*z]/z}\[x-3].1+!3}

```

Try it online!

-2 thanks to ovs. The original version had `(|!\|!\)/` for the GCD (because `(|!\)` alternates between `0,gcd` and `gcd,0` in the end). ovs suggested `y(|!\)/` which iterates exactly `y` times, which is valid because:

* at each iteration, `x,y` becomes `y%x,x`, which strictly reduces the minimum of the two until one becomes 0 (except at the first iteration, because `x > y` at that point); the minimum is reduced at least `y-1` times
* the above leaves the possibility that the minimum is reduced by 1 `y-1` times in a row, but it is impossible: after one reduction, the pair becomes `y-1,y`, and after one more, `1,y-1`, which is a reduction of more than 1 if `y >= 4`.

# Answer
> 5 votes
# K (ngn/k), 59 52 bytes

```
{{{~1=(*|(*:)(|!\)/)y,x}[x*y*z](1+)/z+1}\[x-3].1+!3}

```

Try it online!

-7 : peeking at @ovs’s solution suggested obvious golf

# Answer
> 5 votes
# 05AB1E, ~~16~~ ~~14~~ ~~13~~ 12 bytes

```
λ∞+Dλ3.£P¿Ïн

```

-1 byte thanks to *@ovs*.

Outputs the infinite sequence.

Try it online.

**Explanation:**

```
λ         # Start a recursive environment,
          # to output the infinite sequence
          # (which is output implicitly at the end)
          # Implicitly starting with a(0)=1
          # Where every following a(n) is calculated as:
          #  (implicitly push a(n-1))
 ∞        #  Push an infinite positive list: [1,2,3,...]
  +       #  Add the a(n-1) to each: [a(n-1)+1,a(n-1)+2,a(n-1)+3,...]
 D        #  Duplicate this infinite list
  λ       #  Push a list of all items thus far: [a(0),a(1),...,a(n-1)]
   3.£    #  Pop and only leave (up to†) the last three items: [a(n-3),a(n-2),a(n-1)]
      P   #  Take the product of this triplet: a(n-3)*a(n-2)*a(n-1)
       ¿  #  Check the gcd (Greatest Common Divisor) of this product with each value `v`
          #  in the infinite (duplicated) list: gcd(v,a(n-3)*a(n-2)*a(n-1))
  Ï       #  †† Pop both lists, and only leave the values at the truthy††† positions
   н      #  Pop and push the first remaining item of this infinite list

```

Footnotes:

* †: In the first two iterations, `λ` won't contain three items yet, so will be `[1]` or `[1,"2"]` respectively. This won't affect the output though, since it'll calculate \\$2\\$ based on just \\$\[a(0)=1\]\\$ and calculate \\$3\\$ based on \\$\[a(0)=1,a(1)=2\]\\$.
* ††: The outputs are strings (except for the first implicit item) because of the `Ï` builtin. Not sure why it does that tbh. (You could add a `ï` to the footer if you prefer actual integer outputs: Try it online.)
* †††: Only `1` is truthy in 05AB1E, so only the items at which `gcd(v,a(n-3)*a(n-2)*a(n-1))==1` will be kept with `Ï`.

# Answer
> 3 votes
-10 from ovs/emanresu A

-5 from Arnauld

-3 from dingledooper

# JavaScript (V8), 64 bytes

```
for(A=B=C=D=j=1;;)A*B*C%j|D%j--||(j||print((A=B,B=C,C=D)),j=++D)

```

Try it online!

# Answer
> 3 votes
# , 40 bytes

```
{1&(]],_3&{.>:@]^:(3<1#.+./)^:_{:)&1 2 3

```

Try it online!

0 indexed, returns the selected element, though it generates all up to that element under the hood.

# Answer
> 3 votes
# , ~~83~~ 71 bytes

```
a=3:1
repeat if(all(prod(a[1:3])%%2:a|(T=T+1)%%2:a))show((a=c(T,a))[4])

```

Attempt This Online!

# Answer
> 3 votes
# Pyth, 18 bytes

```
#eaYf!-iT>3Y1he|Y0

```

Try it online!

Outputs terms of the sequence indefinitely.

### Explanation

```
                      # implicitly assign Y = []
#                     # repeat until error
               |Y0    #   short circuiting Y or 0
              e       #   last element of
             h        #   plus 1
    f                 #   counting up from this number, find the first element which satisfies lambda T
         >3Y          #     last three elements of Y
       iT             #     map to gcd with T
      -     1         #     remove 1 from this list
     !                #     True if list is empty
  aY                  #   append to Y
 e                    #   print the last element of Y

```

# Answer
> 3 votes
# Julia, ~~84~~ 79 bytes

```
~n=(i=A=1;while length(A)<n;if max(gcd.(last(A,3),i+=1)...)<2;A=[A;i]end;end;A)

```

Attempt This Online!

Given \\$n\\$, returns \\$\[a\_1, a\_2, \ldots, a\_n\]\\$.

The function `last(A,3)` works gracefully for vectors with less than 3 values. Substituting `A=[A;i]` for `push!(A,i)` saves 3 bytes. Incrementing `i` inside a function call saves 2 bytes.

* -4 bytes thanks to MarcMush: replace `i=1;A=[1]` with `i=A=1`
* -1 byte thanks to MarcMush: remove unecessary semicolon

# Answer
> 2 votes
# Charcoal, 36 bytes

```
ＦＮ«≔⊕↨υ⁰θＷ¬⬤…²⊕θ∨﹪θλ﹪Π…⮌υ³λ≦⊕θ⊞υθ»Ｉυ

```

Try it online! Link is to verbose version of code. Outputs the first `n` numbers. Explanation:

```
ＦＮ«

```

Repeat `n` times.

```
≔⊕↨υ⁰θ

```

Start with `1` more than the previous number, or `1` if there were no previous numbers.

```
Ｗ¬⬤…²⊕θ∨﹪θλ﹪Π…⮌υ³λ

```

While a common factor between the candidate number and the product of the last three numbers can be found...

```
≦⊕θ

```

... increment the candidate number.

```
⊞υθ

```

Add the next element to the list.

```
»Ｉυ

```

Output the found elements.

# Answer
> 2 votes
# Arturo, 69 bytes

```
a:@0..3i:5whileø[drop'a 1print a\0while->1<>gcd@[i∏a]->i:i+1'a++i]

```

Try it! (Modified to print the first `n` elements so the playground can actually show the output.)

Prints the sequence indefinitely.

```
    a:@0..3             ; assign [0 1 2 3] to a
    i:5                 ; assign 5 to i
    whileø[             ; start infinite loop
        drop'a 1        ; delete the first element in a
        print a\0       ; print the (new) first element in a
        while->1<>      ; while 1 is not equal to...
        gcd@[i∏a]->     ; ...the gcd of i and the product of a
            i:i+1       ; increment i (without mutation)
        'a++i           ; append i to a
    ]                   ; end loop

```

# Answer
> 2 votes
# Vyxal, 118 bitsv2, 14.75 bytes

```
W£λ¥nġΠṅ;+)T⁺⌐Ḟ

```

Try it Online!

# Answer
> 2 votes
# , 34 bytes

```
($1 2 3,3((]+3<1#.+.)^:_{:)\])^:_~

```

Attempt This Online!

Returns first n terms. Very inefficient because it computes the next term for every 3-window at every iteration.

```
($1 2 3,3((]+3<1#.+.)^:_{:)\])^:_~
(                            )^:_~  repeat (...) on n until it converges,
                                    also giving n as the fixed left arg
                               (after 1 iteration, the value is always a
                                length-n array starting with 1 2 3)
 $1 2 3,3(                )\]  compute the next term for every 3-window,
                               prepend 1 2 3 and make it length n
          (]+3<1#.+.)^:_{:  compute the next term for a window:
          (         )^:_{:  iterate from the 3rd number until convergence:
                  +.        gcd with the 3 preceding terms
           ]+3<1#.          if the sum is >3, increment

```

# , 34 bytes

```
0{(]}.,](]+3<1#.+.)^:_{:)^:[&1 2 3

```

Attempt This Online!

Returns the nth term, 0-indexed. Maintains the next 3 terms in a loop.

```
0{(]}.,](]+3<1#.+.)^:_{:)^:[&1 2 3
0{(                     )^:[&1 2 3  starting from 1 2 3, iterate n times
                                    and extract the first number
       ](]+3<1#.+.)^:_{:            compute the next term
    }.,                             prepend previous two terms
   ]                                ignore n in this function

```

# Answer
> 1 votes
# Haskell, 73 bytes

```
h n|n<4=n
h n=head[x|x<-[h$n-1..],all(\d->gcd d x==1)[h$n-1,h$n-2,h$n-3]]

```

Attempt This Online!

# Answer
> 0 votes
# Raku, 51 bytes

```
1,2,3,{first 1==(*Xgcd$^x,$^y,$^z).all,($z..*)}...*

```

Try it online! This is an expression for the infinite sequence of numbers.

* `1, 2, 3, { ... } ... *` is a lazy sequence starting with 1, 2, and 3, and with successive elements generated by the brace-delimited anonymous function. The function mentions placeholder variables `$^x`, `$^y`, and `$^z`, so it takes the previous three elements of the sequence as arguments.
* `first 1 == (* Xgcd $^x, $^y, $^z).all, ($z .. *)` finds the first number in `$z .. *`--that is, the numbers starting from the last number in the sequence going up to infinity--such that the `gcd` of that number with each of the last three elements in the sequence is 1.

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


title: Vanilla Natural Logarithm Challenge

text:
# Question
Title: Vanilla Natural Logarithm Challenge
There is a challenge for multiplying two numbers so I guess this counts too

Given as input a positive real number `n` compute its natural logarithm.

Your answer should be within \\$10^{-6}\\$ for \\$1 \leq n \leq 10\\$ and within \\$10^{-3}\\$ for \\$0.1 \leq n \leq 100\\$. You don't need to handle numbers outside this range.

See this thread on mathematics.se for various approaches to this problem. Just for inspiration, feel free to use a method not on that page.

Please add builtin answers to the community wiki instead of posting them separately.

## Test Cases

| x | ln(x) |
| --- | --- |
| 0.1 | -2.3025850929940455 |
| 0.25 | -1.3862943611198906 |
| 0.5 | -0.6931471805599453 |
| 0.75 | -0.2876820724517809 |
| 0.9 | -0.10536051565782628 |
| 1.0 | 0.0 |
| 1.3 | 0.26236426446749106 |
| 2 | 0.6931471805599453 |
| 2.718281828459045 | 1.0 |
| 3.141592653589793 | 1.1447298858494002 |
| 4 | 1.3862943611198906 |
| 5 | 1.6094379124341003 |
| 7 | 1.9459101490553132 |
| 10 | 2.302585092994046 |
| 53 | 3.970291913552122 |
| 54.59815003314423 | 4.0 |
| 99 | 4.59511985013459 |

## IO

Standard IO rules apply. Importantly, you may take input as a fraction if you prefer. You may also output as a fraction, which does not need to be fully reduced.

# Answer
# Excel, ~~19~~ 16 bytes

With many thanks to **Dominic van Essen** for the 3-byte save:

```
=1E9*(A1^1E-9-1)

```

*Previous*:

```
=9^9*(A1^(1/9^9)-1)

```

Input in cell `A1`. The choice of `1E9` (i.e. 1000000000) is sufficient for the given test cases and required accuracy.
> 18 votes

# Answer
# Builtins

These answers are in alphabetical order based on programming language.
If your answer is identical to an existing one, please combine them.

## 05AB1E, 4 bytes

```
žr.n

```

Try it online!

## APL (Dyalog Unicode), 1 byte

Try it online!

## Brachylog, 2 bytes

```
*₁

```

Try it online!

## C (gcc) / PARI/GP / Julia polyglot, 3 bytes

```
log

```

Try it online in C (gcc)!
Attempt this online in PARI/GP!
Try it online in Julia!

## CJam, 4 bytes

```
{ml}

```

Try it online!

## Desmos, 2 Bytes

```
ln

```

Try it online!

## Excel, 7 bytes

```
=LN(A1)

```

## Go, 17 bytes

```
import."math"
Log

```

Attempt This Online!

## , 2 bytes

```
^.

```

Attempt This Online!

## J-uby, 9 bytes

```
:log&Math

```

Attempt This Online!

## Java, 9 bytes

```
Math::log

```

Try it online!

## JavaScript (Node.js), 8 bytes

```
Math.log

```

Try it online!

## Jelly, 2 bytes

```
Æl

```

Try it online!

# Julia 1.0, 3 bytes

```
log

```

Try it online!

## MATL, 2 bytes

```
Yl

```

Try it online!

## MATLAB / Octave, 4 bytes

```
@log

```

Try it online!

## Pascal, ≥ 5 bytes

The built‑in function `ln` fulfills the task. Its only parameter needs to be positive. Extended Pascal, ISO standard 10206, allows complex numbers, too.

```
ln(n)         { where `n` is an acceptable numerical expression}

```

## Pyth, 2 bytes

```
.l

```

Try it online!

## Python 3, 20 bytes

```
import math
math.log

```

Try it online!

## Racket

```
(log z)

```

Try it online!

## Rust, 7 bytes

```
f64::ln

```

Attempt This Online!

## Swift, 40 bytes

```
import Darwin;var l={i->Float in log(i)}

```

macOS-only.

## Thunno 2, 2 bytes

```
ÆN

```

Try it online!

## Vyxal, 2 Bytes

```
∆L

```

Try it online!

## Wolfram Language (Mathematica), 3 bytes

```
Log

```

Try it online!
> 12 votes

# Answer
# \>\<\> (Fish), 71 bytes

Trying to solve this in \>\<\> was the original inspiration for this challenge. Posting this now instead of waiting the usual 24 hours to hopefully inspire more esolang submissions.

```

```

Hover over any symbol to see what it does

Try it

Based on the power series \\$\ln(z)=2\sum\_{n=0}^\infty\\,\frac{1}{2n+1}\left(\frac{z-1}{z+1}\right)^{2n+1}\\$ from this answer om math.se. \>\<\> lacks exponentiation so that too must be done with a loop.

The green loop is the big sum while the grey loop raises to the power of 2n+1
> 11 votes

# Answer
# Hexagony, ~~161~~ 122 bytes

```
?.{10''2\}{}u44.\4476'*0&}=..$/:"-+{=&={{/.|"=}{{&={*={&1d000000}{{}240504"-~{&137{:_1&':!@..~<>".){{{=$/_"'\>{={<>(<\&1=/

```

Try it online!

Layed out:

```
       ? . { 1 0 ' '
      2 \ } { } u 4 4
     . \ 4 4 7 6 ' * 0
    & } = . . $ / : " -
   + { = & = { { / . | "
  = } { { & = { * = { & 1
 d 0 0 0 0 0 0 } { { } 2 4
  0 5 0 4 " - ~ { & 1 3 7
   { : _ 1 & ' : ! @ . .
    ~ < > " . ) { { { =
     $ / _ " ' \ > { =
      { < > ( < \ & 1
       = / . . . . .

```

My first go at a Hexagony program. Could probably still be golfed some, but I'm happy to have gotten it to side length 7.

Since there are no floats in Hexagony, input and output are both fixed point \\$\lfloor n\cdot10^7\rfloor\\$.

### The algorithm

(skip to the second paragraph if you don't care how I came up with it or why it works)

The algorithm used to approximate here is one I came up with myself. I'm sure something like it has been done before, but I'll go over how the constraints of Hexagony led me to this particular method. The first useful observation is that all logarithms are the same, at least up to a constant multiple. That is, \\$\log\_a(x)=\frac{\log\_b(x)}{\log\_b(a)}\\$. This is nice because \\$\log\_{10}\\$ is easier to work with when dealing with decimal representations. In fact, it's super easy. We can approxiamte the base ten logarithm just by taking the length of the decimal representation! Unfortunately, on the range \\$\[0.1, 100\]\\$ this give us 4 possible output values. Not quite good enough. We need a way to make our numbers longer, but longer in a very specific way. Firstly, as I mentioned earlier, we can't even enter \\$0.1\\$ into Hexagony, so we pad the lengths and get some necessary input precision by multiplying everything by \\$10^7\\$. Then, we use another simple logarithm observation: \\$\log(x)=\frac{1}{n}\log(x^n)\\$. Which is to say, up to another constant multiple (which was already necessary), we can take our input to any power before taking the logarithm. Great, so we just take the input to some super high power, take the length of the result and multiply it by something. But there's still a problem. While this idea *technically* works, it means that we'd be multiplying and measuring the length of numbers millions of digits long. I'd never be able to verify any test cases. We've successfully made our numbers longer, now we need to make them shorter. So we break the large exponent into steps, and at each step we truncate the input. By looking at how much we truncate each time we can give an approximation for how long we think it would have gotten if it didn't truncate. This approxiamtion becomes our logarithm. So, for the actual algorihtm:

We take the input and keep a running count of how many digits long we think it is. We enter a loop. For each iteration, we square the input and double this running count (since squaring roughly doubles length). We then truncate the input to the first 7 digits, and add the number of digits we took off to our running count. Iterating 24 times gives us more than enough precision. We then take our predicted length, add a constant, multiply by a constant and print it out.

### The agony

So how is this implemented exactly? I'll refer to the memory graph as it is labeled below. as well as the colored paths.

Note that I only use one instruction pointer for this program, which is probably not optimal. We begin on the blue path. This initializes some variables, putting the input in A, `10` in H, `100000000` in I, and `24` on L leaving the memory pointer in L. Then on to the main loop in green. The main loop first uses G and F to square A, then similarly uses E and K to double D. Moving the memory pointer to B, we then use the yellow path to redirect into a sub loop on the orange tiles. This sub loop uses B an C to divide A by 10, compare against I and increment D. Once the input is less than I, We use the red path to traverse back to the main loop, putting the memory pointer back on L and decrementing. L serves as the main loop counter. Once L is 0, we break out of the main loop and on to the purple track. The purple track uses C and J to do the final subtraction and multiplication on the output in D. The final output ends up in J

Visualizations done with hexagony.net.
> 10 votes

# Answer
# Dyalog APL (no builtin), 13 12 bytes

Dyalog does have the builtin , but this way it's more fun :)

```
(⊢-1-÷∘*)⍣=⍨

```

Basically just Newton's method:

$$ x\_{n+1} = x\_n - \frac{f(x\_n)}{f'(x\_n)} $$

where (L is the number we are taking the log of)

$$ f(x) = e^x - L \\ f'(x) = e^x \\ x\_{n+1} = x\_n - \frac{e^{x\_n} - L}{e^{x\_n}} = x\_n - 1 - \frac L {e^{x\_n}} $$

```
(⊢-1-÷∘*)⍣=⍨
           ⍨ ⍝ x_0 is L
         ⍣=   ⍝ repeat Newton's method until x_n and x_n+1 are "equal":
 ⊢-1-         ⍝ x_n - 1 -
     ÷∘*      ⍝ L / e^x_n

 Created with the help of Luminespire at https://vyxal.github.io/Luminespire

```

"Equal" here means

$$ \left|x\_n-x\_{n+1}\right|\leq10^{-14}\max\left(\left|x\_n\right|, \left|x\_{n+1}\right|\right) $$

test cases

| x | ln(x) | builtin ln(x) | steps until convergence |
| --- | --- | --- | --- |
| 0.1 | -2.3025850929940455E0 | -2.3025850929940455 | 8 |
| 0.25 | -1.3862943611198906E0 | -1.3862943611198906 | 7 |
| 0.5 | -6.9314718055994520E-1 | -0.6931471805599453 | 7 |
| 0.75 | -2.8768207245178090E-1 | -0.2876820724517809 | 7 |
| 0.9 | -1.0536051565782634E-1 | -0.10536051565782628 | 7 |
| 1 | 1.1102230246251565E-16 | 0 | 8 |
| 1.3 | 2.6236426446749117E-1 | 0.26236426446749106 | 7 |
| 2 | 6.9314718055994530E-1 | 0.6931471805599453 | 7 |
| 2.718281828459045 | 9.9999999999999990E-1 | 1 | 8 |
| 3.141592653589793 | 1.1447298858494002E0 | 1.1447298858494002 | 8 |
| 4 | 1.3862943611198906E0 | 1.3862943611198906 | 9 |
| 5 | 1.6094379124341003E0 | 1.6094379124341003 | 9 |
| 7 | 1.9459101490553135E0 | 1.9459101490553132 | 11 |
| 10 | 2.3025850929940460E0 | 2.302585092994046 | 14 |
| 53 | 3.9702919135521220E0 | 3.970291913552122 | 55 |
| 54.59815003314423 | 4 | 4 | 57 |
| 99 | 4.5951198501345900E0 | 4.59511985013459 | 100 |

gotta say, ln(1) resulting in 1e-16 is kinda annoying but well within the spec

This is 1 byte less than an implementation of Jos Woolley's, `1e9×¯1+*∘1e¯9`, but probably still has some room to be golfed further.
> 8 votes

# Answer
# , 18 bytes

```
\(x)1e9*(x^1e-9-1)

```

Attempt This Online!

Port of Jos Woolley's Excel answer, using a constant of `1e9` to avoid needing parentheses to express its reciprocal of `1e-9`.
> 7 votes

# Answer
# Minecraft Data Pack via Lectern, 1144 bytes

```
@function a:a
summon bat ~ ~ ~ {Attributes:[{Name:generic.armor}]}
data merge storage  {a:[[9.,-0.9,-0.69,-0.45,-0.26,-0.14,-0.073,-0.038,-0.02,-0.011,-0.0056,-0.0029,-0.0015,-7.6e-4,-3.9e-4,-2.e-4,-1.1e-4,-5.6e-5,-2.9e-5,-1.5e-5,-7.6e-6,-3.9e-6,-2.e-6,-1.1e-6,-5.6e-7],[-1073741824,1073741824,546146222,278783439,140411372,70331752,35347866,18065629,9420929,5157943,2618732,1354293,700005,354538,181900,93273,51298,26115,13523,6995,3544,1819,933,513,261]],Operation:2,UUID:[I;0,0,0,1]}
execute as @e[type=bat] run function a:b
@function a:b
data modify entity @s Attributes[].Base set from storage  i
data modify storage  Amount set from storage  a[0][0]
data modify entity @s Attributes[].Modifiers append from storage :
execute store result score  a run attribute @s generic.armor get
execute if score  a matches 1..29 store result entity @s Attributes[].Modifiers[-1].UUID[] int 1 store result score v a run data get storage  a[1][0]
attribute @s generic.armor modifier remove 0-0-0-0-1
execute if score  a matches 1..29 run scoreboard players operation o a += v a
data remove storage  a[][0]
execute if data storage  a[][] run function a:b

```

The function is `a:a`.

Takes input in data storage `: i`, as a double.

Outputs via a scoreboard `o a`, scaled up by 466320149.

If we cannot assume a clean world with no bats, it's +8 to start with a `kill @e` command. If we mustn't kill the player it's another +10 for `[type=bat]`. If we cannot assume the objective `a` already exists it's +34 for `scoreboard objectives add a dummy`. If we can't assume the value `o` doesn't exist yet it's +29 for `scoreboard players set o a 0`.

Using a variant of binary search, we go over the values in `a`, multiply our value by `1+x` using attributes, and if it's 1 or more we keep the multiplication and add the log of `1/(1+x)` to our answer. Because the log decreases by less than half in each step we get the correct answer.

We start with a multiplication by 10 to deal with the case of \\$0.1\leq x\<1\\$. We only perform the multiplication if the result is less than 30, to prevent the value going over 100. We need to use 30 because `generic.armor` is clamped to it.

Uses the fact that the storage name in Minecraft can be empty, as can the score holder. The scoreboard objective could've been as well, but then `scoreboard players operation o a += v a` wouldn't work because spaces are trimmed at the end of each line.
> 5 votes

# Answer
# Jelly, 8 bytes

```
*İ}’×ʋȷ9

```

Try it online!

Uses the formula \\$\ln(z) \approx 10^9(z^{10^{-9}} - 1)\\$, adapted slightly from Jos Woolley's answer

## How it works

```
*İ}’×ʋȷ9 - Main link. Takes z on the left
      ȷ9 - 10^9
     ʋ   - Last 4 links as a dyad f(z, 10^9):
  }      -   To 10^9:
 İ       -     Take it's reciprocal
*        -   Raise z to the power 10^-9
   ’     -   Decrement
    ×    -   Multiple by 10^9

```

# Jelly, 14 bytes

```
’÷‘*÷ṛɗȷŻḤ‘¤SḤ

```

Try it online!

Uses the series definition $$\ln(z) = 2\sum^\infty\_{n = 0} \frac 1 {2n+1} \left(\frac {z-1} {z+1}\right)^{2n+1}$$

For this series, \\$1000\\$ is more than enough to provide the required accuracy, as pointed out by mousetail for -1 byte!

## How it works

```
’÷‘*÷ṛɗȷŻḤ‘¤SḤ - Main link. Takes z on the left
’              - z-1
  ‘            - z+1
 ÷             - (z-1)/(z+1)
           ¤   - Last links as a nilad:
       ȷ       -   10^4
        Ż      -   [0, 1, 2, ..., 1000]
         Ḥ     -   [0, 2, 4, ..., 2000]
          ‘    -   [1, 3, 5, ..., 2001]
      ɗ         - Last 3 links as a dyad f((z-1)/(z+1), [1, 3, 5, ..., 2001]):
   *            -   [(z-1)/(z+1), (z-1)/(z+1)^3, (z-1)/(z+1)^5, ...]
    ÷ṛ          -   [(z-1)/(z+1), ((z-1)/(z+1)^3)/3, ((z-1)/(z+1)^5)/5, ...]
             S  - Sum
              Ḥ - Unhalve; Double

```
> 4 votes

# Answer
# Python, 85 Bytes

```
f=lambda x:sum(1/y for y in range(9**7,round(x*9**7)+1))if x>1else-f(1/x)if x-1else 0

```
* Thanks to TheThonnu for their 86 byte suggestion, probably borrowing the `9**7` idea from Command Master.
* Thanks to c-- for showing it is 1 byte shorter to not have a k variable.

---

Uses numerical integration.

Try It Online! (I've used the Pypy implementation in the TIO website since it's apparently 4x faster)
> 2 votes

# Answer
# Python 3, 24 bytes

```
lambda x:1e9*(x**1e-9-1)

```

Try it online!

Port of Jos Woolley's Excel answer (and Dominic van Essen's R answer).

Somehow only 4 bytes off the built-in.
> 2 votes

# Answer
# Ruby, 20 bytes

CW because it's literally a copy-and-paste of The Thonnu's Python 3 answer.

```
->n{1e9*(n**1e-9-1)}

```

Attempt This Online!
> 2 votes

# Answer
# Charcoal, 12 bytes

```
Ｉ×Ｘχχ⊖ＸＮＸχ±χ

```

Try it online! Link is to verbose version of code. Explanation: Port of @JosWooley's Excel answer.

```
       Ｎ        Input number
      Ｘ         Raised to power
         χ      Predefined variable `10`
        Ｘ       Raised to power
           χ    Predefined variable `10`
          ±     Negated
     ⊖          Decremented
 ×              Multiplied by
   χ            Predefined variable `10`
  Ｘ             Raised to power
    χ           Predefined variable `10`
Ｉ               Cast to string
                Implicitly print

```

Importing `math.log` from Python costs 11 bytes:

```
Ｉ▷math.logＮ

```

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

# Answer
# Python, 84 bytes

```
def f(x):
 g=i=999;s=1|-(x>1);x=x**s-1
 while i:g=i+x*(i*i/g-(i:=i-1))
 return x*s/g

```

Attempt This Online!

#### Thanks @xnor for -1.

### How?

Evaluates a continued fraction https://en.wikipedia.org/wiki/Euler%27s\_continued\_fraction\_formula
> 2 votes

# Answer
# JavaScript (Node.js), 18 bytes

```
x=>1e9*(x**1e-9-1)

```

Try it online!

Port of Excel answer
> 1 votes

# Answer
# C (gcc), 44 bytes

```
float f(float x){return(pow(x,1e-9)-1)*1e9;}

```

Try it online!

*Port of Jos Woolley's Excel answer*
> 1 votes

# Answer
# BQN, 2 bytes

```
⋆⁼
 ⁼  # The inverse of
⋆   # the function e^x

 Created with the help of Luminespire at https://vyxal.github.io/Luminespire

```

yeah ok this might be cheating :) can mark as community wiki or delete and move to the builtin answer if enough people complain
> 1 votes

# Answer
# Swift 5.6, no imports, 146 bytes

Swift has no `log` or `pow` builtins -- you have to import those from C! Here's a Swift answer that doesn't use any imports:

```
let i:(Float,Int)->_={x,y in(0..<y).reduce(1){n,_ in n*x}}
func l(x:Float)->Float{2*(0...126).reduce(0){$0+i((x-1)/(x+1),2*$1+1)/(.init($1)*2+1)}}

```

SwiftFiddle link with test cases. Uses this method from the linked Math.SE post. 126 is just the magic number needed to get the requisite precision for \\$\ln\left(99\right)\\$.

This works in later versions of Swift, but I'm pinning it to 5.6 in case exponentiation is added in the future. `i` is a handwritten exponentiation function where the exponent must be a positive integer (called `Int` instead of `UInt` to save bytes).
> 1 votes

# Answer
# Python, 130 bytes

```
def f(x):
 x,m=(1/x,-1)if x<1 else(x,1)
 while x>1.03:x,m=x**.5,m<<1
 r=x**.5
 return m*90*(x-1)/(7*x+32*((x+1)*r+2*x)**.5+12*r+7)

```

This algorithm is derived from Carlson's version of Borchard's algorithm, which uses a modified arithmetic-geometric mean. Carlson's version adds Richardson acceleration. See Carlson, B. C. “An Algorithm for Computing Logarithms and Arctangents.” *Mathematics of Computation*, Apr 1972 https://doi.org/10.2307/2005182

My version is essentially two loops of Carlson's, with range reduction. It only uses elementary operations and square roots. Its absolute error is under 5e-14. Here are some error plots:

Try it in SageMathCell
> 1 votes

# Answer
# Itr, 12 bytes

`$x'¿Fäeäx-\-`

online interpreter

check all test-cases

## Explanation

Uses Newtons method starting at `0` to approximate the result.

```
$x            ; store the input in x
  '¿F         ; repeat 191 times (enough for all test-cases)
     äeäx-\-  ; replace top stack value y starting at 0 with
              ; y-(e^y-x)/e^y (step in Newton method)
              ; implicitly print result

```

# Itr, 17 bytes

`$xx>3*i'¿Fäeäx-\-`

Also works for negative (and complex) inputs

`x>3*i` sets the initial value to `3i` if the real part of the input is negative
> 1 votes

---
Tags: code-golf, math, number, floating-point
---


title: Output some reserved words

text:
# Question
Title: Output some reserved words
For a computer language, a reserved word is a word that cannot be used as an identifier, such as the name of a variable, function, or label. For other computer languages, keywords can be considered as the set of the language instructions.

## Challenge

Using your language of choice, write a code in the chosen language that given a number between one and ten, `1<=n<=10`, outputs any `n` reserved words (keywords) of the chosen language.

## Specifics

* If the chosen language is case sensitive the outputted keywords must be also.
* If the chosen language is not case sensitive the outputted keywords can be in any case.
* If the chosen language has less than 10 keywords saying `p`, the code must output all the reserved words for any `n` between `p` and `10`.
* If possible specify in the answer whether you consider operators as keywords or not.

## Possible samples for Java (JDK10)

* `n=1 --> true`
* `n=3 --> try new interface`
* `n=4 --> continue this long break`

## Possible samples for \>\<\>

* `n=1 --> >`
* `n=3 --> > < ^`
* `n=4 --> > < \ /`

## Possible samples for Brain-Flak

* `n=1 --> (`
* `n=3 --> ( ) [ ]`
* `n=9 --> ( ) [ ] { } < >`

## Rules

* The input and output can be given in any convenient format.
* No need to handle **invalid input values**, valid inputs are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an on-line testing environment so other people can try out your code!
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
> 7 votes
# APL (Dyalog Unicode), 9 bytesSBCS

Full program. Prompts stdin for `n` (actually works for the range 0–29). APL keywords are single character symbols, so this prints `n` symbols to stdout.

```
⎕↑156↓⎕AV

```

Try it online!

`⎕AV` the Atomic Vector (i.e. the character set)

`156↓` drop the first 156 elements

`⎕↑` prompt for `n` and take that many elements from the above

# Answer
> 5 votes
# Python 2, 25 bytes

```
lambda n:'=+*/%&^|<>'[:n]

```

An unnamed function accepting an integer in \[1,10\] which returns a string of single-byte binary operators.

**Try it online!**

The operators:

```
=  Assign
+  Addition
*  Multiplication
/  Division
%  Modulo
&  Bitwise-AND
^  Bitwise-XOR
|  Bitwise-OR
<  Less Than?
>  Greater Than?

```

---

### If only actual keywords are allowed: 40 bytes

```
from keyword import*
lambda n:kwlist[:n]

```

An unnamed function accepting an integer in \[1,10\] which returns a list of strings.

**Try it online!**

The code should be quite straightforward - it defines a function taking one argument, `n`, using `lambda n:...` which returns the first `n` (`...[:n]`) of the known keywords using the standard library's `keywords.kwlist` (along with the standard golfing technique of `import*`).

# Answer
> 4 votes
# Java 10, ~~83~~ 72 bytes (keywords)

```
n->"do   if   for  int  new  try  var  byte case char ".substring(0,n*5)

```

Try it online.

**Old 83 bytes answer:**

```
n->java.util.Arrays.copyOf("do if for int new try var byte case char".split(" "),n)

```

Try it online.

**Explanation:**

```
n->                         // Method with integer parameter and String-array return-type
  java.util.Arrays.copyOf(  //  Create a copy of the given array:
    "do if for int new try var byte case char".split(" ")
                            //   The keywords as String-array,
    ,n)                     //   up to and including the given `n`'th array-item

```

List of available keywords for Java 8. Java 10 has the keyword `var` in addition to these.

---

# Java 8+, 30 bytes (operators)

```
n->"+-/*&|^~<>".substring(0,n)

```

Try it online.

# Answer
> 3 votes
# JavaScript (Node.js), 79 61 bytes

```
n=>'true int var for in if new try of do'.split` `.slice(0,n)

```

Try it online!

# How :

```
n =>         // the input (will be an integer) between 1 and 10 (both inclusive)
    '        // beginning our string
        true int var for in if new try of do'. // space separated reserved words
    split` `.        // turn it into an array every time there is a space we add to array
    slice(0,n)      // return elements of array starting from 0 and upto n

```

If using operators is allowed (most likely will be since they are reserved words) then :

# JavaScript (Node.js), 26 25 bytes

```
n=>'|/^%+<&*-='.slice(-n)

```

Try it online!

Saved 8 bytes thanks to *@Adam* and 1 more byte thanks to *@l4m2*

# How :

```
n =>     // input (integer from 0-9 inclusive)
    '|/^%+<&*-='.    // operators make a shorter string
        slice(-n)   // outputs string chars from last upto n
            // this works since all operators are single chars and not multi chars.

```

# Answer
> 3 votes
# Ruby, 22 bytes

```
->n{'+-*/%&|^<>'[0,n]}

```

Try it online!

-2 bytes thanks to *@benj2240*

# Answer
> 3 votes
# Jelly, 3 bytes

```
ØAḣ

```

A monadic link accepting an integer and returning a list of characters.

**Try it online!**

The resulting characters are all monadic atoms in Jelly's code-page:

```
A   Absolute value.
B   Convert from integer to binary.
C   Complement; compute 1 − z.
D   Convert from integer to decimal.
E   Check if all elements of z are equal.
F   Flatten list.
G   Attempt to format z as a grid.
H   Halve; compute z ÷ 2.
I   Increments; compute the differences of consecutive elements of z.
J   Returns [1 … len(z)].

```

### How?

```
ØAḣ - Link: integer n (in [1,10])
ØA  - yield uppercase alphabet = ['A','B','C',...,'Z']
  ḣ - head to index n

```

# Answer
> 3 votes
# Charcoal, 16 bytes

```
✂”yＰＢＧ¤Ｔ⎚Ｍ↶↷Ｊ”⁰Ｎ

```

Too bad there isn't a preset variable for its own code-page in Charcoal.

Try it online.

**Explanation:**

Get a substring from index 0 to the input-number:

```
Slice("...",0,InputNumber)
✂”y...”⁰Ｎ

```

The string with 10 keywords:

```
”yＰＢＧ¤Ｔ⎚Ｍ↶↷Ｊ”

```

# Answer
> 3 votes
# Perl 5 `-lp`, 24 bytes

```
#!/usr/bin/perl -lp
$_=(grep!eval,a..zz)[$_]

```

Try it online!

Easy to extend to more and longer keywords, but you will need to do special casing starting at 4 letters because you will run into problems with `dump`, `eval`, `exit`,`getc` etc..

Of course just outputting operators and sigils is boring but shorter at 11 bytes:

```
#!/usr/bin/perl -lp
$_=chr$_+35

```

Try it online!

(I skipped `#` since it's unclear how I should classify it in the context of this challenge)

# Answer
> 2 votes
# Brain-Flak, ~~122~~ 120 bytes

```
({}<((((((((((((((()()){}()){}){}){})())[][]){}())()())[(([][]){}){}()])()())){}())[()()])>){({}<{({}<>)(<>)}{}>[()])}<>

```

Try it online!

Just doing my part to fill out the example languages. Outputs `()[]<>}{`, popping off the front for numbers less than 8.

# Answer
> 2 votes
# C# .NET, ~~76~~ 62 bytes (keywords)

```
n=>"as  do  if  in  is  for int new out ref ".Substring(0,n*4)

```

Try it online.

**Old 76 bytes answer:**

```
using System.Linq;n=>"as do if in is for int new out ref".Split(' ').Take(n)

```

Try it online.

**Explanation:**

```
using System.Linq;  // Required import for Take
n=>                 // Method with integer parameter and IEnumerable<string> return-type
  "as do if in is for int new out ref".Split(' ')
                    //  The keywords as string-array,
  .Take(n)          //  and return the first `n` items

```

List of available keywords in C# .NET.

---

# C# .NET, 30 bytes (operators)

```
n=>"+-/*&|^~<>".Substring(0,n)

```

Try it online.

# Answer
> 2 votes
# Pyth, 4 bytes

```
>QPG

```

Try it online!

Unfortunately, many of the letters are variables (`GHJKNQTYZbdkz`).

```
p  <any>                  Print A, with no trailing newline. Return A.
q  <any> <any>            A == B
r  <str> 0                A.lower()
r  <str> 1                A.upper()
r  <str> 2                A.swapcase()
r  <str> 3                A.title()
r  <str> 4                A.capitalize()
r  <str> 5                string.capwords(A)
r  <str> 6                A.strip() - Remove whitespace on both sides of A.
r  <str> 7                Split A, eval each part.
r  <seq> 8                Run length encode A. Output format [[3, 'a'], [2, 'b'], [1, 'c'], [1, 'd']].
r  <str> 9                Run length decode A. Input format '3a2bcd' -> 'aaabbcd'
r  <seq> 9                Run length decode A. Input format [[3, 'a'], [2, 'b'], [1, 'c'], [1, 'd']].
r  <int> <int>            Range, half inclusive. range(A, B) in Python, or range(A, B, -1).
r  <str> <str>            String range. r(C(A), C(B)), then convert each int to string using C.
r  <int> <seq>            r(B, A)
s  <col(str)>             Concatenate. ''.join(A)
s  <col>                  reduce on +, base case []. (Pyth +)
s  <cmp>                  Real part. A.real in Python.
s  <num>                  Floor to int. int(A) in Python.
s  <str>                  Parse as int. "" parses to 0. int(A) in Python.
t  <num>                  A - 1.
t  <seq>                  Tail. A[1:] in Python.
u  <l:GH> <seq/num> <any> Reduce B from left to right, with function A(_, _) and C as starting value. G, H -> N, T ->. A takes current value, next element of B as inputs. Note that A can ignore either input.
u  <l:GH> <any> <none>    Apply A(_, _) until a result that has occurred before is found. Starting value B. A takes current value, iteration number as inputs.
v  <str>                  Eval. eval(A) without -s, ast.literal_eval(A) with -s (online). literal_eval only allows numeric, string, list, etc. literals, no variables or functions.
w                         Take input. Reads up to newline. input() in Python 3.
x  <int> <int>            Bitwise XOR. A ^ B in Python.
x  <lst> <any>            First occurrence. Return the index of the first element of A equal to B, or -1 if none exists.
x  <str> <str>            First occurrence. Return the index of the first substring of A equal to B, or -1 if none exists.
x  <non-lst> <lst>        All occurrences. Returns a list of the indexes of elements of B that equal A.
x  <str> <non-lst>        First occurence. Return the index of the first substring of A equal to str(B), or -1 if none exists.
y  <seq>                  Powerset. All subsets of A, ordered by length.
y  <num>                  A * 2.

```

# Answer
> 2 votes
# Unary, ~~6072204020736072426436~~ 378380483266268 bytes

```
+[>+<+++++]>---. (0o12602122222703334)

```

Thank Jo King for 99.999993768646738908474177860631% reducing

# Answer
> 2 votes
# Charm, 52 bytes

This outputs *all* of the reserved words in Charm.

```
" [  := :: \"   " 0 2 copyfrom 3 * substring pstring

```

Since all non-recursive code in Charm is inline-able, this is an anonymous function. Call like this:

```
4 " [  := :: \"   " 0 2 copyfrom 3 * substring pstring

```

(outputs `[ := :: "`, the only four reserved words.)

---

Giving this function a name adds 5 bytes:

```
f := " [  := :: \"   " 0 2 copyfrom 3 * substring pstring

```

# Answer
> 2 votes
# Japt, 3 bytes

Returns a string, with each individual character being a method name in Japt.

```
;îC

```

Try it

`;C` is the lowercase alphabet and `î` repeats it until its length equals the input.

# Answer
> 2 votes
# , ~~76~~ ~~62~~ ~~60~~ 57 bytes

*12 bytes saved thanks to MickyT*

*5 bytes saved thanks to snoram*

```
cat(c("if","in",1:0/0,"for",F,T,"NULL","else")[1:scan()])

```

Try it online!

There aren't many Reserved words in R but these are among the shortest to encode. There are only 9 here, but if an input of `10` is given, a missing value `NA` is appended to the end of the list and printed.

# Answer
> 2 votes
# Ruby, ~~50~~ 49 bytes

```
->n{%w[do if or in end not for def nil and][0,n]}

```

Try it online!

Not using any operators (`+`, `|`, etc.).

# Answer
> 2 votes
# Ruby, ~~71~~ 68 bytes

```
->n{(?a..'zzz').reject{|x|begin;eval x+'=n';rescue Object;end}[0,n]}

```

Okay, not the shortest approach, but too fun not to post. Programmatically finds all strings of up to three lowercase letters that can't be assigned to. There happen to be exactly 10: `["do", "if", "in", "or", "and", "def", "end", "for", "nil", "not"]`.

Edit: Saved 3 bytes thanks to Asone Tuhid.

# Answer
> 2 votes
# Chicken, 7 bytes

```
chicken

```

Not a serious answer. But it has to be here.

# Answer
> 1 votes
# Python 2, 64 bytes

```
lambda n:'as if def del for try elif else from pass'.split()[:n]

```

Try it online!

---

# Python 2, 57 bytes (with operators)

```
lambda n:'as if in is or and def del for not'.split()[:n]

```

Try it online!

---

keywords
operators

# Answer
> 1 votes
# \>\<\>, ~~11 10~~ 9 bytes

```
1-:n:0=?;

```

Try it online!

Turned out the simplest solution was the best. This outputs the first n numbers, starting from 0.

### Old 10 byte solutions

```
"'r{$[>o<3

```

Try it online!

Some 10 byte alternatives:

* `"':1+{[>o<`
* `"r:n[~>o<a`
* `"'a{[>o<bc`

# Answer
> 1 votes
# Whitespace, 84 bytes

```
[S S S T    S S S S S N
_Push_32][S N
S _Duplicate][T N
S S _Print_as_character][S N
S _Duplicate][T N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve][S S S T  N
_Push_1][T  S S T   _Subtract][S N
S _Duplicate][N
T   S N
_If_0_Jump_to_Label_EXIT][S S S T   S S T   N
_Push_9][T  N
S S Print_as_character][S S S T N
_Push_1][T  S S T   _Subtract][N
T   S N
_If_0_Jump_to_Label_EXIT][S S S T   S T S N
_Push_10][T N
S S _Print_as_character][N
S S N
_Create_Label_EXIT]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Whitespace only contains three valid 'keywords': spaces, tabs and new-lines.

**Explanation in pseudo-code:**

```
Print space
Integer i = STDIN as integer - 1
If i is 0:
  Exit program
Else:
  Print tab
  i = i - 1
  If i is 0:
    Exit program
  Else:
    Print new-line
    Exit program

```

### Example runs:

**Input: `1`**

```
Command       Explanation                 Stack      Heap      STDIN    STDOUT   STDERR

SSSTSSSSSN    Push 32                     [32]
SNS           Duplicate top (32)          [32,32]
TNSS          Print as character          [32]                          <space>
SNS           Duplicate top (32)          [32,32]
TNTT          Read STDIN as integer       [32]       {32:1}    1
TTT           Retrieve                    [1]        {32:1}
SSSTN         Push 1                      [1,1]      {32:1}
TSST          Subtract top two (1-1)      [0]        {32:1}
SNS           Duplicate top (0)           [0,0]      {32:1}
NTSN          If 0: Jump to Label_EXIT    [0]        {32:1}
NSSN          Create Label_EXIT           [0]        {32:1}
                                                                                error

```

Program stops with an error: No exit defined.
Try it online (with raw spaces, tabs and new-lines only).
Outputs a single space.

**Input: `2`**

```
Command       Explanation                 Stack      Heap      STDIN    STDOUT   STDERR

SSSTSSSSSN    Push 32                     [32]
SNS           Duplicate top (32)          [32,32]
TNSS          Print as character          [32]                         <space>
SNS           Duplicate top (32)          [32,32]
TNTT          Read STDIN as integer       [32]       {32:2}    2
TTT           Retrieve                    [2]        {32:2}
SSSTN         Push 1                      [2,1]      {32:2}
TSST          Subtract top two (2-1)      [1]        {32:2}
SNS           Duplicate top (1)           [1,1]      {32:2}
NTSN          If 0: Jump to Label_EXIT    [1]        {32:2}
SSSTSSTN      Push 9                      [1,9]      {32:2}
TNSS          Print as character          [1]        {32:2}             \t
SSSTN         Push 1                      [1,1]      {32:2}
TSST          Subtract top two (1-1)      [0]        {32:2}
NTSN          If 0: Jump to Label_EXIT    []         {32:2}
NSSN          Create Label_EXIT           []         {32:2}
                                                                                error

```

Program stops with an error: No exit defined.
Try it online (with raw spaces, tabs and new-lines only).
Outputs a space, followed by a tab.

**Input: `3` (or higher)**

```
Command       Explanation                 Stack      Heap      STDIN    STDOUT   STDERR

SSSTSSSSSN    Push 32                     [32]
SNS           Duplicate top (32)          [32,32]
TNSS          Print as character          [32]                          <space>
SNS           Duplicate top (32)          [32,32]
TNTT          Read STDIN as integer       [32]       {32:3}    3
TTT           Retrieve                    [3]        {32:3}
SSSTN         Push 1                      [3,1]      {32:3}
TSST          Subtract top two (3-1)      [2]        {32:3}
SNS           Duplicate top (2)           [2,2]      {32:3}
NTSN          If 0: Jump to Label_EXIT    [2]        {32:3}
SSSTSSTN      Push 9                      [2,9]      {32:3}
TNSS          Print as character          [2]        {32:3}             \t
SSSTN         Push 1                      [2,1]      {32:3}
TSST          Subtract top two (2-1)      [1]        {32:3}
SSSTSTSN      Push 10                     [1,10]     {32:3}
TNSS          Print as character          [1]        {32:3}             \n
NSSN          Create Label_EXIT           []         {32:3}
                                                                                error

```

Program stops with an error: No exit defined.
Try it online (with raw spaces, tabs and new-lines only).
Outputs a space, followed by a tab, followed by a new-line.

# Answer
> 1 votes
# Brain-Flak, 118 bytes

```
({}<(((((((((((()()()()()){}){}){})())(([][][])){}{}())()())([][][])[]{})()())[][][][][])()())>){({}<({}<>)<>>[()])}<>

```

Try it online!

```
# Push stuffs under the counter
({}<(((((((((((()()()()()){}){}){})())(([][][])){}{}())()())([][][])[]{})()())[][][][][])()())>)

# While True
{
    # Decrement the counter
    ({}<

        # Toggle a character
        ({}<>)<>
    >[()])
}

# Display alternate stack
<>

```

# Answer
> 1 votes
# Haskell, 22 bytes

```
(`take`"';,=\"@\\`|~")

```

Try it online!

Thanks to @Angs for catching keyword errors.

I felt like this could be shorter by generating the string instead of explicitly defining it, but I couldn't find a range of 10 consecutive ASCII characters that are Haskell keywords (I found some that are close, if you count language extension keywords). If there is one, you could reduce it to 15 bytes with this, replacing `%` with the starting character:

```
(`take`['%'..])

```

---

Without symbolic keywords:

# Haskell, 58 bytes

```
(`take`words"of in do let then else case data type class")

```

Try it online!

# Answer
> 1 votes
# C (gcc), ~~62~~ 60 bytes

-2 thanks to GPS

```
f(n){puts("autocasecharelseenumgotolongvoidint do"+40-4*n);}

```

Try it online!

I mean... there was never any requirement to actually separate the keywords.

In case I misread - or you're more interested in something more in the spirit of the question - here's an alternate version with separating spaces:

# C (gcc), 69 bytes

```
f(n){puts("auto case char else enum goto long void int  do"+50-5*n);}

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 2 bytes

Try it online!

---

Every letter of the alphabet is a command in 05AB1E.

All this does is prints the first `N` letters of the alphabet.

# Answer
> 1 votes
# Tcl, 37 bytes

```
puts [lrange [info commands] 1 $argv]

```

Try it online!

# Answer
> 1 votes
# Taxi, 509 bytes

```
"[]a lrnsew" 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 Post Office.Go to Post Office: s 1 r 1 l 2 r 1 l.Go to The Underground: n 1 r 1 l.Pickup a passenger going to The Underground.Go to Chop Suey: n 2 r 1 l.Switch to plan "a".

```

This takes a hardcoded string at the top, and prints "n" characters from it, and then errors with "error: no outgoing passengers found".

The string contains:

1. `[` and `]`, the characters used to declare a plan
2. `a` used in the "Pickup a passenger ..." syntax.
3. The space character, which is required to separate pieces of syntax
4. `l` and `r`, short for "left" and "right", used to tell the driver which way to turn.
5. `n`, `s`, `e`, and `w`, the four directions.

I believe all of those count as one character keywords. Ungolfed:

```
"[]a lrnsew" 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.
[print character]
Pickup a passenger going to Post Office.
Go to Post Office: south, 1st right, 1st left, 2nd right, 1st left.
Go to The Underground: north, 1st right, 1st left.
Pickup a passenger going to The Underground.
Go to Chop Suey: north, 2nd right, 1st left.
Switch to plan "print character".

```

# Answer
> 1 votes
# , 15 bytes

```
[:u:46,"0~65+i.

```

Try it online!

Gives an array of strings `A.` to `J.`.

Dotted words in J act as built-ins (such as `a.` or `A.`) or control structures (such as `if.` or `do.`), or simply throw spelling error. None of them can be used as identifiers.

## Less interesting, 15 bytes

```
{.&'!#$%^*-+=|'

```

Try it online!

Gives some of the 10 one-byte verbs.

# Answer
> 1 votes
## Bash and shell utils 20 bytes

```
compgen -b|head -$1

```

You can save that in a file with execute permissions (builtins) and run it under bash like this:

```
$ ./builtins 5
 .
 :
 [
 alias
 bg

```

Outputs the first N bash built ins.

If you are running some shell other than bash, you will need the shebang #!/bin/bash line at the start of the file, for +12b

# Answer
> 1 votes
# QBasic, 60 bytes

```
INPUT n
?LEFT$("CLS FOR DEF RUN DIM PUT GET SUB END IF",n*4)

```

This answer fits the spirit of the question best, I believe: outputting alphabetic reserved keywords with spaces in between. I don't think symbolic operators really count as "words" in QBasic, but for completeness, here's a **30-byte answer** using operators:

```
INPUT n
?LEFT$("+-*/\^=><?",n)

```

# Answer
> 1 votes
# MATL, 5 bytes

```
:96+c

```

Try it online!

The lowercase alphabets all correspond to builtins in MATL, so this outputs the first n lowercase letters.

For a version with a smile, there's:

```
2Y2i:)

```

at 6 bytes.

# Answer
> 1 votes
# Julia 0.6, 59 bytes

```
n->split("if do for try let end type else true macro")[1:n]

```

Try it online!

Using the list of reserved keywords from julia-parser.scm.

An operators-included version gets quickly confusing, as to what is an operator and what is a syntactic indicator (like `@` for a macro). Going by julia-parser.scm again, a bunch of operators are termed "syntactic operators" and can't be assigned to or overloaded by the user (so fit the definition of "reserved"). Some of these are:

# Julia 0.6, 45 bytes

```
n->split("= : :: && || ... >: <: -> .=")[1:n]

```

Try it online!

# Answer
> 1 votes
# Cubix, 12 bytes

Based on some of the other answers I think this should qualify for reserved words. I avoided using the numeric literals as I thought that might be stretching the definition a bit far.

```
SoI;W(>!@+/$

```

Try it online!

This wraps onto the cube as follows

```
    S o
    I ;
W ( > ! @ + / $
. . . . . . . .
    . .
    . .

```

Watch it run

* `WSI` change lane, push 32 and get input. This sets up the stack with 32 and the input value.
* `>!@` redirect, test for 0 and halt if true.
* `+/o;` add stack items, reflect onto top face, output character and pop the sum.
* `!/$W(` redundant test, reflect, skip the lane change, decrement the input and back into the main loop.

Output for 10

```
*)('&%$#"!

* multiply the top two items on the stack
) increment the TOS value
( decrement the TOS value
' push the next character's value to the stack
& pop top two items (integers) of the stack, concatenate and push the int result
% take modulo of top two stack items
$ Skip the next command
# push the stack length
" start and end of string literal.  Character codes of string are pushed to the stack
! test for truthy and skip next command if true

```

# Answer
> 0 votes
# Thunno 2 , 4 bytes

```
ıkCɼ

```

Try it online!

#### Explanation

```
ıkCɼ  # Implicit input
ı     # Input no. times:
   ɼ  #  Random character from
 kC   #  Thunno 2 Codepage
      # Join on spaces
      # Implicit output

```

---
Tags: code-golf, string, compression
---