# Question
Title: Sum of a range of a sum of a range of a sum of a range of a sum of a range of a sum of
### Inspired by the fact that a few related challenges to this could be answered by Vyxal in 0 Bytes using a special flag combination.

Given only one input integer \\$n\\$, calculate \\$f(n,n)\\$ where $$ f(x,y)= \begin{cases} x & \text{if } y=0 \\ f(\left(\sum\_{k=1}^xk\right),\text{ }y-1) & \text{otherwise} \end{cases} $$ If you want an explanation in plain English, here it is, quoted from OEIS:

> Let \\$T(n)\\$ be the \\$n\\$-th triangular number \\$n\*(n+1)/2\\$; then \\$a(n)\\$ = \\$n\\$-th iteration \[of\] \\$T(T(T(...(n))))\\$.

Note that a(n) is the function.

---

This is also A099129\\$(n)\\$, but with the case for \\$n=0\\$. This is , so as long as you make your answer short, it doesn't matter whether it times out on TIO (my computer can't calculate \\$n=6\\$ within five minutes!). Yes, standard loopholes apply.

---

## Test cases:

```
0 -> 0
1 -> 1
2 -> 6
3 -> 231
4 -> 1186570
5 -> 347357071281165
6 -> 2076895351339769460477611370186681
7 -> 143892868802856286225154411591351342616163027795335641150249224655238508171

```

# Answer
# 05AB1E, 3 bytes

```
FLO

```

Try it online!

#### Explanation

```
     # Implicit input
F    # Repeat input number of times:
 L   #  Push the one-range of top of stack
  O  #  Sum the resulting list
     # Implicit output

```
> 11 votes

# Answer
# Python 2, 35 bytes

```
def f(n):exec"n=n*-~n/2;"*n;print n

```

Try it online!

A function that prints.

# Python 3, 39 bytes

```
lambda n:eval("(n:=n*-~n//2)*0+"*n+"n")

```

Try it online!

The annoying thing in Python 3 here is that `exec` within a function is its own scope and doesn't affect variables outside the `exec`, so we can't port the code like `def f(n):exec("n=n*-~n/2;"*n);print(n)` -- the `n` will be unchanged.

The code above works around this by evaluating a string like `(n:=n*-~n//2)*0+(n:=n*-~n//2)*0+n` that modifies `n` using the walrus `:=` and evaluates to `n` within its own scope. If we didn't need `n=0`, we could do:

**37 bytes, fails n=0**

```
lambda n:eval("(n:=n*-~n//2),"*n)[-1]

```

Try it online!

Here were some other attempts.

**39 bytes**

```
lambda n:eval('('*n+'n'+'+.5)**2//2'*n)

```

Try it online!

Based on @dingledooper's comment.

**40 bytes**

```
def f(n):exec("n*=n/2+.5;"*n+"print(n)")

```

Try it online!

**41 bytes**

```
lambda n:0*[n:=n*-~n//2for _ in[1]*n]or n

```

Try it online!
> 11 votes

# Answer
# Python 3, 42 bytes

think i might be able to get it down further... lmk if you guys see anything !!

```
lambda x:eval("sum(range("*x+"x"+"+1))"*x)

```

Try it online!
> 10 votes

# Answer
# Jelly, 4 bytes

```
RS$¡

```

Try it online!

Full program, takes \\$n\\$ as the first argument and outputs \\$f(n, n)\\$

## How it works

```
RS$¡ - Main link. Takes n on the left
  $  - Last two links as a monad f(n):
R    -   Range [1, ..., n]
 S   -   Sum; T(n)
   ¡ - Apply f n times, beginning with n

```
> 6 votes

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

```
i::?\~n;
-10.\r:1+*2,r1

```

Try it
> 5 votes

# Answer
# Brainfuck, ~~64~~ 48 bytes

```
[>+>+<<-]>[->[[>+>+<<-]>>-[<<+>>-]<<]>[<+>-]<<]>

```

Try it online! (Up to `n = 3` with 8 bit numbers, `n = 4` with 32 bit, `n = 5` with 64 bit, `n = 6` possibly never \[with BigInt\].)

Rather simple brainfuck answer. Assumes you initialise the tape with the input on cell 0 and stores the output in cell 2. If input given in binary, just wrap the code in `,` and `.` for +2 bytes. If the input should be the number in ASCII this would also involve writing the parser, I feel that is not in the spirit of the challenge.

The input in the first cell (0) is duplicated and then the loop simply iterates on cell 1. Each value of the triangle is added to cell 3 and copied back with 1 removed to cell 2. At the end of the loop that new value is stored in cell 2.

```
Header: give N here
++++

Actual code
[>+>+<<-]          # Duplicate
>[-                # Repeat input times:
  >[                 # While x = n can be decremented
    [>+>+<<-]          # Accumulate result and make copy
    >>-[<<+>>-]<<      # Move copy minus 1 back
  ]>[<+>-]<<         # Move back accumulated T(n) as new x
]>

```
> 5 votes

# Answer
# Python 3, ~~63~~ 62 bytes

```
f=lambda x,y=-1:f(x,x)if y<0else x if y<1else f(x*(x+1)/2,y-1)

```

Try it online!

Calculates a(n) using the OEIS definition given in the OP, probably still golfable

Edit: fixed inputs and added "f="
> 4 votes

# Answer
# Pyth, 6 bytes

```
LsSbyF

```

Try it online!

### Alternative 6 byte solution

```
usSGQQ

```

Try it online!

### Another alternative 6 byte solution

```
.v*"sS

```

Try it online!

This one's my favorite.

### Another alternative 6 byte solution

```
em=sSQ

```

Try it online!

Feels like there's gotta be a 5 byte solution but I got nothing
> 4 votes

# Answer
# Factor \+ `math.unicode`, 26 bytes

```
[ dup [ [1,b] Σ ] times ]

```

Try it online!

Literally just take the sum of the range of the input \<input\> number of times. Since `sum` dispatches on `range`s to use the arithmetic formula, it's even efficient.
> 4 votes

# Answer
# Thunno 2, 3 bytes

```
{RS

```

Attempt This Online!

#### Explanation

```
{RS  # Implicit input
{    # Repeat input number of times:
 R   #  One-range of top of stack (initially the input number)
  S  #  Sum the resulting list and leave it for the next iteration
     # Implicit output

```
> 4 votes

# Answer
# BQN, ~~9~~ 6 bytes

*Edit: -3 bytes thanks to ovs*

```
+´⟜↕⍟⊣

```

Try it at BQN REPL

```
+´⟜↕⍟⊣
     ⍟  # Repeat
      ⊣ # number of times equal to argument
+´⟜↕    # this function:
    ↕   #   range 0..(arg-1)
  ⟜     #   as left arg to
+´      #   fold-addition
        #   with starting value of function arg
        #   (so: sum of 0..arg)

```
> 4 votes

# Answer
# R≥4.1, 33 bytes

```
\(x){Map(\(i)x<<-sum(0:x),1:x);x}

```

Attempt This Online!

R afficionados should wince when they see `Map` used for it's out-of-scope side-effect due to `<<-` assignment, and the result discarded...

# R\<4.1, 42 bytes

```
f=function(x,y=x)`if`(y,f(sum(1:x),y-1),x)

```

Attempt This Online!

Without the short `\` form, it's too expensive to define two `function`s.
> 4 votes

# Answer
# Ruby, 34 bytes

```
f=->x,y=x{y<1?x:f[(1..x).sum,y-1]}

```

Try it online!
> 4 votes

# Answer
# , ~~11~~ 10 bytes

```
(-:*>:)^:]

```

Requires extended precision integer as input. -1 thanks to @Bubbler.

Attempt This Online!

```
(-:*>:)^:]
       ^:   NB. repeat
         ]  NB. y times
    >:      NB. increment
 -:         NB. halve
   *        NB. multiply

```

# , ~~12~~ 11 bytes

```
(-:*>:)^:x:

```

Attempt This Online!

```
(-:*>:)^:]
       ^:    NB. repeat
         x:  NB. y times but promote to extended precision
    >:       NB. increment
 -:          NB. halve
   *         NB. multiply

```
> 4 votes

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

```
f=(x,y=x)=>y?f(x*++x/2,y-1):x

```

Try it online!
> 3 votes

# Answer
# Husk, 5 bytes

```
!→¹¡Σ

```

Try it online!
> 3 votes

# Answer
# Vyxal `R`, 14 bitsv2, 1.75 bytes

```
(∑

```

Try it Online!

Yeah...

```
(   # Input number of times:
 ∑  #  Sum top of stack
    #  (R flag makes it take the range instead of the digits)

```
> 3 votes

# Answer
# Racket – 52 bytes

```
(define(f x y)(if(= y 0)x(f(/(*(+ x 1)x)2)(- y 1))))

```

Try it online!

## Explanation

We `define` a function `f` that receives two arguments: `x` and `y` where `y` is used as decrementing iterator that when equal to zero will make `f` return the result of `x`.

```
(define (f x y)
  (if (= y 0)
      x
      (f (/ (* (+ x 1) x) 2)
         (- y 1))))

```

We can represent this function mathematically using the following:

$$ f(x, y) = \begin{cases} x & y = 0 \\ f(\frac{x(x+1)}{1}, y - 1) & y \> 0 \end{cases} $$

## Sub-optimal variations

To allow user input I could've done:

```
(let([n(read)])(let f([x n][y n])(if(= y 0)x(f(/(*(+ x 1)x)2)(- y 1)))))

```

Which consists of 72 bytes when minified. We could also have used a combination of a lambda and `let` statement to save one byte:

```
((λ(n)(let f([x n][y n])(if(= y 0)x(f(/(*(+ x 1)x)2)(- y 1)))))(read))

```

(The `λ` character equals two bytes.)

## Conclusion

Have an amazing day! I am still mind blown at Racket's speed and capability of handling large numbers. At \\$n = 17\\$, TIO can't seem to render all the digits alongside all iterations of the `for` loop in the footer.
> 3 votes

# Answer
# Charcoal, 13 bytes

```
ＮθＦθ≔Σ…·¹θθＩθ

```

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

```
Ｎθ

```

Input `n`.

```
Ｆθ

```

Repeat `n` times...

```
≔Σ…·¹θθ

```

... replace the current value the sum of its range.

```
Ｉθ

```

Output the final value.

14 bytes for an efficient version:

```
ＮθＦθ≔÷×⊕θθ²θＩθ

```

Try it online! Link is to verbose version of code. Explanation: Uses the triangle formula to sum the range.
> 3 votes

# Answer
# J-uby, 23 bytes

```
~(:-&(:**&(:+|:sum))).D

```

Attempt This Online!

## Explanation

With some whitespace:

```
~(:- & (:** & (:+ | :sum))).D

```

The core function here is `:** & (:+ | :sum)`, where `:+` constructs a range and `:sum` sums it, and `:**` applies that function to its own result `n` times. That does what we want—but only if we call it like `F.(n).(n)`. In order to be able to call it like `F.(n)`, we use `:-` to turn it into `F.(n, n)`, `D` to force `F` to be treated as a dyad, and then `~` to repeat the given argument the necessary number of times (which is two, thanks to `D`).
> 2 votes

# Answer
# MATL, 5 bytes

```
t:":s

```

Try it online!

### How it works

```
t      % Input (implicit). Duplicate
:      % Range
"      % For each
  :    %   Range
  s    %   Sum
       % End (implicit). Display (implicit)

```
> 2 votes

# Answer
# Dyalog APL, 10 bytes

```
{+/⍤⍳⍣⍵⊢⍵}

```

## Explanation

```
   ⍤        ⍝ Function composition:
 +/         ⍝   sum reduce
    ⍳       ⍝   the numbers from 1 to the argument of the composed function
     ⍣⍵     ⍝ repeated input times
       ⊢⍵   ⍝ starting from the input

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

```
> 2 votes

# Answer
# Alice, ~~24~~ 20 bytes

```
/O
\I@/.!wrd&+?t.!$K

```

Try it online!

Times out for larger values as it creates a range from 0 to the sum of the last range.

## Alice, 21 bytes

```
/O
\I@/.!w.h*2:?t.!$K

```

Try it online!

Does not time out as it uses the `n*(n+1)/2` formula instead
> 2 votes

# Answer
# Nekomata, 4 bytes

```
ᵑ{R∑

```

Attempt This Online!

```
ᵑ{R∑
ᵑ{      Repeat
  R     Range
   ∑    Sum

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), 20 bytes

```
Nest[#(#+1)/2&,#,#]&

```

Try it online!

This code simply nests the short-hand expression for the triangular numbers the given number of times. The computation time starts to become noticeable around `n=20` and my laptop takes around 50 seconds to compute `n=27`, which is a number that takes 63.5 MB to store.
> 2 votes

# Answer
# Brachylog, 8 bytes

```
;?{⟦+}ⁱ⁾

```

Try it online!

### Explanation

```
;?{  }ⁱ⁾         Iterate <Input> times on the Input:
   ⟦               Range
    +              Sum

```
> 2 votes

# Answer
# Julia 1.0, ~~33~~ 26 bytes

```
~x=(1:x.|>_->x*=(x+1)/2;x)

```

Try it online!

-7 bytes thanks to MarcMush: replace `for` loop with pipe operator `|>`

## Alternate approach, ~~39~~ 35 bytes

```
~x=x|>∘(fill(n->n*(n+1)÷2,x)...)

```

Attempt This Online!

-4 bytes thanks to MarcMush: remove call to `reduce`
> 2 votes

# Answer
# Haskell, 29 bytes

```
(!!)=<<iterate(\x->sum[0..x])

```

Expands to

```
\n -> iterate (\x -> sum [0..x]) n !! n

```

Try it online!
> 2 votes

# Answer
# x86-64 machine code, 17 bytes

Standard System V ABI, signature `long fsor(int n)` (`n` is taken in `edi`, and the output is placed in `rax`).

```
57 58 50 5e ff c6 48 f7 e6 48 d1 e8 ff cf 7f f2 c3

```

Try it online!

## Explanation

```
0000000000000000 <fsor>:
   0:   57                      push   rdi           ; cnt (edi)
   1:   58                      pop    rax           ; n = cnt
                                                     ;
0000000000000002 <__fsor_lp>:                        ; start_loop:
   2:   50                      push   rax           ;
   3:   5e                      pop    rsi           ; n1 = n
   4:   ff c6                   inc    esi           ; n1++
   6:   48 f7 e6                mul    rsi           ; n *= n1
   9:   48 d1 e8                shr    rax,1         ; n >>= 1
   c:   ff cf                   dec    edi           ; cnt--
   e:   7f f2                   jg     2 <__fsor_lp> ; if (cnt > 0) goto start_loop
  10:   c3                      ret                  ; return

```
> 2 votes

# Answer
# Raku, 25 bytes

```
{($_,{.++*$_/2}...*)[$_]}

```

Try it online!
> 2 votes

# Answer
# ForWhile, 15 bytes

`{:(.0'(+:):)}1$`

same length, but faster (uses formula for sum of first n numbers):

`{:(.::*+2/:)}1$`

online Interpreter

# Explanation

`{ }1$` defines a function, store it at id 1

the argument is read from the stack

`:` duplicate the argument

`(.` loop but ignore the loop counter

`0'(+:)` compute the triangle number corresponding to the top value on the stack

`:)` end of for loop, now the next triangle number is on the stack

returns the result on the stack

Example for how to call the function

```
{:(.0'(+:):)}1$ \ the actual function

4 1@? \ call the function with argument 4

\ print the top stack value as an integer, displaying stack values directly is not supported by this version of the interpreter
0;1+(.;10%"0".+;2+~,1+'10/';)'.(,#)10#.
\ alternatively you can read the stack contents in the browser console from the 'valueStack' variable

```

The interpreter is newer than the challenge, but it implements he same language as the original C interpreter.
> 1 votes

# Answer
# Retina, 18 bytes

```
.+
*
"$+"+`_
$>`
_

```

Try it online! No test suite due to the way the program uses history. Explanation:

```
.+
*

```

Convert `n` to unary.

```
"$+"+`

```

Repeat `n` times.

```
_
$>`

```

Replace the current value with its range, effectively taking the sum.

```
_

```

Convert to decimal.
> 1 votes

# Answer
# MathGolf, ~~6~~ 4 bytes

```
_Å╒Σ

```

Try it online.

**Explanation:**

```
_      # Duplicate the (implicit) input-integer†
 Å     # Pop one, and loop that many of times,
       # using the following two characters as inner code-block:
  ╒    #  Pop an integer, and push a list in the range [1,integer]
   Σ   #  Pop a list, and push its sum
       # (after the loop, the entire stack is output implicitly as result)

```

† The initial duplicate `_` is necessary despite having implicit inputs for two reasons:

1. MathGolf uses `0` if a stack is empty and it needs an integer. Although I think it's a bug in MathGolf (I'm not 100% sure), unfortunately that `0` will take priority over the implicit input-integer in the first iteration of a for-loop. So for any \\$n\>0\\$, just `Å╒Σ` will result in `0` because `Å` will push a 0 in its first iteration and use it for the , instead of using the (implicit) input-integer.
2. For \\$n=0\\$, the `Å╒Σ` will only pop the (implicit) input-integer and leave the stack empty, and thus it'll output an empty string as result. The initial `_` will ensure a second `0` is still on the stack to be output instead.
> 1 votes

# Answer
# Python + `vyxal`, 68 Bytes

```
lambda x:execute_vyxal("","eR"+"s"*x,str(x))
from vyxal.main import*

```

With the power of Python, I can make dynamic flags!\*

The `vyxal` package can be installed using `pip install vyxal`.

---

###### \*Oh wait dynamic flags sound very useful
> 1 votes

# Answer
# sed, 73 bytes

```
s/!*/&''&/g
:a
s/<(!*)''!(!*>)/<'\1'\2/
s/(<!*)'(!*)!/\1\2!'\2/
ta
s/'//g

```

Try it online!

Input is unary, with exclamation marks, surrounded by angle brackets. Output is unary with exclamation marks, surrounded by angle brackets. In the TIO link I made it convert to decimal for the output, so that it's easier to see. If you would like to see the unary output, just delete everything in the footer section.
> 1 votes

# Answer
# Perl 5, 27 bytes

```
$\=$_;$\*=$\++/2while$_--}{

```

Try it online!
> 1 votes

# Answer
# C (gcc), 36 bytes

```
x;a(n){for(x=n;n--;x/=2)x+=x*x;n=x;}

```

Try it online!

Was missing a semicolon, so now it's 36 bytes.
> 1 votes

# Answer
# Desmos, 45 bytes

Input is in a variable `n`. Output is placed in variable `f`.

Start the ticker to run the program. To reset, run the action in the "reset" folder.

**Ticker:**

```
\left\{k<n:f->f(f+1)/2\right\},k->k+1

```

**Expression List:**

```
f=n
k=0

```

Try it on Desmos!

---

**Explaination:**

Applies \\$f\to T(f)\\$ `n` times, using a ticker because Desmos does not support recursion.
> 1 votes

# Answer
# Japt `-h`, 6 bytes

```
õ@=ô x

```

Try it

## 5 bytes

If we could output `undefined` for `0`
(or I could use the `-hF0` flags to output `0` but I *hate* Japt's `-E` & `-F` flags!)

```
Æ=õ x

```

Try it
> 0 votes

# Answer
# Go, 56 bytes

```
func(n int)int{k,i:=n,0
for;i<n;i++{k=k*-^k/2}
return k}

```

Attempt This Online!

Maxes out at `n=5`.

# Go, 138 bytes, `math/big`

```
import."math/big"
func f(n int)*Int{N:=NewInt
k,i,z:=N(int64(n)),0,N(0)
for;i<n;i,z=i+1,N(0){k.Div(z.Mul(k,z.Add(k,N(1))),N(2))}
return k}

```

Attempt This Online!
> 0 votes

# Answer
# Uiua, 9 bytes

```
⍥(/++1⇡).

```

Try it!
> 0 votes

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


title: Jelly compression quine

text:
# Question
Title: Jelly compression quine
The golfing language Jelly has a very complex and clever string compression system which I'm not going to go into depth about here. You can find a very good explanation here.

Basically, Jelly's string literals are represented as `“...»`, where `...` is a string of characters from Jelly's codepage that is decoded into a base-250 integer before being decoded into a string which can contain both words and printable ASCII characters.

Your challenge is to find a string that, when decompressed in Jelly, represents itself. For example, if `xxx` is your string, `“xxx»` must return `xxx` to be valid.

You can test ideas here, or just download Jelly and use the `sss` function.

## Scoring

The shortest submission in bytes (not counting  and `»`) wins. I'll happily accept a proof of impossibility, although it seems unlikely.

I've tested that there are no 1-or-2-byters, but there might still be a trivial one that is a single word.

## Tips, notes and ideas

* Compressing ASCII characters is actually less effective than just using an ordinary string, so with enough, you'll have space to fit an extra word.
* You'll have to use printable ASCII (+ newlines) because nothing decompresses into characters that aren't those.
* There *might* be trivial solutions of 1-2 short words.

The empty string is not a valid solution. The string must be one single string - that is, you can't just escape the string and output it some other way.

# Answer
> 5 votes
## closest so far: `'xC~x9u1'` from `“xC~x9u+»` and `'zC~x9u1'` from `“xC~x9u1»`: 6/7, 85.7%

floor: above 33\*250^9
ceiling: below 129×250^34

update from last time: no matches in 8 or 9 digits; my computer is too slow to find any more near misses. 9 digits alone took around 634 CPU hours (~26 days, split onto 4 cores), checking the same way for 10 digits would take over 6 CPU years on my computer. I recently thought of a new strategy for skipping a large percent of numbers but it means I also skip near misses as well; so any further digits I do will have yet another new definition for near miss. I also haven't figured out if it's guaranteed that it'll hit every match or if it has a chance to skip some, so I'm gonna do some more math before I figure out how to explain it here. if you know how to improve code performance, I'm still putting new iterations of my code as comments at the bottom of the gist linked in the comments, and I would love any suggestions you have. it's still in rust right now; but I have no idea what I'm doing when it comes to optimizations. there were quite a few near misses in the 7 digit range so I am rather disappointed that there were none in 8 or 9; if you spot a bug in my algorithm that'd be cool as well.

no other changes since last time:

no solution yet, but some preliminary results which may be helpful to others.

in the first step of decompression, you divmod by 3 to either select making a character or using one of the dictionaries. if you ignore the dictionary, this means it basically reduces to a base conversion problem where one side is base 1/288: (using the  for when it would touch a dictionary and ¶ for a newline)

```
 ��!��"��#��$��%��&��'��(��)��*��+��,��-��.��/��0��1��2��3��4��5��6��7��8��9��:��;��<��=��>��?��@��A��B��C��D��E��F��G��H��I��J��K��L��M��N��O��P��Q��R��S��T��U��V��W��X��Y��Z��[��\��]��^��_��`��a��b��c��d��e��f��g��h��i��j��k��l��m��n��o��p��q��r��s��t��u��v��w��x��y��z��{��|��}��~��¶��

```

and the other side is bijective base 250:

```
¡¢£¤¥¦©¬®µ½¿€ÆÇÐÑ×ØŒÞßæçðıȷñ÷øœþ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~¶°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥẠḄḌẸḤỊḲḶṂṆỌṚṢṬỤṾẈỴẒȦḂĊḊĖḞĠḢİĿṀṄȮṖṘṠṪẆẊẎŻạḅḍẹḥịḳḷṃṇọṛṣṭ§Äẉỵẓȧḃċḋėḟġḣŀṁṅȯṗṙṡṫẇẋẏż

```

since the symbols have different values from each other I think it's just a matter of coincidence to get the same number to be represented with the same symbols.

what this means is that until one of them out-bases the other, there may be a number that matches somewhere. (after 250^40 \[roughly 8.27e95 or 2^318.7\], base250 will always take more digits and you'd have to use the dictionaries to pad the output; but past ~129x250^34 \[roughly 4.37e83 or 2^277.8\] every base250 number the same length as the corresponding base288 number will start with a digit greater than  so it will never be ascii-only anymore). what I'm calling a 'near miss' in this first section is when an n-1 long string of digits are the same in both bases. this was found with slow python code; but the 'near miss' qualification was different so I'll leave the results in the answer.

near misses at one digit: \[`“/»` = `'0'`(2 off) and `“2»` = `'1'`(1 off)\]
near misses at two digits: \[`“-Ñ»` = `'¶-'`(111 off) jumps to `“/_»` = `' .'`(303 off)\]

```
'"*'   “S*»    8,793
'),'   “[,»   10,545
'0.'   “c.»   12,297
'70'   “k0»   14,049
'>2'   “s2»   15,801
'E4'   “{4»   17,553
'c='   “"=»   25,062
'j?'   “*?»   26,814
'qA'   “2A»   28,566
'xC'   “:C»   30,318
'¶E'   “BE»   32,070
also spotted “y©» = 'yC' which I thought was funny since the c is just circled

```

near misses at three digits: \[`“+B>»` = `'¶B+'`(65 off) jumps to `“+D⁽»` = `' C+'`(349 off)\]

```
'/D,'   “eD,»   3,017,295
';J/'   “*J/»   3,768,798
';Jb'   “;J/»   3,768,849
'G2 '   “EG2»   4,512,783
'G2#'   “FG2»   4,512,786
'G2&'   “GG2»   4,512,789
'G2)'   “HG2»   4,512,792
'G2,'   “IG2»   4,512,795
'G2/'   “JG2»   4,512,798
'G22'   “KG2»   4,512,801
'G25'   “LG2»   4,512,804
'G28'   “MG2»   4,512,807
'G2;'   “NG2»   4,512,810
'G2>'   “OG2»   4,512,813
'G2A'   “PG2»   4,512,816
'G2D'   “QG2»   4,512,819
'G2G'   “RG2»   4,512,822
'G2J'   “SG2»   4,512,825
'G2M'   “TG2»   4,512,828
'G2P'   “UG2»   4,512,831
'G2S'   “VG2»   4,512,834 [ it's so close to ]
'G2V'   “WG2»   4,512,837 [ being an anagram ]
'G2Y'   “XG2»   4,512,840 [ ...just needs to ]
'G2\'   “YG2»   4,512,843 [ shift a tiny bit ]
'G2_'   “ZG2»   4,512,846
'G2b'   “[G2»   4,512,849
'G2e'   “\G2»   4,512,852
'G2h'   “]G2»   4,512,855
'G2k'   “^G2»   4,512,858
'G2n'   “_G2»   4,512,861
'G2q'   “`G2»   4,512,864
'G2t'   “aG2»   4,512,867
'G2w'   “bG2»   4,512,870
'G2z'   “cG2»   4,512,873
'G2}'   “dG2»   4,512,876
'WW6'   “mW6»   5,522,055
'[Y<'   “[Y7»   5,772,561
'c]9'   “2]9»   6,273,558
'¶j@'   “uj@»   8,026,815
'¶j^'   “¶j@»   8,026,845

```

near misses at four digits: \[`“)f⁸ȧ»` = `'¶¶g)'` jumps to `“)i4Ḣ»` = `' h)'`\]

```
'-I;*'   “-I;V»     723,390,087
'`G]5'   “`G]K»   1,520,148,576

```

near misses at five digits: \[didn't calculate crossing point\]

```
'^)L75'   “n^)L7»   435,080,769,306
'f>-A8'   “~f>-A»   497,707,074,066

```

this section is now from much faster rust code; but as is the nature of exponentials it only gets a bit farther. every ascii-only, non-dictionary, number 8 digits or under has now been checked. after some more optimizations, the 8-digit check only took around 4 hours. there's a couple more optimizations I'm going to implement, but then I'm going to start it on 9 digits, which is projected to finish in only 16 days.
if you want to steal the code and run it on your computer as well you can see the gist linked in the comments from @pan. as for how it works: most numbers are either not ascii-jelly or not dictionary-free, meaning once you've built one of the strings and you find out there's a non-ascii somewhere in the other one all the work you spent making those strings is wasted. we start with the jelly side; writing a for loop that runs through the combinatorial product of n ascii digits. we then put it through an if that checks it's a non-dictionary decompressed string. since we now know that all numbers used are valid, we construct both vectors, and it prints it if there's n-1 digits with the same chars in the same indices. (the more optimized version that finished 8 digits in 4 hours is basically the same except it also realizes that most invalid numbers tend to follow each other, so it jumps to the next valid number instead of trying every single invalid number)

```
'"*'        “S*»                        8,793
'),'        “[,»                       10,545
'0.'        “c.»                       12,297
'70'        “k0»                       14,049
'>2'        “s2»                       15,801
'E4'        “{4»                       17,553
'c='        “"=»                       25,062
'j?'        “*?»                       26,814
'qA'        “2A»                       28,566
'xC'        “:C»                       30,318
'¶E'        “BE»                       32,070
2 digits
'/D,'       “eD,»                   3,017,295
'/_,'       “/L,»                   3,024,045
';J/'       “*J/»                   3,768,798
';Jb'       “;J/»                   3,768,849
'WB6'       “WQ6»                   5,516,805
'WW6'       “mW6»                   5,522,055
'[Y<'       “[Y7»                   5,772,561
'c]9'       “2]9»                   6,273,558
'¶%@'       “¶V@»                   8,009,565
'¶j@'       “uj@»                   8,026,815
'¶j^'       “¶j@»                   8,026,845
3 digits
'-I;V'      “-I;*»                723,390,087
'7iw,'      “7Rw,»                881,655,045
'`G]K'      “`G]5»              1,520,148,576
4 digits
')L]<('     “)L]"(»           165,271,515,291
5 digits
6 digits
'"^zHf-%'   “"*zHf-%»   8,638,176,928,324,038
')`K0/-&'   “)`Kh/-&»  10,348,931,331,136,539
'jURA9~/'   “jtRA9~/»  26,237,629,941,156,798
'xC~x9u1'   “xC~x9u+»  29,607,919,863,029,544
'zC~x9u1'   “xC~x9u1»  29,607,919,863,029,550
7 digits
8 digits
9 digits

```

# Answer
> 3 votes
## No solution without the dictionary using at most 9 characters

Using meet-in-the-middle, we can check that there are no solutions without the dictionary using under 9 characters with the following code:

```
import itertools
import tqdm

code_page  = '''¡¢£¤¥¦©¬®µ½¿€ÆÇÐÑ×ØŒÞßæçðıȷñ÷øœþ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~¶'''
code_page += '''°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥẠḄḌẸḤỊḲḶṂṆỌṚṢṬỤṾẈỴẒȦḂĊḊĖḞĠḢİĿṀṄȮṖṘṠṪẆẊẎŻạḅḍẹḥịḳḷṃṇọṛṣṭ§Äẉỵẓȧḃċḋėḟġḣŀṁṅȯṗṙṡṫẇẋẏż«»‘’“”'''

pos = code_page[32:96+32]

rev = {a: 3*(code_page.index(a) - 32) for a in pos}
ver = {a: code_page.find(a) + 1 for a in pos}

n = 9
poss = []
for i in range(n):
    spos = []
    for c in pos:
        spos.append(ver[c] * 250**(n-1-i) - rev[c] * 228**i)
    poss.append(spos)

print(poss)

v1 = {sum(x) for x in tqdm.tqdm(itertools.product(*poss[:n//2]), total=96**(n//2))}

for x in tqdm.tqdm(itertools.product(*poss[n//2:]), total=96**((n+1)//2)):
    if -sum(x) in v1:
        print(x, sum(x))
        exit(0)

```

Projecting from the runtime for 9 characters, running it for 10 characters would either take a lot of memory (128GB might be enough) and a couple of hours, or around 1GB and a few days.

---
Tags: code-golf, quine, compression, jelly
---


title: Maximum pentagon sum

text:
# Question
Title: Maximum pentagon sum
For this problem you are given an \\$n \times n\\$ matrix of integers. The task is to find a pentagon in the matrix with maximum sum. The pentagon must include part (or all) of the x and y axes as two of its sides starting from the top left cell.

All the sides except one must be horizontal or vertical. The remaining side is at 45 degrees ( that is it goes up one for each step to the right).

This picture shows a matrix with a pentagonal part shaded.

Either one or two of the sides can have length zero, as in this example where two zero length sides have turned the pentagon into a triangle. This is an optimal triangular solution for this matrix but may not be an optimal pentagon.

Or this example where one zero-length side has turned a pentagon into a rectangle. This happens to be the optimal rectangle but may not be an optimal pentagon.

```
[[ 3  0  2 -3 -3 -1 -2  1 -1  0]
 [-1  0  0  0 -2 -3 -2  2 -2 -3]
 [ 1  3  3  1  1 -3 -1 -1  3  0]
 [ 0  0 -2  0  2  1  2  2 -1 -1]
 [-1  0  3  1  1  3 -2  0  0 -1]
 [-1 -1  1  2 -3 -2  1 -2  0  0]
 [-3  2  2  3 -2  0 -1 -1  3 -2]
 [-2  0  2  1  2  2  1 -1 -3 -3]
 [-2 -2  1 -3 -2 -1  3  2  3 -3]
 [ 2  3  1 -1  0  1 -1  3 -2 -1]]

```

The winning criterion is asymptotic time complexity. E.g. \\$O(n^2)\\$ time.

# Answer
> 4 votes
# Python, \\$\mathcal O(n^2)\\$

```
def best_pentagon(grid):
    best = float("-inf"), -1, -1, -1
    rects = [0] * len(grid[0])
    pents = [(0, 0)] * len(grid[0])
    for y, row in enumerate(grid):
        line = 0
        lines = [line := line + value for value in row]
        rects = [rect + line for rect, line in zip(rects, lines)]
        pents = [
            max((rect, y), (pent + line, z))
            for rect, (pent, z), line in zip(rects, pents[1:], lines)
        ] + [(rects[-1], y)]
        best = max(best, max((pent, x, y, z) for x, (pent, z) in enumerate(pents)))
    return best

```

Attempt This Online!

Returns a tuple `(sum, x, y, z)` for a pentagon summing to `sum` whose bottom row ends at \\$(x, y)\\$ and whose rightmost column ends at \\$(x + y - z, z)\\$.

### How it works

A pentagon whose bottom row ends at \\$(x, y)\\$ is either

* the rectangle with corner \\$(x, y)\\$, or
* the union of the partial row \\$(0, y)…(x, y)\\$ with a pentagon whose bottom row ends at \\$(x + 1, y - 1)\\$.

This leads to a straightforward dynamic programming solution.

# Answer
> 4 votes
# Python, \\$\mathcal{O}(n^2)\\$ time (optimal)

```
def solve(n, grid):
    # Pad the given grid with zeros to form a right triangle.
    # Note that any pentagonal region in this triangle can be truncated
    # to a valid pentagonal region within the original grid,
    # by stripping away the padded zeros,
    # so if we solve the maximum pentagon problem within this triangle,
    # we get a valid solution for the grid.
    # This is done to simplify coding. It adds some constant factor
    # but doesn't change the overall time complexity.
    triangle = [row[:] for row in grid]
    for r in range(n-1):
        triangle[r] += [0] * (n-1-r)
        triangle.append([0] * (n-1-r))
    m = n * 2 - 1 # size of the triangle

    # Calculate cumulative sums in two directions: rightward and downward.
    right_cumsum = [row[:] for row in triangle]
    down_cumsum = [row[:] for row in triangle]
    for r in range(m):
        for c in range(1, m - r):
            right_cumsum[r][c] += right_cumsum[r][c-1]
    for r in range(1, m):
        for c in range(m - r):
            down_cumsum[r][c] += down_cumsum[r-1][c]

    # We solve the pentagon problem by first forming a large triangle
    # containing the upper left corner, and truncating smaller triangles
    # from the rightmost and downmost ends.
    ans = float('-inf')
    for t in range(1, m+1):
        # From the cumulative sums calculated above, we can get the sums of
        # horizontal strips and vertical strips that form the triangle.
        # The cumulative sum of the horizontal strips gives all possible cutaways
        # from the bottom; that of vertical strips gives those from the right.

        # vertical_strips[k] == sum of k vertical strips from upper right
        # horizontal_strips[k] == sum of k horizontal strips from lower left
        vertical_strips = [0] + [down_cumsum[i][t-1-i] for i in range(t)]
        horizontal_strips = [0] + [right_cumsum[t-1-i][i] for i in range(t)]
        for i in range(1, t+1):
            vertical_strips[i] += vertical_strips[i-1]
            horizontal_strips[i] += horizontal_strips[i-1]
        triangle_sum = horizontal_strips[t]

        # Now, for each possible cutaway from the bottom, we will find the
        # smallest valid cutaway from the right (so we get the maximum sum
        # for the given triangle size and bottom cut size).
        # When k horizontal strips are cut, valid cuts from the right are
        # zero to t-k vertical strips (inclusive).
        # Minimum of these values can be preprocessed in O(m) via cumulative minimum.
        # To make sure that the top left cell is included, k goes up to t-1.
        for i in range(1, t+1):
            vertical_strips[i] = min(vertical_strips[i], vertical_strips[i-1])
        for k in range(0, t):
            cur_area = triangle_sum - horizontal_strips[k]
            max_area = cur_area - vertical_strips[t-k]
            ans = max(ans, max_area)
    return ans

```

Attempt This Online!

This is an art of cumulative operations lol. This is optimal in terms of asymptotic time complexity because you need \\$\mathcal{O}(n^2)\\$ time just to observe all the elements in the matrix.

---
Tags: fastest-algorithm
---


title: Format Datetime in 30-Hour Clock Time

text:
# Question
Title: Format Datetime in 30-Hour Clock Time
Input a datetime, format the datetime in `YYYY-MM-DD HH:mm:ss` format using 30-hour clock time.

The 30-hour clock time works as:

* After 6 a.m., it is same as 24-hour clock time
* Before 6 a.m., it use date for previous day, and plus Hours by 24.

For more examples, you may checkout the testcases.

## Rules

* To simplify the question
    + You may choose to use client timezone or UTC timezone by your prefer;
    + You may assume the client timezone don't have DST;
    + You may assume no leap second.
* This is code-golf.
* Input can be in any convenience format. Although certainly, you cannot take input in 30-hour clock time.
* Output need to be a string, displayed on screen, or other similar replacements with exactly specified format.

## Testcases

```
Input               -> Output
2023-12-01 00:00:00 -> 2023-11-30 24:00:00
2023-12-01 01:23:45 -> 2023-11-30 25:23:45
2023-12-01 05:59:59 -> 2023-11-30 29:59:59
2023-12-01 06:00:00 -> 2023-12-01 06:00:00 or 2023-11-30 30:00:00
2023-12-01 06:00:01 -> 2023-12-01 06:00:01
2023-12-01 12:34:56 -> 2023-12-01 12:34:56
2023-12-01 23:59:59 -> 2023-12-01 23:59:59
2024-01-01 02:00:00 -> 2023-12-31 26:00:00
2024-03-01 00:00:00 -> 2024-02-29 24:00:00

```

# Answer
# Ruby, ~~62 56~~ 48 bytes

```
->d{r="#{d-21600}"[0,19];60000.times{r.succ!};r}

```

Try it online!
> 6 votes

# Answer
# Excel ms365, 71 bytes

Assuming input as normal date-time value in `A1`:

```
=LET(x,MOD(A1,1),y,x<0.25,TEXT(A1-y,"e-mm-dd ")&TEXT(x+y,"[hh]:mm:ss"))

```
> 3 votes

# Answer
# Bash, ~~81~~, ~~89~~, 86 bytes

```
h=$[24+10#${1:11:2}];r=`date -d$1-$[h<30]day +%F\ %T`;((h<30))&&r=${r/ ??/ $h};echo $r

```

Try it online!

# Perl 5 `-MPOSIX=strftime -p`, 99 bytes

```
@a=reverse/\d+/g;$a[5]-=1900;--$a[4];$h=$a[2]+24;--$a[3];$_=strftime("%F %T",@a),s/ ../ $h/ if$h<30

```

Try it online!
> 3 votes

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

```
x=>x.toJSON().replace(/T(..)|\..*/g,(_,x)=>' '+(-x-1006+'').slice(3))

```

Try it online!

Only work in GMT+6

# JavaScript (Node.js), 84 bytes

```
x=>new Date(x+'+6').toJSON().replace(/T(..)|\..*/g,(_,x)=>' '+(-x-1006+'').slice(3))

```

Try it online!

Set GMT+6 in code so work everywhere
> 2 votes

# Answer
# Retina 0.8.2, ~~149~~ 142 bytes

```
T`d`4-9` 0[0-5]
T`d`9d`.0?(-01)* 4
 3
 2
-90-
-12-
((?!00)([02468][048]|[13579][26])(00)?-02)-90
$1-29
02-90
02-28
(0[^469]|10|12)?-90
$1-3$#1

```

Try it online! Link includes test cases. Explanation:

```
T`d`4-9` 0[0-5]

```

Add 44 hours to times between midnight and 6am.

```
T`d`9d`.0?(-01)* 4

```

Subtract 1 day and 10 hours from those times, plus also subtract 1 month and 1 year if the day (and month) were originally 1; in this case the day (and month) "rolls under" to 90 and will be fixed up later to the correct last day or month.

```
 3
 2

```

Subtract another 10 hours from those times.

```
-90-
-12-

```

Change month 90 to December.

```
((?!00)([02468][048]|[13579][26])(00)?-02)-90
$1-29

```

February in a leap year has 29 days.

```
02-99
02-28

```

Other Feburaries have 28 days. (This must be February rather than, say, 2002, because month 90 was fixed up earlier.)

```
(0[^469]|10|12)?-90
$1-3$#1

```

Fix up the last day of the month in other months.
> 2 votes

# Answer
# Factor, 78 bytes

```
[ dup hour>> 6 < [ 1 days time- [ 24 + ] change-hour ] when timestamp>ymdhms ]

```

Attempt This Online!

Takes a timestamp object (in 24-hour time); returns a string.

* `dup hour>> 6 <` is the hour less than six?
* `[ ... ] when` then do `...`
* `1 days time-` subtract one day
* `[ 24 + ] change-hour` add twenty-four hours in a way that doesn't roll the day over
* `timestamp>ymdhms` change the timestamp to a string in the required format
> 2 votes

# Answer
# APL (Dyalog APL), 55 bytes

Anonymous prefix lambda, taking a Dyalog Date Number (number of days since the beginning of 1899-12-31) as argument.

```
{' 1'⎕R' 2'⍣a⊢'T'⎕R' '⊃'%ISO%'(1200⌶)⍵-12÷⍨5×a←1>4×1|⍵}

```

Attempt This Online!

`{``}` "dfn"; argument is :

the argument

`1|` remainder when the divided by 1 (i.e. the fractional part)

four times that

`1>` is 1 greater than that? (i.e. is the time part of the argument before 06:00?)

`a←` store this in `a` (for **a**djust)

five times that

`12÷⍨` that divided by twelve (this gives the number of days to subtract corresponding to subtracting ten hours)

`'%ISO%'(1200⌶)` represent the Dyalog Date Number as an array of ISO 8601 extended format strings (`YYYY-MM-DD"T"hh:mm:ss`)

get the first element of that (since we returned an array of strings)

`'T'⎕R' '`**R**eplace the letter `"T"` with a space (since the ISO format separates date and time with a "T")

…`⍣a⊢` if we need to adjust (`a`):

`' 1'⎕R' 2'`**R**eplace `" 1"` with `" 2"` (to add back the missing 10 hours)
> 2 votes

# Answer
# Bash \+ common linux utils, 66

```
date "-d$1+6" '+%F %H %M:%S'|awk '{printf"%s %02d:%s",$1,$2+6,$3}'

```

Try it online!
> 2 votes

# Answer
# Jelly, 75 bytes

```
ọ4,25>/“ḢȷĠ’b4¤o+28ṙḢ;@,’ḅ’dɗ12‘ʋ
Ṗç/$’3¦ỊṪ$?,+1¦24$}ɗ,<6Ḣ$}?Ṿ¹ŻṖ?$€€j"⁾-:K

```

A full program taking the Y,M,D year as a list of three integers as the first argument and the H,M,S time as a list of three integers as the second argument. Prints a formatted string as a 30-hour time. Most of the code reflects Jelly’s lack of date time handling.
> 1 votes

# Answer
# Charcoal, ~~97~~ 87 bytes

```
¿‹η06«≔Ｉ⪪θ-υ⪫﹪%02dＥυ∨⁻ι¬⊙υ∧›μκ⊖λ⎇⊖κ⁺²⁸∨Ｉ§”)“∧Ｂn»”§υ¹¬﹪⊟Φ↨§υ⁰¦¹⁰⁰μ⁴¦¹²-⁺ ⁺²⁴Ｉ…η²✂η²»«θ η

```

Try it online! Link is to verbose version of code. Takes input as separate "words", i.e. the date and time can be on two lines instead of space-separated. Explanation:

```
¿‹η06«

```

If the time is before 6am, then:

```
≔Ｉ⪪θ-υ

```

Split the date on `-` and cast to integer.

```
⪫﹪%02dＥυ∨⁻ι¬⊙υ∧›μκ⊖λ⎇⊖κ⁺²⁸∨Ｉ§”)“∧Ｂn»”§υ¹¬﹪⊟Φ↨§υ⁰¦¹⁰⁰μ⁴¦¹²-

```

Decrement any component where all the following components are all `1`, but if the component becomes zero, then replace it with `12` if it's the month otherwise calculate the number of days in the previous month. Format and output the resulting date.

```
⁺ ⁺²⁴Ｉ…η²

```

Add 24 to the hours.

```
✂η²

```

Output the minutes and seconds.

```
»«θ η

```

Otherwise just output the date and time.
> 1 votes

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


title: Counting +1 primes

text:
# Question
Title: Counting +1 primes
Define that the natural number **p** is a *+1 prime* of the natural number **n** if **p** is a prime number and the standard binary representation (i.e., without leading zeroes) of **p** can be obtained by adding (i.e., prepending, appending or inserting) a single **1** to the standard binary representation of **n**.

For example, the binary representation of **17** is **100012**. The distinct natural numbers that can be formed by adding a **1** to **100012** are **1100012** or **49**, **1010012** or **41**, **1001012** or **37**, and **1000112** or **35**.

Among these, **41** and **37** are prime numbers, so **17** has two *+1 primes*.

### Task

Write a program or function that accepts a strictly positive integer **n** as input and prints or returns the number of distinct *+1 primes* of **n**.

Input and output must either be an integer, or its decimal or unary string representation.

Standard rules apply.

### Test cases

```
Input:  4
Output: 0

Input:  1
Output: 1

Input:  17
Output: 2

Input:  33
Output: 3

Input:  553
Output: 4

Input:  3273
Output: 5

Input:  4145
Output: 6

Input:  4109
Output: 7

Input:  196869
Output: 8

```

# Answer
> 5 votes
# Pyth, 20 bytes

```
s/LPd{mij\1c.BQ]d2hQ

```

Test Suite

```
s/LPd{mij\1c.BQ]d2hQ
                        Q = eval(input())
      m           hQ    For insertion position in [0 ... Q]
            .BQ         Convert Q to binary string
           c   ]d       Chop at insertion position
        j\1             Join on '1'
       i         2      Convert to integer
     {                  Deduplicate
 /LPd                   Map each number to the number of times it occurs in its
                        prime factorization, e.g. whether or not it is prime.
s                       Sum and print.

```

# Answer
> 8 votes
# JavaScript ES6, 141 bytes ~~143~~ ~~147~~ ~~160~~

*Saves 13 bytes, thanks to @Naouak*

```
n=>[...t=n.toString(2)].map((l,i)=>t.slice(0,v=i+1)+1+t.slice(v)).filter((l,i,a)=>a.indexOf(l)==i&&(p=(n,c)=>n%c&&c>n-2||p(n,++c))('0b'+l,2))

```

Similar method to my TeaScript answer, uses RegExp (you heard me right) to check for primes.

### Ungolfed

```
n=>
   [...t = n.toString(2)]                  // To binary
   .map((l,i)=>                            // Make cycles
               t.slice(0, v = i+1)
               + 1
               + t.slice(v)
   ).filter((l,i,a)=>
                     a.indexOf(l) == i &&  // Remove Duplicates
                     (p=(n,c)=>            // Prime checking
                               n % c &&
                                 c > n - 2 ||
                                 p(n,++c)
                     )('0b'+l,2)
   ).length

```

# Answer
> 4 votes
# TeaScript, 22 bytes

```
x÷¿®x÷E(i¬,1)¤©d¡F(¥)n

```

TeaScript is starting to look like APL... The special characters are converted to longer, commonly repeated sequences

Online interpreter be sure to check "Inputs are numbers."

### Explanation && Ungolfed

```
xT(2)s``m(#P(xT(2)E(i+1,1),2))d()F($P)n

xT(2)      // Take input, convert to binary
s``m(#     // Loop over input

  P(         // Convert to decimal...
     xT(2)     // Input to binary
     E(i+1,1)  // Inset 1 into (above) at current index in loop
  ,2)

)d()       // Remove duplicates
F($P)      // Filter items that aren't prime
n          // Grab length.

```

# Answer
> 4 votes
# Julia, ~~55~~ 52 bytes

```
n->sum(isprime,∪(2n+(k=2.^(0:endof(bin(n))))-n%k))

```

`k=2.^(0:endof(bin(n)))` generates an array containing the powers of 2 from 1 to the highest power less than `n`. `2n+k-n%k` then uses array operations to determine all of the possible "+1 numbers".  (equivalent to `union`, which does the same thing as `unique` in this situation) removes the repeat values. Then `sum(isprime,)` counts the number of primes on the list.

# Answer
> 4 votes
## CJam, 26 bytes

Not a winner, but it beats the existing CJam answers quite solidly and it's the first time I got to use the 0.6.5 command `e\`.

```
1ri2b+_,{_)e\_}%_&{2bmp},,

```

Test it here.

### Explanation

```
1       e# Push a 1 (this is the 1 we'll be inserting everywhere).
ri      e# Read input and convert to integer.
2b      e# Convert to base 2.
+       e# Prepend the 1.
_,      e# Duplicate and get the number of bits N.
{       e# Map this block over i from 0 to N-1...
  _)    e#   Create a copy and increment to i+1.
  e\    e#   Swap the bits at positions i and i+1, moving the 1 one step through the array.
  _     e#   Duplicate so we keep this version on the stack.
}%
_&      e# Remove duplicates via set intersection with itself.
{       e# Filter the remaining digit lists based on this block...
  2b    e#   Convert bits back to an integer.
  mp    e#   Test for primality.
},
,       e# Get the length of the remaining list.

```

One thing worth noting is that we swap the bits at `0` and `1` before making the first copy, so we lose the original array with the `1` prepended to the front. However, the input is always positive, so the leading digit will always be one. That means after prepending another one, the digit list will always start with `[1 1 ...]` so the first swap will be a no-op in any case.

# Answer
> 3 votes
# Julia, ~~110~~ ~~108~~ ~~104~~ 87 bytes

```
n->sum(i->isprime(parse(Int,i,2)),(b=bin(n);∪([b[[1:i;1;i+1:end]]for i=1:endof(b)])))

```

This creates an unnamed function that accepts and integer and returns an integer. To call it, give it a name, e.g. `f=n->...`.

Ungolfed:

```
function f(n::Integer)
    # Get the binary representation of n as a string
    b = bin(n)

    # Construct an array consisting of binary strings with
    # a one prepended, appended, and each insertion
    x = [b[[1:i; 1; i+1:end]] for i = 1:endof(b)]

    # Count the number of primes
    c = sum(i -> isprime(parse(Int, i, 2)), unique(x))

    return c
end

```

Saved 17 bytes thanks to Glen O!

# Answer
> 3 votes
## Minkolang 0.11, ~~54~~ 52 bytes

```
n1(2*d0c`,)(0c1c$%$r2*1c*1c++1g2:d1G)rxSI1-[0g2M+]N.

```

### Explanation

```
n             Get integer from input (let's call it n)
1(       )    Get the smallest power of 2 (say, k) greater than input (starting with 1)
  2*d         Multiply by 2 and duplicate
     0c`,     Copy n and see if it's greater (while loop breaks on 0)

(0c1c$%                       Copy n, copy k, and divmod (pushes n//k, n%k)
       $r                     Swap top two elements
         2*                   Multiply by 2
           1c*                Copy k and multiply
              1c+             Copy k and add
                 +            Add
                  1g2:        Get k and divide by 2
                      d1G)    Duplicate and put one copy back in its former place

rx            Reverse and dump (dumps n and top of stack is now 0)
S             Remove duplicates
I1-[     ]    Check each element for primality
    0g        Get potential prime from bottom of stack
      2M      1 if prime, 0 otherwise
        +     Add (this is why I didn't dump the left-over 0 earlier)
N.            Output as integer and stop.

```

# Answer
> 3 votes
# Mathematica, 87 bytes

```
Union[#~FromDigits~2&/@StringReplaceList[#~IntegerString~2,a_:>a<>"1"]]~Count~_?PrimeQ&

```

# Answer
> 2 votes
# CJam, 58 bytes

```
L{:TQ\=A+Q\+TWe\-2<s:~2b}q~2b0+:Q,(%{:BLe=!{B+:L}&}%~:mp:+

```

This took me a day, and this was my 4th iteration.

# Answer
> 2 votes
# Japt `-x`, ~~14~~ 11 bytes

```
Æ¤iX1Ãâ ®Íj

```

Try it or run all test cases

```
Æ¤iX1Ãâ ®Íj     :Implicit input of integer U
Æ               :Map each X in the range [0,U)
 ¤              :  Convert U to binary string
  iX1           :  Insert "1" at 0-based index X
     Ã          :End map
      â         :Deduplicate
        ®       :Map
         Í      :  Convert to decimal
          j     :  Is prime?
                :Implicit output of array sum

```

# Answer
> 1 votes
## PHP, 145 bytes

I've added a newline for readability:

```
function($n){for($b=base_convert;++$i<=strlen($s=$b($n,10,2));$r+=!$s[$i]&$k<=$j)
for($j=1;($k=$b(substr_replace($s,1,$i,0),2,10))%++$j;);echo$r;}

```

# Answer
> 1 votes
# CJam, 34 bytes

```
li2b_,),\f{_2$<@@>1\++}_&2fb{mp},,

```

Try it online

First version, will update if I come up with something better.

# Answer
> 1 votes
# APL, 55

```
{+/{2=+/0=⍵|⍨⍳⍵}¨∪⍵{2⊥(⍵↑X),1,⍵↓X←⍺⊤⍨N⍴2}¨-1-⍳N←1+⌊2⍟⍵}

```

2 bytes shorter Dyalog-specific version:

```
{+/2=+/¨0=|⍨∘⍳⍨¨∪⍵{2⊥⍵(↑,(1∘,↓))⍺⊤⍨N⍴2}¨-1-⍳N←1+⌊2⍟⍵}

```

# Answer
> 1 votes
## Matlab (120)

```
n=input('');a=dec2bin(n);g=arrayfun(@(x)bin2dec(cat(2,a(1:x),49,a(x+1:end))),1:log2(n));nnz(unique(g(find(isprime(g)))))

```

---

* More golfing in progress ...

# Answer
> 1 votes
# Brachylog, 17 bytes

```
{ḃ~c₂{,1}ʰc~ḃṗ}ᶜ¹

```

Try it online!

Input through the input variable and output through the output variable.

```
{             }ᶜ¹    Count every unique
             ṗ       prime number
           ~ḃ        the binary representation of which is
 ḃ                   the binary representation of the input
  ~c₂                partitioned into two (possibly empty) lists
     {  }ʰ           with the first list
      ,1             having a 1 appended
          c          and the two lists then being concatenated back into one.

```

# Answer
> 1 votes
# Jelly, 13 bytes

```
BLṬkj1ʋ€$QḄẒS

```

Try it online!

# Answer
> 1 votes
# Husk, 20 bytes

```
←#ṗumȯḋJ1`Cḋ¹oSze↔ŀḋ

```

Try it online!

Barely got away with a single byte.

# Husk, 21 bytes

```
#oṗḋumJ1§z§e↑↓oΘŀo¢;ḋ

```

Try it online!

There's probably a much shorter way to do this.

# Answer
> 1 votes
# Husk, ~~18~~ 17 bytes

```
#oṗḋużoJ1eḣḋ¹mtṫḋ

```

Try it online!

Different approach to Razetime's Husk answer, saving ~~2~~ 3 bytes.

**How?**

```
#oṗḋużoJ1eḣḋ¹mtṫḋ
#o                      # how many
  ṗ                     # prime numbers
   ḋ                    # among numbers formed by binary digits of
    u                   # unique elements of
     żo                 # zip together 2 lists of lists,
       J1e              # joining each pair with the digit '1'
          ḣḋ¹           # list 1:
          ḣ             # all prefixes of
           ḋ¹           # binary digits of input
             mtṫḋ       # list 2:
             mt         # remove first element from
               ṫ        # all suffixes of
                ḋ       # binary digits of input

```

# Answer
> 0 votes
# Python 2, 103 bytes

```
lambda n:sum(all(i%j for j in range(2,i))for i in{n%2**i+((n>>i)*2+1<<i)for i in range(len(bin(n))-2)})

```

Try it online!

# Answer
> 0 votes
# Vyxal 3 `s`, 11 bytes

```
bƛ?bm1ỊB}uṄ

```

Try it Online! (link is to literate version)

## Explained

```
'uniquify( to-binary map<
  (input to-binary) 'insert (ctx-m 1)
  from-binary}
)

prime?

```

---
Tags: code-golf, math, primes, binary
---


title: Kolmogorov shifter

text:
# Question
Title: Kolmogorov shifter
Output or display the following three lines of text, exactly as they are shown below. A trailing newline is accepted.

```
 bC#eF&hI)kL,nO/qR2tU5wX8z
A!cD$fG'iJ*lM-oP0rS3uV6xY9
aB"dE%gH(jK+mN.pQ1sT4vW7yZ

```

That block of text is the same as the one below, but where the n'th column is rotated n times downward:

```
 !"#$%&'()*+,-./0123456789
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz

```

Keep in mind that this is a challenge, so the output format is not flexible.

# Answer
# Java 8, ~~169~~ ~~162~~ ~~150~~ ~~146~~ ~~116~~ ~~113~~ ~~106~~ ~~95~~ ~~94~~ ~~93~~ ~~92~~ ~~91~~ ~~90~~ 84 bytes

Yay, we finally did it! We've beat the 88-byte literal output that can be found at the bottom. Thanks to all those who participated in the golfing!

```
v->{for(int i=0,t=0;++i<81;System.out.printf("%c",i%27<1?10:(4-t++%3)*32%97+i%27));}

```

-7 bytes thanks to *@StewieGriffin*.
-42 bytes thanks to *@Neil*.
-11 bytes thanks to *@PeterTaylor*.
-3 bytes thanks to *@OlivierGrégoire*.
-6 bytes thanks to *@OlivierGrégoire* and *@Neil* (Olivier suggested a port of Neil's JavaScript answer).

Try it online.

**Explanation:**

```
v->{                          // Method with empty unused parameter and no return-type
  for(int i=0,t=0;++i<81;     //  Loop from 1 to 81 (exclusive)
     System.out.printf("%c",  //   Print the following character:
      i%27<1?                 //    If it's the last column
       10                     //     Print a new-line
      :                       //    Else:
       (4-t++%3)*32%97+i%27   //     Print the correct character based on the index

```

See here what each of the arithmetic parts do, and how it ends up at the correct characters.

---

# Java 8, 88 bytes

```
v->" bC#eF&hI)kL,nO/qR2tU5wX8z\nA!cD$fG'iJ*lM-oP0rS3uV6xY9\naB\"dE%gH(jK+mN.pQ1sT4vW7yZ"

```

Boring, ~~but utilizing the intended rotation of columns won't be any shorter in Java for sure..~~ I stand corrected! ~~Will post a solution in a moment either way to see how much bytes it differs.~~ Apparently the difference is just **-4 bytes! :D**

Try it online.

---
> 18 votes

# Answer
# Husk, 13 bytes

```
Tzṙṫ26¡m→"Aa

```

Note the trailing space. Try it online!

## Explanation

```
Tzṙṫ26¡m→"Aa   No input.
         "Aa   The string "Aa ".
      ¡        Iterate
       m→      map successor: ["Aa ","Bb!","Cc\"","Dd#",..
 z             Zip with
   ṫ26         the reversed range [26,25,24,..,1]
  ṙ            using rotation: [" Aa","b!B",..,"z9Z"]
               This also truncates the list to length 26.
T              Transpose, implicitly print separated by newlines.

```
> 13 votes

# Answer
# SPL (Shakespeare Programming Language), ~~1679~~ ~~1618~~ 1600 bytes

```
.
Ajax,.
Ford,.
Puck,.
Act I:.
Scene I:.
[Enter Ajax and Ford]
Ajax:
You are the remainder of the quotient between the sum of the remainder of the quotient between the product of me and a fat joy and the sum of the cube of a big red day and the difference between a red fat pig and a big old fat cow and the quotient between me and the sum of a day and the square of the sum of a joy and a big red day and the sum of a cat and a fat son.
[Exit Ajax]
[Enter Puck]
Ford:
Am I as good as nothing? If so, you are a bad big old red fat day. Am I as good as a joy? If so, you are the sum of a joy and a the cube of an old bad day. Am I as good as a big day? If so, you are the sum of the square of the sum of a big red fat cat and an old cow and the sum of an old war and a lie.
[Exit Ford]
[Enter Ajax]
Ajax:
You are the sum of thyself and the remainder of the quotient between me and the sum of a man and the square of the sum of a son and a big fat cow. Speak thy mind!
[Exit Puck]
[Enter Ford]
Ford:
You are the sum of yourself and a son.
Ajax:
You are the remainder of the quotient between me and the sum of a cat and the square of the sum of a cow and an old red sky.
Ford:
Am I as good as nothing? If so, let us proceed to scene III.
Scene II:.
Ajax:
You are the product of the sum of a fat man and a cow and the sum of a man and the square of the sum of a cat and a big red son. Are you not better than me? If so, let us return to act I. Let us proceed to scene IV.
Scene III:.
Ajax:
You are the sum of a big old fat cat and a red cow. Speak thy mind! Let us return to scene II.
Scene IV:.
[Exeunt]

```

I had some issues with the interpreter (https://github.com/drsam94/Spl), so it's not as small as I think it could have been. But at least this works :)

---

Here's the same logic in PHP, to make it a bit easier to see what's going on.

```
<?php

Act1Scene1:
$ford = ((2 * $ajax) % 52 + $ajax / 26) % 3;
if ($ford == 0) {
    $puck = 32;
}
if ($ford == 1) {
    $puck = 65;
}
if ($ford == 2) {
    $puck = 97;
}
$puck = $ajax % 26 + $puck;
echo chr($puck);

$ajax = $ajax + 1;

$ford = $ajax % 26;
if ($ford == 0) {
    goto Act1Scene3;
}

Act1Scene2:
if ($ajax < 78) {
    goto Act1Scene1;
}
goto Act1Scene4;

Act1Scene3:
$ford = 10;
echo chr($ford);
goto Act1Scene2;

Act1Scene4:

```
> 11 votes

# Answer
## JavaScript (ES6), ~~86~~ 75 bytes

```
f=(i=k=0)=>i<80?String.fromCharCode(++i%27?(4-k++%3)*32%97+i%27:10)+f(i):''

```

Edit: Saved 11 bytes thanks to @Ryan. Now 10 bytes shorter than the literal!

## JavaScript (Node.js), 64 bytes

```
f=(i=k=0)=>i<80?Buffer([++i%27?(4-k++%3)*32%97+i%27:10])+f(i):''

```

Try it online! Thanks to @Ryan.
> 10 votes

# Answer
# 05AB1E, ~~17~~ 15 bytes

Saved 2 bytes thanks to *Erik the Outgolfer*

```
žQAuA)øε¼¾GÁ]ø»

```

Try it online!

**Explanation**

```
žQ                 # push the list of printable ascii characters
  Au               # push upper-case alphabet
    A              # push lower-case alphabet
     )ø            # zip
       ε           # apply to each
        ¼          # increment counter
         ¾G        # for N in [1 ... counter] do:
           Á       # rotate string right
            ]      # end loops
             ø     # zip
              »    # print list joined by newlines

```
> 8 votes

# Answer
## CJam (18 bytes)

```
26{_" Aa"f+m>}%zN*

```

Online demo

### Dissection

The obvious approach is to generate the original lines, zip, rotate with `ee::m>`, and zip back. But `ee::` is quite long, and it's shorter to generate the columns directly.

```
26{         e# For i = 0 to 25...
  _" Aa"f+  e#   Generate the unrotated column by offsets from the starting chars
  m>        e#   Rotate the appropriate distance
}%
zN*         e# Zip and join the rows with newlines

```
> 8 votes

# Answer
# Python 2, 72 bytes

```
x=98
exec"r='';exec'r+=chr(x/3);x+=291*(x<180)-94;'*26;print r;x-=78;"*3

```

Try it online!

This works by removing `31.333..` from the previous character, adding `97` when the previous codepoint is less than 60, and subtracting `26` at the end of each line.
> 8 votes

# Answer
# , ~~64~~ 63 bytes

```
cat(intToUtf8(c(32:57,10,65:90,10,97:122,10)[(0:80*55)%%81+1]))

```

Try it online!

-1 byte thanks to Giuseppe

I arrived at this through quite a bit of trial and error, so I'm struggling with a concise explanation. Essentially, instead of the character codes, I started off with a more simple sequence of 1:81 representing the original block of text (3\*26 plus 3 newlines), and examined the indices of where these values end up in the rotated block. This follows a regular sequence that drops by 26 each time, modulo 81 (or equivalently, increases by 55 mod 81). It was then a matter of recreating that sequence `(0:80*55)%%81+1])`, mapping to the real unicode values `c(32:57,10,65:90,10,97:122,10)`, converting to characters and printing.
> 8 votes

# Answer
## CJam, ~~23~~ 21 bytes

```
3{26{_I-" aA"=+}/N}fI

```

Try it online!

### Explanation

```
3{         e# For I from 0 to 2...
  26{      e#   For i 0 to 25...
    _I-    e#     Duplicate i and subtract I. This shifts the starting
           e#     character of each line left in the following string.
    " aA"= e#     Pick the character at the start of the unrotated line
           e#     of the current character. We basically just cycle
           e#     through non-letters, lower-case, upper-case, which is
           e#     the cycle throughout the result. Due to the I-, when
           e#     We get to the second line we start from A, and on the
           e#     third line we start from a.
    +      e#     Add i to the starting character to get the correct
           e#     column.
  }/
  N        e#   Push a linefeed.
}fI

```
> 6 votes

# Answer
# Japt, ~~17~~ 15 bytes

```
"@`"
;By@=cÄ é
```

Test it online!

### Explanation

```
"@`"         The string "@`\x1F". The following newline sets U to this string.
;            Reset variables A-L to various values. B is set to
 B           the uppercase alphabet, which we only use to get a length of 26.
  y@         Map each column Z (initially just the letter itself) through this function:
     cÄ        Increment each char-code in U.
        é      Rotate by 1 character.
    =          Set U to the result to keep the chain going.
             This generates the 26 columns exactly how we needed them.
             Implicit: output result of last expression

```

7 other possible 15-byters:

```
;By@" Aa"c+Y éY
;ByÈpv)iSc+Y)éY
;ByÈ+v)iSc+Y)éY
;ByÈpv)iYd32)éY
;ByÈ+v)iYd32)éY
;ByÈpv)i32dY)éY
;ByÈ+v)i32dY)éY

```
> 6 votes

# Answer
# , ~~88~~ 86 bytes

```
cat(intToUtf8(rbind(diffinv(matrix(c(66,-32,-31),25,5,T)[,1:3],,,t(c(32,65,97))),10)))

```

Try it online!

~~R is terrible at string manipulation and although it has some neat matrix builtins, rotations are another thing it doesn't do very easily.~~ I will happily give a bounty to anyone who can out-golf me in R.

Despite my having found a shorter answer, I'll still award a 50 rep bounty to the first other R answer shorter than 88 bytes.

I suppose I'd award myself the bounty if I could, but this is a whole two bytes shorter than the "boring" answer! I avoid rotations by just using R's penchant for recycling.

EDIT: user2390246's answer completely outgolfed me and I will be awarding a 100 point bounty since that solution is far superior.

To get here, I deconstructed the desired output to their ASCII code points with `utf8ToInt` (removing the newlines), built a matrix, and ran a `diff` on themm getting the columnwise differences. Noting the periodicity there, I set out to construct the matrix in a golfy fashion, hoping to use `diffinv` to recreate the original.

Thanks to the periodicity, we can recreate the `diff`ed matrix by forcing R to recycle with a non-multiple length, and extract the columns we actually wanted:

```
matrix(c(66,-32,-31),25,5,T)[,1:3]

```

Then we invert this process, with `diffinv` to recreate the code points, append a row of `10` (newlines) to the bottom, reconvert to ASCII with `intToUtf8`, and `cat` the result.
> 5 votes

# Answer
# MATL, 16 bytes

```
1Y2tk9V:v26:l&YS

```

Try it online!

### Explanation

```
1Y2     % Push 'AB...Z' (predefined literal)
t       % Duplicate
k       % Maker lowercase
9V      % Push 9, convert to string representation: gives char '9'
:       % Range. For chars, gives string from space to that
v       % Concatenate vertically. Gives a 3×26 char matrix
26      % Push 26
:       % Range. For numbers, gives numeric vector from 1 to that
l&YS    % Circularly shift each column of the first input (char matrix)
        % by the amount specified by the second input (numeric vector).
        % Implicitly display

```
> 5 votes

# Answer
# Perl 5, 46 bytes

```
print map{chr$n+++ord,$/x!($n%=26)}($",a,A)x26
```

Try it online!

Saved 13 bytes thanks to @TonHospel's arcane wizardry!
> 5 votes

# Answer
# Stax, ~~14~~ 12 bytes

```
ü≤▐éh╢%╠£┐3]

```

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

```
3R26        push [1,2,3] and 26
K           cross-map using the rest of the program, printing lines implicitly
            this instruction maps over a cartesian join
  -         subtract
  " Aa"@    index into " Aa" using the subtraction result
  i+        add the iteration index

```

Run this one

This program only uses features that have been available since the initial release of stax, but apparently I forgot about `K` for cross-map when I originally write this answer.

One nearly interesting thing to note about this answer is that the `R` is an unnecessary instruction because `K` implicitly turns integers into ranges. However there's no way to push `3` and `26` without some extra byte in between.
> 5 votes

# Answer
# Jelly, 13 bytes

```
26“ aA‘ẋs+ḶỌY

```

Try it online!

### How it works

```
26“ aA‘ẋs+ḶỌY  Main link. No arguments.

26             Set the argument and the return value to 26.
  “ aA‘ẋ       Repeat [32, 97, 65] (code points of ' ', 'a', and 'A') 26 times.
        s      Split the result into chunks of length 26.
          Ḷ    Unlength; yield [0, ..., 25].
         +     Add [0, ..., 25] to each of the chunks.
           Ọ   Unordinal; cast all integers to characters.
            Y  Jojn, separating by linefeeds.

```
> 5 votes

# Answer
# Charcoal, ~~26~~ ~~21~~ 15 bytes

```
Ｅ³⭆β§§⟦γαβ⟧⁻κμμ

```

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

```
 ³              Literal 3
Ｅ               Map over implicit range
   β            Lowercase letters
  ⭆             Map over characters and concatenate
            κ   Outer index
             μ  Inner index
           ⁻    Subtract
       γ        Printable characters
        α       Uppercase letters
         β      Lowercase letters
     §⟦   ⟧     Circularly index into list (selects one of the three strings)
              μ Inner index
    §           (Circularly) index into string
                Implicitly print each inner map result on a separate line

```
> 4 votes

# Answer
# , 29, 27 25 bytes

-2 bytes thanks to FrownyFrog -2 bytes thanks to miles

```
 |:u:(<26)2&(|.>:)32 65 97

```

Try it online!

Initial approach: , 29 bytes

```
u:(-|."_1&.|:32 65 97+/])i.26

```

Explanation: `i.26` \- range 0-26

```
   i.26
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

```

`32 65 97+/]` \- create a 3-row table for the characters

```
   32 65 97+/i.26
32 33 34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57
65 66 67  68  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122

```

`&.|:` transpose then do the next verb (`|.`) and transpose again

`-|."_1` rotate each row n times

```
     (-i.26)|."_1|:32 65 97+/i.26
 32  65  97
 98  33  66
 67  99  34
 35  68 100
101  36  69
 70 102  37
 38  71 103
104  39  72
 73 105  40
 41  74 106
107  42  75
 76 108  43
 44  77 109
110  45  78
 79 111  46
 47  80 112
113  48  81
 82 114  49
 50  83 115
116  51  84
 85 117  52
 53  86 118
119  54  87
 88 120  55
 56  89 121
122  57  90

```

`u:` convert to unicode

```
    u:(-i.26)|."_1&.|:32 65 97+/i.26
 bC#eF&hI)kL,nO/qR2tU5wX8z
A!cD$fG'iJ*lM-oP0rS3uV6xY9
aB"dE%gH(jK+mN.pQ1sT4vW7yZ

```

Try it online!
> 4 votes

# Answer
# PowerShell, 53 bytes

```
0..2|%{-join(32..57|%{[char]($_+(0,65,33)[$j++%3])})}

```

Try it online!

I see this is similar to Dom's Perl answer, but I arrived at it independently.

This exploits the fact that the pattern goes `Symbol - Lowercase - Capital`, even when wrapping newlines (`8 - z - A`, for example), and thus just adds the appropriate offset (chosen via `$j++%3`) to the current number `$_` before `-join`ing those together into a single string. That's done three times to come up with the three lines (preserving `$j` between iterations). Those three lines are left on the pipeline, and the implicit `Write-Output` gives us the newlines for free.
> 4 votes

# Answer
# Julia 0.6, 79 bytes

```
println.([prod([' ':'9' 'A':'Z' 'a':'z'][n,mod1(i-n,3)] for n=1:26) for i=2:4])

```

`[' ':'9' 'A':'Z' 'a':'z']` is the unrotated 2d array of characters, `[n,mod1(i-n,3)]` indexes into that array with appropriate rotation. `prod` takes a Vector of Characters to a String (since multiplication is used for string join). There are two nested Vector comprehensions resulting in a Vector containing 3 strings, then `println.` prints the each string in the Vector followed by a newline.

TIO lacks the appropriate method to multiply (with `prod`) two characters to get a String. I know that method was added somewhat recently, but the TIO version appears to be the same as the version on my PC where this code works, so I can't fully explain why it doesn't work on TIO.

Copy paste example (the `;` isn't necessary, it just supresses extra output in the REPL):

```
julia> println.([prod([' ':'9' 'A':'Z' 'a':'z'][n,mod1(i-n,3)] for n=1:26) for i=2:4]);
 bC#eF&hI)kL,nO/qR2tU5wX8z
A!cD$fG'iJ*lM-oP0rS3uV6xY9
aB"dE%gH(jK+mN.pQ1sT4vW7yZ

```
> 4 votes

# Answer
# C, ~~70~~ ~~69~~ ~~67~~ ~~60~~ 64 bytes

```
i;f(t){for(i=t=0;++i<81;putchar(i%27?(4-t++%3)*32%97+i%27:10));}

```

+4 bytes to make the function reusable.

Invalid 60-bytes answer that isn't reusable:

```
i,t;f(){for(;++i<81;putchar(i%27?(4-t++%3)*32%97+i%27:10));}

```

Port of ~~my Java 8 answer~~ *@Neil*'s JavaScript answer.

Try it online.
> 4 votes

# Answer
# Vim, ~~81~~ 79 bytes

```
a !"#$%&'()*+,-./0123456789␛:h<_␍jjYZZpPgU$klqq"aDjlma"bD"ap`ajD"bpkkp`akl@qq@q

```

## Explanation (simplified)

```
a !"#$%&'()*+,-./0123456789␛    Insert the first line
:h<_␍jjYZZpPgU$                  Insert the alphabet twice by copying it from the help page
klqq                             Define the loop `q`:
"aDjl                             Cut the rest of the line to `a`
ma"bD"ap                          Replace the rest of the second line (cut `b`, paste `a`)
`ajD"bp                           Replace the rest of the third line (cut `c`, paste `b`)
kkp                               Paste `c`
`akl@qq@q                        Run the loop, each time one more step to the right

```
> 3 votes

# Answer
# APL+WIN, 26 bytes

Index origin 0

```
⎕av[(-⍳26)⊖32 65 97∘.+⍳26]

```

Generate a matrix of integer index values of the characters in the APL atomic vector.

Rotate each column downwards by its number value.

Use the resulting indices to display the characters from the atomic vector.
> 3 votes

# Answer
# Japt, 17 bytes

```
26Æ" Aa"c+X éXÃ·y

```

Test it

---

## Explanation

```
26Æ           Ã       :Create the range [0,26) and pass each X through a function
   " Aa"              :  String literal
        c+X           :  Add X to the codepoint of each character
            éX        :  Rotate right X times
               ·      :Join with newlines
                y     :Transpose

```
> 3 votes

# Answer
# Ruby, ~~71~~ 63 bytes

```
3.times{|j|26.times{|i|$><<(i+"aA aA "[2-j+i%3].ord).chr}
puts}

```

Try it online!

For a bit there I was worried I wouldn't be able to beat the string literal version.

-8 bytes: Index into a 6-character string, instead of a rotating 3-int array

```
3.times{|j|
  26.times{|i|
    # Find the appropriate base character (2-j+i%3)
    # Add i to the ascii value of that character
    # Push to STDOUT
    $><< (i + "aA aA "[2 - j + i % 3].ord).chr
  }
  # newline
  puts
}

```
> 3 votes

# Answer
# C, 72 bytes

```
f(k,x,n){for(n=81;n;putchar(x?k*32+59-x-!k:10))x=--n%27,k=(3+x-n/27)%3;}

```
> 3 votes

# Answer
# Python 2, 65 bytes

```
for x in 2,99,196:s='';exec"s+=chr(32+x%291/3);x-=94;"*26;print s

```

Try it online!
> 3 votes

# Answer
# Ruby, 59 bytes

Try it online!

```
a=%w[\  A a]
75.times{|i|a[i%3]<<a[~-i%3][i/3].next}
puts a

```

Initiates an array with first characters of the three strings and then grows them in a single loop.
> 3 votes

# Answer
# Jelly, 16 bytes

```
“ Aa‘ṙ2‘$25Ð¡ỌZY

```

Try it online!

-4 thanks to miles.
> 2 votes

# Answer
# Python 2, 79 bytes

```
p=0
exec"o=0;r='';exec'r+=chr(o+[32,65,97][(p-o)%3]);o+=1;'*26;p+=1;print r;"*3

```

Try it online!
> 2 votes

# Answer
# APL (Dyalog Unicode), 23 bytes (Adám's SBCS)

```
(⎕UCS-⊖∘↑32 65 97+⊂)⍳26

```

Try it online!

-1 thanks to Adám.

Runs in an interactive environment.

Assumes `⎕IO←0`.
> 2 votes

# Answer
# Perl, ~~49~~ 46 bytes

```
perl -E 'say map chr($_*55%81)=~y// -:A-Z
a-z
/cr,0..79'

```

or

```
perl -E 'say grep{$_=chr$_*55%81;y// -:A-Z
a-z
/c}0..79'

```
> 2 votes

# Answer
# SOGL V0.12, 15 bytes

```
 9ΔZz⁰I{∑ē⌡«}⁰H

```

Try it Here!

Explanation:

```
 9               push "9"
  Δ              range from " " to "9" (that 1st space has nothing to do with this)
   Zz            push the uppercase and lowercase alphabets
     ⁰           wrap those in an array
      I          and rotate clockwise
       {    }    for each item
        ∑          join the item together
         ē⌡        counter times
           «         rotate the string left
             ⁰   wrap that all in an array
              H  and rotate anti-clockwise

```
> 2 votes

# Answer
# K4, 38 bytes

**Solution:**

```
-1"c"$+(-t).q.rotate'32 65 97+/:t:!26;

```

**Example:**

```
q)k)-1"c"$+(-t).q.rotate'32 65 97+/:t:!26;
 bC#eF&hI)kL,nO/qR2tU5wX8z
A!cD$fG'iJ*lM-oP0rS3uV6xY9
aB"dE%gH(jK+mN.pQ1sT4vW7yZ

```

**Explanation:**

9 characters to perform the rotation...

```
-1"c"$+(-t).q.rotate'32 65 97+/:t:!26;
-1                                   ; / print to stdout, swallow return
                                  !26  / til 26, 0..25
                                t:     / save as variable t
                             +/:       / add each right item to...
                     32 65 97          / the list 32, 65, 97 (ASCII offsets)
           .q.rotate'                  / rotate each-both
       (-t)                            / negate, 0..-25
      +                                / flip rows and columns
  "c"$                                 / cast to characters

```
> 2 votes

# Answer
# Pip, 24 bytes

Requires `-l` flag.

```
Z:B@{-a+^012}ME Z[PAAZz]

```

Try it online!

### Explanation

```
Z:B@{-a+^012}ME Z[PAAZz]
                          PA is string of all printable ASCII characters; AZ is uppercase
                          letters; z is lowercase letters (implicit)
                 [PAAZz]  Construct a list of those three strings
                Z         Zip (transpose), clipping PA to the length of the shorter two
             ME           Map-enumerate: apply the following function to the index (a) and
                          value (b) of each item in the list:
        ^012               Split 012 into a list of digits [0 1 2]
     -a+                   To each, add negative a
    {       }              Modify that function
  B@                       by using its return value to index into b
Z:                        Take the result of the map operation and zip it again
                          Print, each sublist concatenated on a separate line (-l flag)

```
> 2 votes

# Answer
# Perl 6,  ~~76 57~~  55 bytes

```
$/=|120.comb;.put for [Z~] map *.[|$/.=rotate(-1)],[Z] ' '..~9,'A'..*,'a'..*

```

Try it

```
.put for [Z~] ((' Aa','a A','Aa ')».ords «+»^26)».chr

```

Try it

```
.put for [Z~] (<!Bb b!B Bb!>».ords «+»(^26-1))».chr

```

Try it

## Explanation

```
( ' Aa', 'a A', 'Aa ' )».ords

  ( (32, 65, 97),    # ' Aa'.ords
    (97, 32, 65),    # 'a A'.ords
    (65, 97, 32), )  # 'Aa '.ords

```

(`^26` is short for `0..^26` which is similar to `0..26-1`)

```
… «+» ^26            # matrix add; extending both sides

  #   + line 1
  #   |    + line 2
  #   |    |    + line 3           +-------------+-------------+ repeat 0..25
  #   V    V    V                  V             V             V
  ( ( 32,  65,  97), # ( (.[0;0] + 0), (.[0;1] + 0), (.[0;2] + 0) ),# <+ repeat
    ( 98,  33,  66), # ( (.[1;0] + 1), (.[1;1] + 1), (.[1;2] + 1) ),#  | ' Aa'.ords
    ( 67,  99,  34), # ( (.[2;0] + 2), (.[2;1] + 2), (.[2;2] + 2) ),#  |
                                                                    #  |
    ( 35,  68, 100), # ( (.[0;0] + 3), (.[0;1] + 3), (.[0;2] + 3) ),# <+
    (101,  36,  69), # ( (.[1;0] + 4), (.[1;1] + 4), (.[1;2] + 4) ),#  |
    ( 70, 102,  37), # ( (.[2;0] + 5), (.[2;1] + 5), (.[2;2] + 5) ),#  |
                                                                    #  |
    ( 38,  71, 103), # ( (.[0;0] + 6), (.[0;1] + 6), (.[0;2] + 6) ),# <+
    (104,  39,  72), # ( (.[1;0] + 7), (.[1;1] + 7), (.[1;2] + 7) ),
    ( 73, 105,  40), # ( (.[2;0] + 8), (.[2;1] + 8), (.[2;2] + 8) ),
    … )

```

```
(…)».chr             # (…).deepmap(*.chr)

  #   + line 1
  #   |    + line 2
  #   |    |    + line 3
  #   V    V    V
  ( (' ', 'A', 'a'),
    ('b', '!', 'B'),
    ('C', 'c', '"'),
    ('#', 'D', 'd'),
    ('e', '$', 'E'),
    ('F', 'f', '%'),
    … )

```

```
[Z~] …               # reduce using zip meta-op combined with concat op
                     # (has effect of rotating 90°, and joining)

  ( ' bC#eF&hI)kL,nO/qR2tU5wX8z',
    "A!cD$fG'iJ*lM-oP0rS3uV6xY9",
    'aB"dE%gH(jK+mN.pQ1sT4vW7yZ', )

```

```
.put for …           # loop over them printing them with trailing newline

```
> 2 votes

# Answer
# brainfuck, ~~121~~ 115 bytes

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

```

*Thanks to @JoKing for saving 6 bytes!*

Try it online!
> 2 votes

# Answer
# C (gcc) ~~59 58~~ 55 bytes

```
t;f(i){for(;putchar(i++%27?t%26+" aA"[t++%3]:10)^90;);}

```

Reusable millions of times, until t oveflows
> 2 votes

# Answer
# JavaScript (ES6), 85 bytes

```
_=>` bC#eF&hI)kL,nO/qR2tU5wX8z
A!cD$fG'iJ*lM-oP0rS3uV6xY9
aB"dE%gH(jK+mN.pQ1sT4vW7yZ`

```

```
f=_=>` bC#eF&hI)kL,nO/qR2tU5wX8z
A!cD$fG'iJ*lM-oP0rS3uV6xY9
aB"dE%gH(jK+mN.pQ1sT4vW7yZ`
o.innerText=f()
```

```
<pre id=o>
```
> 1 votes

# Answer
# C (gcc), ~~108~~ ~~103~~ 102 bytes

```
f(j,k){for(k=1;k<4;k+=puts(""))for(j=0;j<26;)putchar(j+!(j%3-k+1)*32+!(~k%3+j%3)*65+!(j++%3-k%3)*97);}

```

Try it online!
> 1 votes

# Answer
# \>\<\>, 57 bytes

```
0 >::dd+%$3%3$-3%1+v
;v^?%+dd:+1o+,2*'A'<
> ^
?a
%o
3:
^<

```

Try it online!
> 1 votes

# Answer
# Python 3, 71 bytes

```
print(''.join(chr(b%3*65%97+b%26+32)+'\n'[25-b%26:]for b in range(78)))

```

Try it online!
> 1 votes

# Answer
# Yabasic, 88 bytes

An anonymous solution that takes no input and outputs to the console in text-graphics mode.

Note: the standard Yabasic host will place the message `---Program done, press RETURN---` over top the second line of output so a terminal line such as `?:?` must be added to the end of the solution to push this message down by two or more lines.

```
Clear Screen
For c=0To 25
For r=0To 2
?@(c,Mod(r+c,3))Chr$(c-.5*r^2+33.5*r+32)
Next
Next

```

## Output

# Literal Solution, 86 bytes

```
?" bC#eF&hI)kL,nO/qR2tU5wX8z\nA!cD$fG'iJ*lM-oP0rS3uV6xY9\naB\"dE%gH(jK+mN.pQ1sT4vW7yZ"

```

Try it online!
> 1 votes

# Answer
# \>\<\>, 38 bytes

```
>ldd+%3l3%-'A'*2,+ol0ld6*)?;ldd+%.
/ao

```

Try it online!
> 1 votes

# Answer
# Vyxal 3 `j`, 17 bytes

```
kp½hkR+₂ẆTƛm(ṙ]T“

```

Try it Online!

I tried, no easy way to get codepoints so slicing builtins it is.
> 1 votes

# Answer
# PHP, 74 bytes

```
for(;$a<78;$a++)echo$a%26?'':'
',chr($a%26+[32,65,97][(2*$a%52+$a/26)%3]);

```
> 0 votes

# Answer
# Deadfish~, 803 bytes

```
{iii}iic{iiiiii}iiiiiic{ddd}dc{ddd}ddc{iiiiii}iiiiiic{ddd}dc{ddd}ddc{iiiiii}iiiiiic{ddd}dc{ddd}ddc{iiiiii}iiiiiic{ddd}dc{ddd}ddc{iiiiii}iiiiiic{ddd}dc{ddd}ddc{iiiiii}iiiiiic{ddd}dc{ddd}ddc{iiiiii}iiiiiic{ddd}dc{ddd}ddc{iiiiii}iiiiiic{ddd}dc{ddd}ddc{iiiiii}iiiiiic{{d}}{d}ddc{iiiii}iiiiic{ddd}ddc{iiiiii}iiiiiic{ddd}dc{ddd}ddc{iiiiii}iiiiiic{ddd}dc{ddd}ddc{iiiiii}iiiiiic{ddd}dc{ddd}ddc{iiiiii}iiiiiic{ddd}dc{ddd}ddc{iiiiii}iiiiiic{ddd}dc{ddd}ddc{iiiiii}iiiiiic{ddd}dc{ddd}ddc{iiiiii}iiiiiic{ddd}dc{ddd}ddc{iiiiii}iiiiiic{ddd}dc{ddd}ddc{ddddd}iiic{{i}d}dddc{ddd}dc{ddd}ddc{iiiiii}iiiiiic{ddd}dc{ddd}ddc{iiiiii}iiiiiic{ddd}dc{ddd}ddc{iiiiii}iiiiiic{ddd}dc{ddd}ddc{iiiiii}iiiiiic{ddd}dc{ddd}ddc{iiiiii}iiiiiic{ddd}dc{ddd}ddc{iiiiii}iiiiiic{ddd}dc{ddd}ddc{iiiiii}iiiiiic{ddd}dc{ddd}ddc{iiiiii}iiiiiic{ddd}dc

```

Try it online!
> 0 votes

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

```
f=(i=k=81)=>i--?Buffer([i%27?k--%3*32.5+58.5-i%27:10])+f(i):''

```

Try it online!

From Neil's solution
> 0 votes

---
Tags: code-golf, string, kolmogorov-complexity, alphabet
---


# Question
Title: Approximate the Dottie number to arbitrary precision
The Dottie number is the fixed point of the cosine function, or the solution to the equation **cos(x)=x**.1

Your task will be to make code that approximates this constant. Your code should represent a function that takes an integer as input and outputs a real number. The limit of your function as the input grows should be the Dottie number.

You may output as a fraction, a decimal, or an algebraic representation of a number. Your output should be capable of being arbitrarily precise, floats and doubles are not sufficient for this challenge. If your language is not capable of arbitrary precision numbers, then you must either implement them or choose a new language.

This is a question so answers will be scored in bytes, with fewer bytes being better.

### Tips

One way of calculating the constant is to take any number and repeatedly apply the cosine to it. As the number of applications tends towards infinity the result tends towards the fixed point of cosine.

Here is a fairly accurate approximation of the number.

```
0.739085133215161

```

1: Here we will take cosine in radians

# Answer
> 10 votes
# MATL, ~~34~~ ~~30~~ 19 bytes

*11 bytes off thanks to Sanchises!*

```
48i:"'cos('wh41hGY$

```

The last decimal figures in the output may be off. However, the number of correct figures starting from the left increases with the input, and the result converges to the actual constant.

**Try it online!**

### Explanation

For input *n*, and starting at *x*=1, this applies the function

*x* ↦ cos(*x*)

with *n*-digit variable-precision arithmetic *n* times.

```
48         % Push 48, which is ASCII for '1': initial value for x as a string
i:"        % Do n times, where n is the input
  'cos('   %   Push this string
  w        %   Swap. Moves current string x onto the top of the stack
  h        %   Concatenate
  41       %   Push 41, which is ASCII for ')'
  h        %   Concatenate. This gives the string 'cos(x)', where x is the
           %   current number
  GY$      %   Evaluate with variable-prevision arithmetic using n digits
           %   The result is a string, which represents the new x
           % End (implicit). Display (implicit). The stack contains the last x

```

# Answer
> 8 votes
# dzaima/APL, 55 bytes

```
⎕←⊃{⍵,⍨-/P,((P÷⍨×)/¨(2×⍳N)⍴¨⊃⍵)÷!2L×⍳N}⍣{⍵≢∪⍵}P←10L*N←⎕

```

Using big integer (no big decimals!) arithmetic (where \\$10^N\\$ is the equivalent of a `1`), iterate the first \\$N\\$ terms of the Taylor series (an overestimate, but that's fine) until a duplicate has been encountered. May be off by a bit due to lost precision in the end, but, as with other answers, those differences will disappear with higher \\$N\\$.

No TIO link as TIO's dzaima/APL hasn't been updated to support bigintegers.

Example I/O:

```
1
9L

10
7390851332L

100
7390851332151606416553120876738734040134117589007574649656806357732846548835475945993761069317665318L

200
73908513321516064165531208767387340401341175890075746496568063577328465488354759459937610693176653184980124664398716302771490369130842031578044057462077868852490389153928943884509523480133563127677224L

```

# Answer
> 7 votes
# Python 3, 58 bytes

```
lambda n:S('cos('*n+'0'+')'*n).evalf(n)
from sympy import*

```

Try it online!

# Answer
> 6 votes
# GNU bc -l, 30

Score includes +1 for `-l` flag to `bc`.

```
for(a=1;a/A-b/A;b=c(a))a=b
a

```

The final newline is significant and necessary.

Try it online.

`-l` does 2 things:

* enable the "math" library, including `c()` for cos(x)
* sets precision (scale) to 20 decimal places (`bc` has arbitrary precision calculation)

I'm not really clear on the precision requirement. As it is, this program calculates to 20 decimal places. If a different precision is required, then `scale=n;` needs to be inserted at the start of the program, where `n` is the number of decimal places. I don't know if I should add this to my score or not.

Note also that for some numbers of decimal places (e.g. 21, but not 20), the calculation oscillates either side of the solution in the last digit. Thus in the comparison of current and previous iterations, I divide both sides by 10 (`A`) to erase the last digit.

# Answer
> 5 votes
# Wolfram Language (Mathematica), 19 bytes

```
Nest[Cos,0,9#]~N~#&

```

Try it online!

-3 bytes from @alephalpha

# Answer
> 3 votes
# (+Rmpfr), 55 bytes

```
function(n,b=Rmpfr::mpfr(1,n)){for(i in 1:n)b=cos(b);b}

```

Dennis has now added Rmpfr to TIO so this will work; added some test cases.

### Explanation:

Takes the code I wrote from this challenge to evaluate `cos` `n` times starting at `1`, but first I specify the precision I want the values to be in by creating an object `b` of class `mpfr` with value `1` and precision `n`, `n>=2`, so we get more precision as we go along.

Try it online!

# Answer
> 3 votes
# Octave, 42 bytes

```
@(n)digits(n)*0+vpasolve(sym('cos(x)-x'));

```

Try it online!

Pretty much a duplicate of my answer to Approximate the Plastic Number, but somewhat shorter due to more relaxed requirements.

# Answer
> 2 votes
# Mathics or Mathematica, 46 bytes

```
{$MaxPrecision=#}~Block~Cos~FixedPoint~N[1,#]&

```

Try it online!

# Answer
> 2 votes
# PHP, 50 bytes

```
$a=$argv[1];$i=$j=0;while($i<$a){$j=cos($j);$i++;}

```

Try it online!

# Answer
> 2 votes
# Pyth, 57 54 bytes

```
u_.tG1lX$globals()$"neg"$__import__("decimal").Decimal

```

This would be much shorter if we didn't need the Decimal to be up to spec, but it is what it is.

Edit 1: -3 bytes because we need a number anyways, so we can use `X`s returned copy of `globals()` length as our starting value, moving it to the end and removing a `$` and some whitespace.

Try it online!

# Answer
> 2 votes
# JavaScript (Node.js), 84 bytes

```
n=>"0."+(F=(J,Z=c=0n)=>J?F(J*-I*I/++c/++c/B/B,Z+J):I-Z>>2n?(I=Z,F(B)):I)(B=I=10n**n)

```

Try it online!

Has a precision of roughly `n-1` digits. BigInt is used and `cos(x)` is calculated using its Taylor expansion. The `I-Z>>2n` part is used only to prevent looping forever (with a cost of 4 bytes and some precision). Although theoretical applicable for arbitrary precision, practical range is `n<63` because of stack overflow.

### Shorter (82 bytes), no worries about stack overflow, but far fewer precision

```
n=>"0."+eval("for(I=B=10n**n;n--;I=Z)for(Z=J=B,c=0n;J;)Z+=(J=J*-I*I/++c/++c/B/B)")

```

### Much shorter (80 bytes), larger range until stack overflow (`n<172`), but same precision as the 82-byte.

```
n=>"0."+(F=(J,Z=c=0n)=>J?F(J*-I*I/++c/++c/B/B,Z+J):n--?(I=Z,F(B)):I)(B=I=10n**n)

```

### If arbitrary precision is not the main point, then 25 bytes:

```
F=n=>n?Math.cos(F(n-1)):1

```

# Answer
> 2 votes
# Factor \+ `math.polynomials math.factorials`, 66 bytes

```
[| x | 1 x [ sq neg x [0,b) [ 2 * n! recip ] map polyval ] times ]

```

Try it online!

Factor has rational numbers, but no arbitrary-precision decimals. This answer tries to exploit it as much as possible: iterate the evaluation of the fist `n` terms of Taylor series (more precisely, Maclaurin series) `n` times, with the starting value of 1. The output is given as a rational number; the floating-point representation is also shown on TIO to check the value in human-readable form.

The function is very slow to calculate and very slow to converge, but in theory it must converge to the Dottie number as `n` increases, since the iterated function approaches the cosine function, the iteration count increases to infinity, and the whole computation is done in rationals (and therefore exact).

### How it works

Given a positive integer \\$n\\$, the code approximates the Dottie number as follows:

$$ \cos{x} = \sum\_{i=0}^{\infty}{\frac{(-1)^i}{(2i)!}x^{2i}} \approx \sum\_{i=0}^{n-1}{\frac{(-x^2)^i}{(2i)!}} \\ \text{Dottie number } = \cos{x} \text{ iterated } \infty \text{ times on } 1 \\ \approx \sum\_{i=0}^{n-1}{\frac{(-x^2)^i}{(2i)!}} \text{ iterated } n \text{ times on } 1 $$

```
[| x |  ! an anonymous function that takes one arg `x` as a local variable
  1 x [ ... ] times  ! repeat the inner function x times on the value 1...
    sq neg           !   val -> -val^2
    x [0,b)          !   0..x-1
    [ 2 * n! recip ] map  ! convert each number `i` to 1/(2i)!
    polyval          !   evaluate the array as polynomial at the value of -val^2
]

```

# Answer
> 2 votes
# Julia 1.0, 42 bytes

```
!n=big(n<2||setprecision(()->cos(!~-n),n))

```

Try it online!

sets the precision of `BigFloat`s to `n` bits and computes \\$cos^{n-1}(1)\\$ recursively

# Answer
> 1 votes
# Perl 5, 41 Bytes

```
use bignum;sub f{$_[0]?cos(f($_[0]-1)):0}

```

Bignum is required for the arbitrary precision. Defines a function f that recursively applies cosine to 0 N times.

TIO doesn't seem to have bignum so no link :(

# Answer
> 1 votes
## Mathematica 44 Bytes

```
FindRoot[Cos@x-x,{x,0},WorkingPrecision->#]&

```

`FindRoot` uses Newton's method by default.

# Answer
> 1 votes
# Axiom, 174 bytes

```
f(n:PI):Complex Float==(n>10^4=>%i;m:=digits(n+10);e:=10^(-n-7);a:=0;repeat(b:=a+(cos(a)-a)/(sin(a)+1.);if a~=0 and a-b<e then break;a:=b);a:=floor(b*10^n)/10.^n;digits(m);a)

```

ungolfed and commented

```
-- Input: n:PI numero di cifre
-- Output la soluzione x a cos(x)=x con n cifre significative dopo la virgola
-- Usa il metodo di Newton a_0:=a  a_(n+1)=a_n-f(a_n)/f'(a_n)
fo(n:PI):Complex Float==
  n>10^4=>%i
  m:=digits(n+10)
  e:=10^(-n-7)
  a:=0     -- Punto iniziale
  repeat
     b:=a+(cos(a)-a)/(sin(a)+1.)
     if a~=0 and a-b<e then break
     a:=b
  a:=floor(b*10^n)/10.^n
  digits(m)
  a

```

results:

```
(3) -> for i in 1..10 repeat output[i,f(i)]
   [1.0,0.7]
   [2.0,0.73]
   [3.0,0.739]
   [4.0,0.739]
   [5.0,0.73908]
   [6.0,0.739085]
   [7.0,0.7390851]
   [8.0,0.73908513]
   [9.0,0.739085133]
   [10.0,0.7390851332]
                                                               Type: Void
           Time: 0.12 (IN) + 0.10 (EV) + 0.12 (OT) + 0.02 (GC) = 0.35 sec
(4) -> f 300
   (4)
  0.7390851332 1516064165 5312087673 8734040134 1175890075 7464965680 635773284
  6 5488354759 4599376106 9317665318 4980124664 3987163027 7149036913 084203157
  8 0440574620 7786885249 0389153928 9438845095 2348013356 3127677223 158095635
  3 7765724512 0437341993 6433512538 4097800343 4064670047 9402143478 080271801
  8 8377113613 8204206631
                                                      Type: Complex Float
                                   Time: 0.03 (IN) + 0.07 (OT) = 0.10 sec

```

I would use the Newton method because it would be faster than 'repeated cos(x) method'

```
 800   92x
1000  153x
2000  379x

```

where in the first column there is the number of digit and in the second column there is how much Newton method is faster than use repeated cos(x) method, here. Good Morning

# Answer
> 1 votes
# PowerShell Core, 35 bytes

```
1.."$args"|%{$x=[Math]::Cos($x)}
$x

```

Try it online!

# Answer
> 1 votes
# Vyxal, 6 bytes

```
(∆c)$Ḟ

```

Try it Online!

Uses sympy's arbitrary-precision cosine function. Since decimals are outputted to a fixed precision (although stored as arbitrary-precision) it has to be taken to n decimal places.

```
(  )   # n times
 ∆c    # cosine
    $Ḟ # result to n decimal places

```

# Answer
> 1 votes
# Maxima, 93 bytes

A port of @MarcMush's Julia 1.0 answer in Maxima.

93 bytes, it can be golfed much more.

---

Golfed version. Try it online!

```
b(n):=block([o],o:fpprec,fpprec:n,r:if n<2 then bfloat(n)else bfloat(cos(b(n-1))),fpprec:o,r)

```

Ungolfed version. Try it online!

```
/* Define the recursive function with dynamic precision */
b(n) := block(
    [old_prec],
    /* Save the old precision */
    old_prec: fpprec,
    /* Set the precision relative to n */
    fpprec: n,
    /* Perform the calculation with the new precision */
    result: if n < 2 then bfloat(n) else bfloat(cos(b(n-1))),
    /* Restore the old precision */
    fpprec: old_prec,
    /* Return the result */
    result
);

/* Print the results from 1 to 1000 */
for i:1 thru 1000 do (
    print(b(i))
);

```

# Answer
> 0 votes
# Pari/GP, 47 bytes

```
f(n)=if(n,subst(Pol(cos(x+O(x^n))),x,f(n-1)),1)

```

Try it online!

# Answer
> 0 votes
# Haskell, 267 bytes

```
f d=(iterate(\(b,e)->r(\(x,y)(z,w)->(x*10^(2*d-y)+z*10^(2*d-w),2*d))(0,0)$takeWhile((/=0).fst)[r(\(x,y)(z,w)->(x*z,y+w))((-1)^n,0)[let z=2*e*n;s=max(z-d)0in(b^(2*n)`div`10^s,z-s),(10^d`div`product[2..2*n],d)]|n<-[0..]])(7,1))#[];(h:t)#v|h`elem`v=h|0<1=t#(h:v);r=foldr

```

Try it online!

# Answer
> 0 votes
# J-uby, 33 bytes

Takes the desired precision as an argument.

```
~:!~%(:& &~(:cos&BigMath))&0.to_d

```

Attempt This Online!

# Answer
> 0 votes
# Go, 71 bytes

```
import."math"
func f(n int)(k float64){for;n>=0;n--{k=Cos(k)}
return k}

```

Attempt This Online!

Input is the number of times to apply `cos`. Limited to 64-bit floating point precision.

# Answer
> 0 votes
# APL(NARS), 219 chars

```
R←{⍵=0:⍵⋄10≥m←(⍺-⍨⌊10⍟d←∣1∧÷⍵×1x)⌊⍺-⍨⌊10⍟n←∣1∧⍵×1x:⍵⋄(×⍵)×(⌊n÷q)÷⌊d÷q←{(10∘×⍣⍵)1x}m-5}

r←p C w;d;e;v;m
r←d←1⋄e←1÷10x*p⋄v←¯1,0⋄m←w×w×¯1
r+←d×←m÷×/v+←2⋄→2×⍳e<∣d⋄r←p R r

r←D w;e;v
e←1÷10x*w⋄v←1x
r←w C v⋄→0×⍳e>∣v-r⋄v←r⋄→2

```

C is the cos function, has as parameters p the precision (or the number of digits afther the decimal point) and w the rational number (here represented using r as in 23r4 for 23/4) and return a rational. If the argument of that function is a int or a float, it return one float. For 3 significative digits we have

```
      3 C 1
0.5403028025
      3 C 1x
4357r8064
      2○1
0.5403023059

```

D is the function that would return the number in question that has argument the digit of precision. How appear one fractional result?

```
      D 3
117407r158925

```

So there is need one function that traslate the fractional result in a decimal string we can read r2fs: input ⍺ the precision ⍵ one rational number

```
r2fs←{⎕ct←0⋄k←≢b←⍕⌊⍵×10x*a←⍺⋄k-←s←'¯'=↑b⋄c←{s:'¯'⋄''}⋄m←s↓b⋄0≥k-⍺:c,'0.',((⍺-k)⍴'0'),m⋄c,((k-⍺)↑m),'.',(k-⍺)↓m}

```

One has to note as ⎕ct is a local varible in r2fs and its value in use out of that function is different. So all could be more clear

```
      8 r2fs¨ D¨ 1 2 3 4 5 6 7 8
 0.70224186 0.73556389 0.73875727 0.73905483 0.73908230 0.73908552 0.73908517 0.73908513
      19 r2fs D 20
0.7390851332151606416
      40 r2fs D 39
0.7390851332151606416553120876738734040131
      39 r2fs D 40
0.739085133215160641655312087673873404013

```

For the C function sometime the result is not ok for float input

```
     10 C 45
55.65114514
      2○45
0.5253219888
      10 C 45
55.65114514
      2○45
0.5253219888

```

but the fraction input it seems converge right for cos

```
      49 r2fs 50 C 45x
0.5253219888177296960474644048235629188973106884573

```

One other problem one has to solve here it seems to me that the function D can converge to that number but its fraction in r is so big that consume all resources so have to be cut in some way... I would say one could reduce the size of the fraction in memory cuting the final parts of the numerator and denomicator (save all the digits of both until precision number), something as function R make (for me R has to be used inside the cos).

---
Tags: code-golf, math, trigonometry, approximation
---