# Question
Title: Size Does Matter (at least referring to bottles)
# Introduction

I have an **even** number of bottles, all of different sizes. Unfortunately, I only know the size of the smallest bottle: **300ml**.
I also know the following:

* Half of the bottles are twice the size of the other half, meaning that the smallest small bottle and the smallest large bottle are in a ratio of 2:1.
* The smaller bottles, from smallest to largest, increase in size by n%, where n is the number of bottles multiplied by 3.

Could you help find what sizes my bottles are?

# Challenge

Your input is to be an **even** number of bottles.
The output should be the size of all of the small bottles (from smallest to largest), then all of the large bottles (from smallest to largest).

# Example I/O

In: `2`
Out: `300, 600`

In: `4`
Out: `300, 336, 600, 672`

In: `10`
Out: `300, 390, 507, 659.1, 856.83, 600, 780, 1014, 1318.2, 1713.66`

(Note: commas are unnecessary; this answer can be formatted in any way you want as long as all of the "small" bottles come before the "large" bottles.)

# Rules

Standard loophole rules apply.
This is , so shortest answer in bytes wins!

# Winners

**Esoteric Languages**
15 bytes
05AB1E by Kevin Cruijssen

**Standard Languages**
36 bytes
Mathematica by attinat

# Answer
> 3 votes
# 05AB1E, 15 bytes

```
₆v;F.03*>NmyтP,

```

Port of *@TFeld*'s Python 2 answer, so make sure to upvote him.

Try it online or verify all test cases.

**Explanation:**

```
₆                # Push builtin integer 36
 v               # Loop `y` over both digits:
  ;              #  Halve the (implicit) input-integer
   F             #  Inner loop `N` in the range [0, input/2):
    .03*         #   Multiply the (implicit) input by 0.03
                 #   (alternative 4-byter: `т/3*` # divide by 100, multiply by 3)
        >        #   Increase this by 1
         Nm      #   Take it to the power `N`
           yт    #   Push both `y` and 100
             P   #   And take the product of the entire stack
              ,  #   Then pop and print this number with trailing newline

```

# Answer
> 6 votes
# Python 2, ~~61~~ ~~60~~ 59 bytes

```
lambda n:[a*(1+.03*n)**i*75for a in 4,8for i in range(n/2)]

```

Try it online!

-1 byte, thanks to Joseph Sible

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

```
{#,2#}&[300(1+.03#)^Range[0,#/2-1]]&

```

Try it online!

# Answer
> 3 votes
# Jelly, 16 bytes

```
×.03‘*HḶ$×300;Ḥ$

```

Try it online!

-2 bytes thanks to Nick Kennedy

# Explanation

```
×.03‘*HḶ$×300;Ḥ$  Main Link
×.03              Multiply the number of bottles by 3%
    ‘             Increment (add 100%)
     *            (Vectorized) exponent to the power of:
      HḶ$         [0, 1, ..., n-1]
         ×300     Multiply each factor by 300
             ;Ḥ$  Double the list and append it

```

# Answer
> 3 votes
# Julia 1.0, 42 38 bytes

```
f(n,z=[75*(1+.03n).^(0:n÷2-1)])=4z,8z

```

-4 bytes using ideas from John and Joseph Sible.

Try it online!

# Answer
> 3 votes
# Haskell, 47 bytes

```
f n=[75*a*(1+0.03*n)**i|a<-[4,8],i<-[0..n/2-1]]

```

Try it online!

# Answer
> 3 votes
# Python 2, 55 bytes

```
n=input()/2
for c in 4,8:exec"print c*75;c*=1+.06*n;"*n

```

Try it online!

The `*75` trick is taken from other answers.

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

```
f=(n,b=300,r=1+n*9/b,h=n/2)=>n?[b,...f(n-1,--h?b*r:600,r,h)]:[]

```

Try it online!

# Answer
> 2 votes
# PHP, ~~70~~ 62 bytes

```
for($s=300;$i++<$n=$argn;$s=$n/2-$i?$s+$s*$n*.03:600)echo$s,_;

```

Try it online!

Output numbers are seperated by `_`.

Alternative for `$s+$s*$n*.03` can be `$s*=1+$n*.03` too, but both are same length.

# Answer
> 2 votes
# Icon, ~~60~~ 58 bytes

```
procedure f(n)
write(!36*(1+.03*n)^(0to n/2-1)*100)&\z
end

```

Try it online!

Saved 2 bytes by replacing `(3|6)`(alternate 3 with 6) with `!36`. `!`generates the components of a data object. When applied to a number it generates its digits. In `Unicon` \- the descendent of `Icon` \- `!n` generates the numbers in the range 1..n.

# Answer
> 2 votes
# Ruby, ~~57~~ 53 bytes

```
->n{n.times.map{|a|300*(1+a*2/n)*(1+0.03*n)**a%=n/2}}

```

Try it online!

# Answer
> 2 votes
# PowerShell, ~~66~~ 54 bytes

-12 bytes thanks to mazzy

```
param($n)300,600|%{$y=$_;1..($n/2)|%{$y;$y*=1+$n*.03}}

```

Try it online!

# Answer
> 2 votes
# K (oK), 32 bytes

```
{s,2*s:(-1+x%2)((1+.03*x)*)\300}

```

Try it online!

# Answer
> 1 votes
# Charcoal, 23 bytes

```
ＮθＦ²Ｅ⊘θＩ××³⁰⁰⊕ιＸ⊕×θ·⁰³κ

```

Try it online! Link is to verbose version of code. Outputs each list element on a separate line. Explanation:

```
Ｎθ

```

Input `n`

```
Ｆ²

```

Loop `i` twice, once for the small sizes, once for the large sizes.

```
Ｅ⊘θ

```

Loop `k` over half of the number of bottles, and implicitly output each calculation on its own line.

```
Ｉ××³⁰⁰⊕ιＸ⊕×θ·⁰³κ

```

Calculate `300(i+1)(.03n+1)ᵏ` and cast the result to string.

# Answer
> 1 votes
# , 46 bytes

```
x=scan();b=300*(1+0.03*x)^(0:(x/2-1));c(b,b*2)

```

Try it online

# Answer
> 1 votes
# Forth (gforth), 84 bytes

```
: x dup 2/ 0 do fdup f. fover f* loop ; : f dup s>f .03e f* 1e f+ 3e2 x 6e2 fnip x ;

```

Try it online!

### Code Explanation

```
\ helper function to extract out common logic from the small and large numbers
: x               \ start a new word definition
  dup 2/          \ duplicate the input and divide by 2
  0 do            \ loop from 0 to n/2
    fdup f.       \ print the top of the floating point stack
    fover f*      \ multiple the top float stack value by the 2nd float stack value
  loop            \ end the loop
;

: f               \ start a new word definition
  dup s>f         \ duplicate n and place a copy on the float stack
  0.03e f*        \ multiple by 0.03 (multiply by 3 and divide by 100)
  1e f+           \ add 1 to get our increase multiplier
  3e2 x           \ print the smaller numbers by starting with 300
  6e2 fnip x      \ drop the remaining small number and print the large numbers from 600
;                 \ end word definition

```

# Answer
> 1 votes
# Pyth, 23 bytes

```
Fk2Fb/Q2*300*hk^h*.03Qb

```

Try it online!

Port of @TFeld's answer, which I was able to make decently concise. Cant help but feel like there's a more clever answer with Pyth but I wasnt able to find it.

## How it Works

```
Fk2Fb/Q2*300*hk^h*.03Qb
Fk2                     - For k in range(2)
   Fb/Q2                - For b in range(input/2)
        *300*hk         - 300 times k+1 times...
                h*.03Q  - 1 + 0.03 times input
               ^      b - The above to the exponent b
                          Implicitly prints the result

```

# Answer
> 1 votes
# Wolfram Language (Mathematica), 40 bytes

Two independent 40-byte answers: the first is an unnamed function, the second is a named function `g`, both taking one argument.

```
Table[300i(1+.03#)^j,{i,2},{j,0,#/2-1}]&

g@n_:=300#(1+.03n)^(#2-1)&~Array~{2,n/2}

```

# Answer
> 0 votes
# Java 8, 89 bytes

```
n->{for(int k=0,i;++k<3;)for(i=0;i<n/2;)System.out.println(Math.pow(.03*n+1,i++)*k*300);}

```

Port of *@TFeld*'s Python 2 answer, so make sure to upvote him.

Try it online.

**Explanation:**

```
n->{                              // Method with integer parameter and no return-type
  for(int k=0,i;++k<3;)           //  Loop `k` in the range (0,3) (basically [1,2]):
    for(i=0;i<n/2;)               //   Inner loop `i` in the range [0, i/2):
      System.out.println(         //    Print with trailing newline:
        Math.pow(.03*n            //     `n` multiplied by 0.03
                 +1               //     incremented by 1
                   ,i++)          //     to the power `i`
                        *k*300);} //     multiplied by `k` and 300

```

# Answer
> 0 votes
# C (gcc), ~~79~~ 74 ~~77~~ bytes

78 if the dash in compile arg is ignored. Port of TField answer. Increase in bytes is to comply with rules.

-5 bytes thanks to ceilingcat and bznein

```
b;c;f(a){for(b=0;++b<3;c=0)while(c<a/2)printf("%f ",pow(.03*a+1,c++)*b*300);}

```

Try it online!

# Answer
> 0 votes
# Wren, 79 bytes

```
Fn.new{|n|
for(a in[300,600])for(i in 1..n/2){
System.print(a)
a=a+a*n*0.03
}
}

```

Try it online!

# Wren, 81 bytes

TField answer turns out to be longer.

```
Fn.new{|n|
for(i in 0...n/2)for(a in[3,6])System.print(a*(1+0.03*n).pow(i)*100)
}

```

Try it online!

# Answer
> 0 votes
# Japt, ~~27~~ 23 bytes

```
_+3/L*Z*U}h[300]Uz
cUmÑ

```

Try it

```
_+3/L*Z*U} // function returning next element
h[300]Uz // runs the above func. U/2 times, starting from 300
cU®Ñ // concat the array obtained with the array multiplied * 2

```

Saved 4 thanks to @Shaggy

# Answer
> 0 votes
# Husk, 20 bytes

```
S+mDmo*300`^→*.03¹ŀ½

```

Try it online! A port of the standard answer.

---
Tags: code-golf, number
---


title: Ones and Twos for days

text:
# Question
Title: Ones and Twos for days
Inspiring myself on a recent challenge, we ought to compute a sequence that is very close to A160242.

# Task

Your task is to generate the sequence \\$ \\{s\_i\\}\_{i=0}^\infty \\$:

`1, 2, 1, 1, 2, 2, 2, 1, 1, 2, 2, 2, 2, 2, 1, 1, 2, 2, 2, 2, 2, 2, 2, 1, ...`

Which is more easily understandable in this format:

```
      1 2 1
    1 2 2 2 1
  1 2 2 2 2 2 1
1 2 2 2 2 2 2 2 1 ...

```

Another way to think of it is, this sequence is the concatenation of blocks \\$b\_i, 0 \leq i\\$ where block \\$b\_i\\$ is a `1`, followed by \\$2i + 1\\$ `2`s, followed by another `1`.

# Input

If your program takes input, the input is a non-negative integer `n`, telling you how far you should go in computing the sequence.

The sequence can

* be 0-indexed, so that \\$s\_0 = 1, s\_1 = 2, s\_2 = 1, ... \\$
* be 1-indexed, so that \\$s\_1 = 1, s\_2 = 2, s\_3 = 1, ... \\$

# Output

Your code may do one of the following:

* indefinitely print the sequence
* print/return the term `n` as given by the input
* print/return all the terms up to the term `n` as given by the input

# Test cases

(the test cases are 0-indexed)

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

```

---

This is so the shortest submission in bytes, wins! If you liked this challenge, consider upvoting it... And happy golfing!

# Answer
# JavaScript (ES7),  ~~25 24~~  23 bytes

Returns the \\$n\\$-th term, 1-indexed.

```
n=>n>(++n**.5|0)**2?2:1

```

Try it online!

### How?

We have \\$a(n)=2\\$ iff the difference between \\$n+1\\$ and the previous square is greater than \\$1\\$:

$$n+1-\left\lfloor \sqrt{n+1}\right\rfloor^2\>1$$

which boils down to:

$$n\>\left\lfloor \sqrt{n+1}\right\rfloor^2$$
> 9 votes

# Answer
# Jelly, 6 bytes

```
,‘Æ²E‘

```

Try it online!

# Explanation

```
,‘Æ²E‘  Main Link:                  N
,       pair with
 ‘                increment         [N, N + 1]
  Æ²    is it a square?             [issq(N), issq(N + 1)]
    E   are both equal (N and N+1 cannot both be square, so if one is square, it will return 0, and if both are not square, it will return 1)
     ‘  increment (if N or N+1 is square, return 1; otherwise, return 2)
        (implicit input)

```
> 7 votes

# Answer
# Python 2, 24 bytes

```
lambda n:2-(-n%n**.5<.5)

```

Try it online!

Outputs the \\$n\\$'th value one-indexed.

We use an arithmetic expression to identify indices `n` that are either perfect square or one below a perfect square. To do so, we use a measure that's roughly of the distance between `n` and the next perfect square, given by `-n%n**.5`.

For squares, we have `-n%n**.5==0` because `n` is an even multiple of its square root, that is for `n=k*k`, `-(k*k)%k==0`. If `n` is one less than a perfect square, then the remainder is `<0.5`, if it's two less, it's be between `0.5` and `1`, and so on. So, the condition `-n%n**.50.5` accepts only perfect squares and numbers one less.
> 7 votes

# Answer
# Python 3.8 (pre-release), 31 bytes

```
i=0
while i:=100*i+121:print(i)

```

Try it online!

Print the sequence infinitely, with a questionable format.

The following version output the first `n` terms of the sequence:

### Python 3, 56 bytes

```
lambda n:"".join(f"{1:2<{-~i*2}}1"for i in range(n))[:n]

```

Try it online!

**Input**: Non-negative integer `n`

**Output**: the first `n` terms of the sequence, concatenated into a string.

**Explanation**

A different approach using only string formatting instead of @Arnauld's closed-form formula.

* `f"{1:2<{x}}1"` evaluates to `"122..21"` with `x-1` characters `"2"`. (The first `"1"` is left justified to a block of width `x`, with `"2"` being the fill character).
* `-~i*2` is equivalent to `(i+1)*2`

Thus `f"{1:2<{-~i*2}}1"` evaluates to the string `"122..21"` with `i*2+1` characters `"2"`.
> 6 votes

# Answer
# , ~~27~~ 25 bytes

-1 byte thanks to Giuseppe

```
1+all((scan()+1:2)^.5%%1)

```

Try it online!

Uses the fact that \\$s\_n=1\\$ iff \\$n+1\\$ or \\$n+2\\$ is a perfect square.
> 4 votes

# Answer
# Symja, ~~38~~ 33 bytes

```
f(x_):=If(Mod(-(x^.5),1)*x<1,1,2)

```

Y'all can try it here

This is just a port of xnor's (who helped me save 5 bytes) Python 2 answer in Symja. This took a while to generate, as I had to properly understand what the formula was, due to operator precedence. Anyhow, enjoy!
> 4 votes

# Answer
# Python 2: 52 bytes

```
def g(n):return(2,1)[not((n+1)**.5%1and(n+2)**.5%1)]

```

Try it online!

Returns the nth term in the sequence. Also using the fact that the nth term = 1 \<=\> (n+1) or (n+2) is square as Robin Ryder pointed out.
> 3 votes

# Answer
# APL (Dyalog Unicode), 67 bytes

This answer returns the entire sequence up to the requested value.

```
f←{(⊃,/1,¨⌽¨1,¨2⍴⍨¨1+2×1-⍨⍳1+⌈⍟⍵)[⍳⍵]}

```

Try it online!

Decomposition/Explanation:

```
f←                                     ⍝ assign the name f to
  {                                  } ⍝ a dfn that takes a single argument
                              ⍟⍵       ⍝ The natural logarithm of the argument,
                             ⌈         ⍝ rounded up to the next integer,
                           1+          ⍝ and add 1 (giving N), then
                          ⍳            ⍝ generate the sequence 1..N,
                       1-⍨             ⍝ and subtract 1 from each term (0..N-1)...
                                       ⍝    ⍨ means to swap the arguments to
                                       ⍝    - (the standard subtraction function), so
                                       ⍝    1-⍨N is the same as N-1.
                     2×                ⍝ ... then multiply each term in the sequence by 2,
                   1+                  ⍝ and add 1
                  ¨                    ⍝ then take each term in the sequence, and
               2⍴⍨                     ⍝ generate a vector of that many 2s
                                       ⍝    ⍨ means to swap the arguments to
                                       ⍝    ⍴ the "shape" function. For simple numeric
                                       ⍝    values of A and B, A⍴B means to generate a
                                       ⍝    vector of A repeats of B.
                                       ⍝ We now have a vector of vectors of 2s.
              ¨                        ⍝ For each of those vectors,
            1,                         ⍝ prepend a 1, then
           ¨                           ⍝ for each vector,
          ⌽                            ⍝ reverse it (so that the 1 is on the 'back end'), then
       1,¨                             ⍝ for each (now reversed with a 1) vector, prepend a 1, and
     ,/                                ⍝ concatenate all the vectors. For reasons I don't quite
                                       ⍝    understand, this generates an enclosed object, so
    ⊃                                  ⍝ unenclose (disclose) it into a 'real' vector, and
   (                            )      ⍝ treat all that as an object...
                                 [  ]  ⍝ ...which can be subscripted. If the subscript is
                                       ⍝    a single integer, it will return just that item from
                                       ⍝    the array; if it's a vector, it will return all of the
                                       ⍝    requested values, in the order specified by the vector.
                                  ⍳⍵   ⍝ This subscript is a vector, of the integers 1 to the original
                                       ⍝    argument to the function, so it will generate the entire
                                       ⍝    sequence up to the ⍵th term. If I only wanted the single
                                       ⍝    term, I would omit the ⍳, which would give me only the ⍵th term.

```

FIRST GOLFING (courtesy ngn):

# APL (Dyalog Unicode), 65 bytes

```
f←{⍵↑(⊃,/1,¨⌽¨1,¨2⍴⍨¨1+2×1-⍨⍳1+⌈⍟⍵)}

```

Try it online!

Explanation of golfing:

```
[⍳⍵] is the same as [1 2 3 4 5 6 ... ⍵],
      which is the first ⍵ items of the vector being subscripted.
      That's the same as
⍵↑    "Take" the first ⍵ items.  Savings, 2bytes.

```

SECOND GOLFING (my own discovery):

# APL (Dyalog Unicode), 63 bytes

```
f←{⍵↑⊃,/1,¨⌽¨1,¨2⍴⍨¨1+2×1-⍨⍳1+⌈⍟⍵}

```

Try it online!

Explanation of golfing: The expression that was formerly subscripted does not need to be parenthesized if using `⍵↑` instead of `[⍳⍵]`. Savings, 2bytes.
> 3 votes

# Answer
# PowerShell, 23 bytes

```
for(){$i++;1;,2*$i++;1}

```

Try it online!

Prints the sequence indefinitely.
> 3 votes

# Answer
# Perl 6, ~~28~~ 27 bytes

```
{flat (1,2,2 xx$++*2,1)xx*}

```

Try it online!

Anonymous codeblock returning a lazy infinite list. I wish I could do `2 xx++$++` or some combination of it, but i can't figure it out.
> 3 votes

# Answer
# GolfScript, 16 bytes

Port of Surculose Sputum's Python answer.

```
0{100*121+.p.}do

```

Try it online!
> 3 votes

# Answer
# Python 3, 37 bytes

```
i=1
while 1:print('1'+'2'*i+'1');i+=2

```

Try it online!
> 3 votes

# Answer
# Husk, ~~14 12~~ 10 bytes

```
ṁ`Jḋ3MRİ12

```

Try it online!

Infinite list.

-1 byte from Dominic Van Essen.

-2 bytes from Zgarb using voodoo magic.
> 3 votes

# Answer
# C (gcc), 56 bytes

```
i,c;main(){main(i--<-2?i=c+=2:putchar(49+(c+~i&&i+3)));}

```

*-1 byte thanks to RGS!*
*-8 bytes thanks to ceilingcat!*

Try it online!

# C (gcc), 46 bytes

```
i;f(n){for(i=0;n--;)printf("%d",i=i*100+121);}

```

Stretches the rules and only works up to \\$n=4\\$.

Try it online!
> 2 votes

# Answer
# Wolfram Language (Mathematica), 42 bytes

```
If[#==1||(d=NumberQ@*Sqrt)@#||d[#+1],1,2]&

```

returns 1 if n=1 or n is a perfect square or n+1 is a perfect square

Try it online!
> 2 votes

# Answer
# 05AB1E, 6 bytes

```
>‚Å²Ë>

```

Port of *@HyperNeutrino*'s Jelly answer, so make sure to upvote him!

Outputs the result for the 1-based input \\$n\\$.

Try it online or verify all the first \\$n\\$ outputs.

Printing the infinite sequence is **~~9~~ 8 bytes** (based on the 6-byter above):

```
∞ü‚Å²€Ë>

```

Try it online.

Previous **9 bytes** variations for the infinite sequence:

**Explanation:**

```
>         # Increase the (implicit) input-integer by 1
 ‚        # Pair it with the (implicit) input-integer: [input, input+1]
  Å²      # Check for both whether they're a square (which will be either both falsey,
          # or just one of the two is truthy)
    Ë     # Check if both are equal (so both falsey) (1 if truhy; 0 if falsey)
     >    # And increase that by 1 (2 if truthy; 1 if falsey)
          # (after which the result is output implicitly)

∞         # Push an infinite positive list: [1,2,3,...]
 ü‚       #  Pair each overlapping pair together: [[1,2],[2,3],[3,4],...]
   Å²     # Check for each whether it's a square
     €Ë   # Check for each pair whether they're equal
       >  # Increase it by 1
          # (after which it is output implicitly as result)

 ∞        # Push an infinite positive list: [1,2,3,...]
Y и       # Repeat a 2 that many times as list: [[2],[2,2],[2,2,2],...]
    δ     # For each inner list:
   X š    #  Prepend a 1: [[1,2],[1,2,2],[1,2,2,2],...]
      €   # For each inner list:
       û  # Palindromize it: [[1,2,1],[1,2,2,2,1],[1,2,2,2,2,2,1],...]
        ˜ # Flatten the list of lists: [1,2,1,1,2,2,2,1,1,2,2,2,2,2,1,...]
          # (after which it is output implicitly as result)

ÅÉ        # Push all odd numbers equal to or less than the given argument,
          # which will be an infinite sequence without argument: [1,3,5,...]
  Å2      # Create for each value a list with that many 2s: [[2],[2,2,2],[2,2,2,2,2],...]
     δ    # For each inner list:
    X .ø  #  Surround it with 1s: [[1,2,1],[1,2,2,2,1],[1,2,2,2,2,2,1],...]
        ˜ # Flatten the list of lists: [1,2,1,1,2,2,2,1,1,2,2,2,2,2,1,...]
          # (after which it is output implicitly as result)

```
> 2 votes

# Answer
# Charcoal, 11 bytes

```
↷²1Ｗ¹«2Ｐ1Ｄ2

```

Try it online! Link is to verbose version of code. Prints the infinite sequence. Explanation:

```
↷²

```

Change the default direction to downwards, so that everything now prints vertically by default.

```
1

```

Output `1` to the canvas.

```
Ｗ¹«

```

Loop forever.

```
2

```

Output `2` to the canvas.

```
Ｐ1

```

Output `1` to the canvas, but don't move the cursor.

Copy the canvas to STDOUT.

```
2

```

Replace the `1` with a `2`.
> 2 votes

# Answer
# dc, 18 bytes

```
?d2+vd*rvd*-d/2r-p

```

Try it online!

This uses 0-based indexing, and it computes the *n*th value in the sequence for index *n*. Input is on stdin, and output is on stdout.

It computes $$2 -K\_{\neq0}\big(\lfloor{\sqrt{n+2}}\rfloor-\lfloor{\sqrt{n}}\rfloor\big),$$ where \\$K\_{\neq0}\\$ is the function that maps 0 to 0, and any non-zero number to 1. (\\$K\_{\neq0}\\$ isn't built into dc, but you can compute it by dividing a number by itself, as long as you're careful with the stack when its argument is 0.)

There may be spurious output on stderr (due to division by 0).

Here's a TIO link to the test suite.
> 2 votes

# Answer
# , 7 bytes

The long length doesn't really matter to me. W doesn't have a square-checking built-in.

```
φßéW!r♀

```

Uncompressed:

```
){Q1m!=r)

```

## Explanation

```
)         % Increment the input. [input + 1]
 {        % Pair with the input. [input, input + 1]
  Q       % Find the square root.[sqrt(input), sqrt(input + 1)]
   1m     % Modulo 1. (Find the digits after the decimal point.)
     !    % Are the digits 0? (True, it's a square number. Otherwise,
          % it can't be a square number.)
      =r  % Reduce by equality.
        ) % Increment the result.

```
> 2 votes

# Answer
# PowerShell, 55 bytes

```
$i=0;1.."$args"|%{$i+=2;write-host "1,$('2,'*$i)1," -n}

```

Try it online!
> 2 votes

# Answer
# C (clang), ~~80~~ 75 bytes

```
j,k=1;main(int a,char**b){for(a=atoi(b[1]);j<a;k+=2,j+=k);return(1<j-a)+1;}

```

Try it online!

This one takes an input N at the terminal and returns the Nth value. This is zero-indexed.

# C (gcc), ~~48~~ 44 bytes

```
j,k=1;f(a){for(;j<a;k+=2,j+=k);a=(1<j-a)+1;}

```

Try it online!

Same basic function here, but modified to just be a function to not take the hit from main's arg-list and converting a string to an integer. Switched over to GCC to take advantage of undefined behavior that avoids need for explicit return.
> 2 votes

# Answer
# MAWP 0.0, 16 bytes

```
[1:![2:1A]%1:2M]

```
> 2 votes

# Answer
# Python 3, ~~39~~ 34 bytes

```
i=1
while 1:print(1,*[2]*i,1);i+=2

```

Prints the sequence infinitely. Thanks to @SurculoseSputum for saving me 5 bytes.

Try it online!
> 1 votes

# Answer
# Bash, ~~64~~ ~~61~~ 41 bytes

Saved 20 bytes thanks to S.S. Anne!!!

```
s=2;while :;do echo 1 $s 1;s+=' 2 2';done

```

Try it online!

Infinitely prints the sequence.
> 1 votes

# Answer
# C (gcc) -lm, ~~57~~ \\$\cdots\\$ ~~52~~ 50 bytes

Saved 2 bytes thanks to ceilingcat!!!

```
t;s(n){t=sqrt(n);n=n!=t*t;};f(n){n=1+s(n)*s(n+1);}

```

Try it online!

Returns the nth term in the sequence.
> 1 votes

# Answer
# Brainfuck, 72

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

```

Might be able to make it shorter but here's my shot. Prints indefinetly

1. Initialize first two cells with (ASCII values for) 1 and 2
2. Start a loop (looping on the 2 cell but it doesn't really matter)
    1. Print the 1
    2. Increase the count, and then copy the count to the next two cells
    3. Use one of the counts to print the twos (decreases the count until 0, then exits loop)
    4. Copy the second copy of the count back to where it was before
    5. Print a final 1
> 1 votes

# Answer
# Perl 5, 35 + 1 (-p) = 36 bytes

```
$_=(map{(1,2,(2,2)x$_,1)}0..$_)[$_]

```

Try it online!

Reads input `n` from stdin. Simplisticly builds a list of the first at least `n` elements (actually the first `2n+3` elements), then prints the `n`th element.

# Perl 5, 30 + 1 (-p) = 31 bytes

```
$_=$_+1>(($_+2)**0.5|0)**2?2:1

```

Smarter and more efficient way of doing it with Arnauld's formula from above (but adjusted to be 0-indexed instead of 1-indexed, because that's how I like it).

Try it online!
> 1 votes

# Answer
# dirt (verbose mode), 17 bytes

```
"1
2
1"|1"
2
2".*

```

Run as `dirt ones_and_twos.dirt -v -i ""`

Outputs each element of the sequence on a new line.

Alternatively, if we allow new lines between some but not all elements,

## dirt (verbose mode), questionable format, 13 bytes

```
"121"|1"22".*

```

prints

```
121
12221
1222221
122222221
12222222221
1222222222221
122222222222221
12222222222222221
...

```
> 1 votes

# Answer
# cQuents, 21 bytes

```
_+(Tr$)%1)=Tr_+$)%1))

```

Try it online!

Port of the jelly answer.

## Explanation

```
    r$)     r_+$)     # Root (defaults to square root)
       %1        %1   # Modulo 1 (only taking the decimal part)
   T     ) T       )  # Ceiling (round up if there is a decimal part)
  (       =         ) # Equal (same as jelly answer)
_+                    # Successor (same as jelly answer)

```

# List output, 15 bytes

```
1,D2)*_-(k*2),1

```

Try it online!

Playing with the output a bit, we can golf off 6 bytes.

Instead of outputting `1,2,2,2,1`, it outputs `1,[2,2,2],1`.

## Explanation

```
1,              # A one
  D2)           # Digits of 2 (which is of course, just 2)
     *_-(k*2)   # Multiplied by k*2-1 (it's multiplying a list)
             ,1 # Another one

```
> 1 votes

# Answer
# Haskell, 36 bytes

```
do n<-[0..];'1':([1..n]>>"22")++"21"

```

Try it online!

This expression evaluates to an infinite string.
> 1 votes

# Answer
# APL+WIN, 31 bytes

Prompts for integer. Index origin=1
Returns single term of the series.

```
2 1[1++/m=1,(n+1),n←+\1+2×⍳m←⎕]

```

Try it online! Courtesy of Dyalog Classic
> 0 votes

# Answer
## Haskell, 51 Bytes

`f n=concat['1':['2'|x<-[0..y*2]]++"1"|y<-[0..n]]!!n`
> 0 votes

# Answer
# Wolfram Language (Mathematica), 26 bytes

```
Count[√#+√(#+1),_@__]&

```

Try it online!

1-indexed.

```
√#+√(#+1)           (* sqrt(n)+sqrt(n+1) *)
Count[ % ,_@__]     (* count nonatomic subexpressions at the first level. *)

```
> 0 votes

# Answer
# Haskell, 31 bytes

```
do n<-[1..];show$div(100^n)9*11

```

Try it online!

**32 bytes**

```
show=<<iterate(\x->x*100+121)121

```

Try it online!
> 0 votes

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


# Question
Title: This highway needs rain across both of its lanes
In this challenge you will take a an ascii art image of a highway like so

```
 |   |   |  |  |  |
 |       |  |     |
 |   |   |  |  |  |
 |       |  |     |
 |   |   |  |  |  |
 |       |  |     |
 |   |   |  |  |  |

```

And you need to put rain across its lanes like so

```
 |\\\|\\\|  |\\|\\|
 |\\\\\\\|  |\\\\\|
 |\\\|\\\|  |\\|\\|
 |\\\\\\\|  |\\\\\|
 |\\\|\\\|  |\\|\\|
 |\\\\\\\|  |\\\\\|
 |\\\|\\\|  |\\|\\|

```

---

A highway will be defined as an ascii art string containing only the characters `|`,  and newlines. All rows of the image will have exactly the same number of characters. Every column will be one of the following

* **Empty space**, all spaces
* **A line**, all `|`
* **A lane divider**, alternating `|` and space

Furthermore there will always be a line before and after every lane divider. So

```
|    |   | |   |
|          |   |
|    |   | |   |

```

would be valid but

```
|     |     |
|  |  |
|     |     |

```

would not be since there is no line after the last lane divider.

And a lane divider will never be exactly next to a line. So

```
||   |
|    |
||   |

```

Is invalid but

```
|   ||  ||
|     | ||
|   ||  ||
|     | ||
|   ||  ||

```

is fine.

Additionally a highway must be at least two rows high and one column wide.

## Task

Your job is to write a program or function that takes a valid highway (as a string or list of lines) as input and outputs the highway with rain across its lanes.

To put rain across a highway's lanes you must replace all space characters that appear between two consecutive lines, where those lines have at least one lane divider between them, with `\`s. And leave all other characters the same.

So in the following diagram:

```
A   B   C   1   2  D
|   |   |       |  |
|   |   |   |      |
|   |   |       |  |
|   |   |   |      |

```

No rain should be put between `A` and `B` or `B` and `C` since there are no lane dividers between them, but rain should be put between `C` and `D` since lane dividers `1` and `2` are between them.

You may output an additional trailing newline, or add/remove trailing spaces from all lines equally if you wish.

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

## Test cases

Simple case

```
 |   |   |  |  |  |
 |       |  |     |
 |   |   |  |  |  |
 |       |  |     |
 |   |   |  |  |  |
 |       |  |     |
 |   |   |  |  |  |

```

---

```
 |\\\|\\\|  |\\|\\|
 |\\\\\\\|  |\\\\\|
 |\\\|\\\|  |\\|\\|
 |\\\\\\\|  |\\\\\|
 |\\\|\\\|  |\\|\\|
 |\\\\\\\|  |\\\\\|
 |\\\|\\\|  |\\|\\|

```

---

Extra line

```
|    |   | |   |
|          |   |
|    |   | |   |

```

---

```
|\\\\|\\\|\|   |
|\\\\\\\\\\|   |
|\\\\|\\\|\|   |

```

---

Unsynced lane dividers

```
   |    |      |
   |        |  |
   |    |      |
   |        |  |
   |    |      |

```

---

```
   |\\\\|\\\\\\|
   |\\\\\\\\|\\|
   |\\\\|\\\\\\|
   |\\\\\\\\|\\|
   |\\\\|\\\\\\|

```

---

Empty road

```
|   |   |       |  |
|   |   |   |      |
|   |   |       |  |
|   |   |   |      |

```

---

```
|   |   |\\\\\\\|\\|
|   |   |\\\|\\\\\\|
|   |   |\\\\\\\|\\|
|   |   |\\\|\\\\\\|

```

---

False roads (suggested by Arnauld)

```
|   | | |   |
|   |   |   |
|   | | |   |
|   |   |   |

```

---

```
|   |\|\|   |
|   |\\\|   |
|   |\|\|   |
|   |\\\|   |

```

---

Hard lane divider

```
|  |  |  |  |
|     |     |
|  |  |  |  |
|     |     |

```

---

```
|\\|\\|\\|\\|
|\\\\\|\\\\\|
|\\|\\|\\|\\|
|\\\\\|\\\\\|

```

---

Adjacent lane dividers

```
|   ||  ||
|     | ||
|   ||  ||
|     | ||
|   ||  ||

```

---

```
|\\\||\\||
|\\\\\|\||
|\\\||\\||
|\\\\\|\||
|\\\||\\||

```

---

No lanes

```
|    |     |  |
|    |     |  |
|    |     |  |

```

---

```
|    |     |  |
|    |     |  |
|    |     |  |

```

---

One line

```
       |
       |
       |

```

---

```
       |
       |
       |

```

---

No lines

```

```

---

```

```

# Answer
# Jelly,  ~~18~~  16 bytes

```
ZḢ”\E?€ṣ”|»Ṁ$€K»

```

A monadic Link accepting a list of lines, each of which is a list of characters, which yields another, similar list.

**Try it online!** Or see the test-suite.

### How?

```
ZḢ”\E?€ṣ”|»Ṁ$€K» - Link: list of lists of characters (i.e. rows of text)
Z                - transpose - i.e. columns (each being: all spaces; all pipes; or a mix)
      €          - for each (column):
     ?           -   if...
    E            -   ...condition: all equal? - i.e. if not dashed
 Ḣ               -   ...then: head - i.e. the unique character
  ”\             -   ...else: literal '\' character
        ”|       - literal '|' character
       ṣ         - split at - i.e. highway chunks now contain spaces and '\' characters
             €   - for each (chunk):
            $    -   last two links as a monad:
           Ṁ     -     maximum - N.B. '\' > ' '
          »      -     maximum (vectorises across the chunk)
                 -   - i.e highway chunks become all '\', others remain as is
              K  - join with space characters
               » - maximum (vectorises across the rows)
                 -   - N.B. '|' > ' ' so the solid lines are not replaced by spaces; and
                 -          '|' > '\' so the dashed lines are not replaced with rain.

```
> 8 votes

# Answer
# JavaScript (ES6),  ~~118 ... 105~~  103 bytes

I/O format: matrix of characters.

```
a=>a.map(r=>r.map((c,i)=>(a[k=0][i]+a[1][i]<'||'?r:r=a.some(r=>r[a[k^=1].indexOf(c,i+1)]<c))/c?'\\':c))

```

Try it online!

### How?

To detect lines, we test whether the first and the second row both contain a `|` at a given position \\$i\\$:

```
a[0][i] + a[1][i] < '||'  // true if it's not a line

```

When a line is detected:

* We know for sure that the character \\$c\\$ at the same position in the current row is a `|`, because lines are guaranteed to go all the way from top to bottom. So we can now use \\$c\\$ instead of `'|'`.
* We update the flag \\$r\\$ which is set to \\$1\\$ when we're located on a road with a lane divider.

We update \\$r\\$ by testing if, for some \\$n\\$, the next `|` (starting from \\$i+1\\$) in either the first or the second row (depending on the parity of \\$n\\$) is facing a space in the \\$n\\$-th row:

```
r = a.some(r => r[a[k ^= 1].indexOf(c, i + 1)] < c  // starting with k = 0

```

Finally, we must replace \\$c\\$ with a `\` if \\$c\\$ is a space and \\$r=1\\$. Because a space is the only road character that is coerced to \\$0\\$, we can simply do:

```
r / c

```

The only truthy value is given by `1/' '` (\\$+\infty\\$). Something like `1/'|'` would result in `NaN`, and so does `0/' '` (\\$0/0\\$).
> 6 votes

# Answer
# 05AB1E, 20 bytes

```
₆F€SøíJ„ \S„\|N_èì`:

```

Try it online!

```
₆F                    # repeat the following 36 times:
  €SøíJ               #  rotate 90 degrees
       „ \S           #  character array [' ', '\']
           „\|        #  string "\|"
              N       #  0-based iteration count
               _      #  logical not: 0 => 1, anything else => 0
                è     #  use that to index in the string "\|"
                 ì    #  prepend (first loop: ["| ", "|\"], then ["\ ", "\\"])
                  `:  #  recursive replace ("| " => "|\" or "\ " => "\\")

```
> 5 votes

# Answer
# Python 3, ~~198~~ ~~196~~ ~~186~~ 159 bytes

```
def g(x):
 for _ in x[0]:x=[''.join([q,'\\'][q<'!'and(x[a-1][b]>'['or'\\'in r[b-1]+r[-~b%len(r)])]for(b,q)in enumerate(x[a]))for(a,r)in enumerate(x)]
 return x

```

Try it online!

## Explanation

This implements a simple automaton. At every step a space is replaced with an `\` iff one of the following is true

* There is a `|` or `\` above it (indexing wraps around)
* There is `\` to the left or right of it.

This means that rain starts at the gaps in the lane dividers and spreads until it hits `|`s.
> 5 votes

# Answer
# Perl 5 `-p`, ~~52~~ 51 bytes

```
/
/;s/(\S(.{@{-}})|\\)\K | (?=(?2)\S|\\)/\\/s&&redo

```

Replace space character with a backslash if there is a non-space character above or below it or a backslash on the right or the left of it. And redo while no more space can be replaced.

One byte saved diverting recursive regex thanks to Grimmy.

Try it online!
> 5 votes

# Answer
# Python 2, ~~112~~ ~~109~~ 107 bytes

```
lambda r:reduce(lambda r,c:[''.join(l[::-1]).replace(c+' ',c+'\\')for l in zip(*r)],r'|\|\\\\:'*len(`r`),r)

```

Try it online!

## Python 3.8 (pre-release), 109 bytes

*Thanks to Kevin Cruijssen for this version!*

```
lambda r:[(r:=[''.join(l[::-1]).replace(c+' ',c+'\\')for l in zip(*r)])for c in r'|\|\\\\:'*len(repr(r))][-1]

```

Try it online!

Port of my 05AB1E answer.
> 4 votes

# Answer
# Jelly, 25 bytes

```
n⁶Zṣ1€oFẸḤƊ$€j1€W$Zị“|\ ”

```

Try it online!

`oFẸḤƊ$€` is "borrowed" from @Riolku lol go upvote him

# Explanation

```
n⁶Zṣ1€oFẸḤƊ$€j1€W$Zị“|\ ”  Main Link
n⁶                         vectorized inequality to space; "|" becomes 1, " " becomes 0
  Z                        transpose into a list of columns
   ṣ1€                     split by [1, 1, ..., 1] (length of original; number of rows)
            €              for each block (space between two lines)
      o                    vectorized OR with
       FẸḤ                 (flatten) (any) (double): 0 if there are only spaces; 2 if there are lane dividers
             j             join on
              1€W$         [1, 1, ..., 1] wrapped ([[1, 1, ..., 1]])
                  Z        zip back into original orientation
                   ị“|\ ”  index into "|\ "; 0s are spaces, 1s are lines, and 2s are the replaced spaces which become \

```
> 4 votes

# Answer
# Haskell, 151 bytes

```
a#b=a!!mod b(length a)
z=zip[0..]
s%_=[[(['\\'|b<'!'&&(s#(x-1)#y>'['||elem '\\'[a#(y-1),a#(y+1)])]++[b])!!0|(y,b)<-z a]|(x,a)<-z s]
g x=foldl(%)x(x!!0)

```

Try it online!

## Explanation

This implements the same algorithm as my python answer. It implements a simple automaton. At every step a space is replaced with an `\` iff at least one of the following is true

* There is a `|` or `\` above it (indexing wraps around)
* There is `\` to the left or right of it.

This means that rain starts at the gaps in the lane dividers and spreads until it hits `|`s.
> 4 votes

# Answer
# Jelly, 25 bytes

```
Zn⁶ṣoFẸḤƊ$€jW}
ç1€ị“|\ ”Z

```

Try it online!

I/O is a list of strings

# Explanation

```
Zn⁶ṣoFẸḤƊ$€jW}   Primary Link (dyad); takes the input on the left and [1, 1, ..., 1] on the right
Z                zip the input into a list of columns
 n⁶              vectorized inequality to space; "|" becomes 1, " " becomes 0
   ṣ             split (on [1, 1, ..., 1])
          €      for each block (between lines)
    o            vectorized or with
     FẸḤ         (flatten) (any) (double): 0 if there are only spaces; 2 if there are lane dividers
           jW}   join on ([1, 1, ..., 1] wrapped) (2,2-chain using })
ç1€ị“|\ ”Z       Main Link
ç                call the primary link with (default left argument),
 1€              [1, 1, ..., 1]
   ị“|\ ”        index into "|\ "
         Z       zip back into original orientation

```
> 4 votes

# Answer
# Retina 0.8.2, 79 bytes

```
+m`(?<=(.)+) ((?<=(?(1).)^(?<-1>.)+\S.*¶.+|\\ )|(?=\\|.*¶(?<-1>.)+(?(1)$)\S))
\

```

Try it online! Same flood fill approach that @WheatWizard uses in his answers but using .NET balancing groups to detect vertical matches. Would save two bytes if the wind was blowing the other direction. Explanation:

```
+m`

```

Repeatedly replace and turn on line detection.

```
(?<=(.)+)

```

Replace a space but count the number of preceding characters on that line.

```
((?<=...|...)|(?=...|...)))
\

```

Replace with a backslash if one of the four conditions is true.

The four conditions are:

```
(?(1).)^(?<-1>.)+\S.*¶.+

```

This space is below rain or a lane divider. The `(?(1).)` can only succeed if the characters are in the same column.

```
\\

```

This space is to the right of existing rain.

```
\\

```

This space is to the left of existing rain.

```
.*¶(?<-1>.)+(?(1)$)\S

```

This space is above rain or a lane divider. The `(?(1)$)` can only succeed if the characters are in the same column.
> 3 votes

# Answer
# Ruby, 144 bytes

```
->s{s.map{|l|((r=s[0]).size.times.map{|i|r[i]!=s[1][i]?[r.rindex(?|,i-1),r.index(?|,i+1)]:p}-[p]).map{|a,b|a.upto(b){|i|l[i]=?\\if l[i]<?!}};l}}

```

Try it online!

I thought I would try a different approach to the automaton. This finds lane dividers by checking for which indices the first two rows differ. It then goes through each of these indices and finds the previous and next line. It then fills in all space characters with the rain character.

This takes a list of strings for each row of the road.

### Golfy Tricks:

* Using `l[i]<?!` instead of `l[i]==" "`. This checks to see whether the character comes before `!` (which only space does of the allowed charactersin this challenge).
* `-[p]` to remove all `nil` elements in an array.
* `map` instead of `each`.
* `size.times` instead of `chars.each_index`
* Using `map` with a condition (where failures result in `nil` and `nil`s are then removed), rather than a `select` followed by a `map`.

### Explanation:

```
->s{s.map{|l|((r=s[0]).size.times.map{|i|r[i]!=s[1][i]?[r.rindex(?|,i-1),r.index(?|,i+1)]:p}-[p]).map{|a,b|a.upto(b){|i|l[i]=?\\if l[i]<?!}};l}}

# Go through each character in the first row (saving the row in a variable for later use)
             ((r=s[0]).size.times.map
# Check if it's a line divider
                                         r[i]!=s[1][i]
# If it is, save the nearest road lines
                                                       [r.rindex(?|,i-1),r.index(?|,i+1)]
# If it isn't save nil
                                                                                p
# Remove all the nils
                                                                                -[p]
# So we have all the indices of the lanes
             ((r=s[0]).size.times.map{|i|r[i]!=s[1][i]?[r.rindex(?|,i-1),r.index(?|,i+1)]:p}-[p])
# For each row in the road
->s{s.map{|l|
# Go through each index within the lane
                                                                                .map{|a,b|a.upto(b)
# And set any empty charaters to rain
                                                                                l[i]=?\\if l[i]<?!
# And then return the new rainy row
                                                                                l

```
> 2 votes

# Answer
# Bash \+ Core utilities, ~~154~~ ~~152~~ ~~145~~ ~~142~~ ~~136~~ 119 bytes

```
IFS=\

read t
d=`sed s/././g<<<$t`
sed -E ":l;s/([|%]$d|%) /\1%/;tl;s/ ($d[|%]|%)/%\1/;tl;"'y/%@/\\\
/'<<<$t@`tr '
' @`

```

Try it online!

Input on stdin, and output on stdout.

(The script has spurious output to stderr in one case, but that's considered acceptable.)

Here are the outputs for the test cases:

```
highway-1-simple
 |\\\|\\\|  |\\|\\|
 |\\\\\\\|  |\\\\\|
 |\\\|\\\|  |\\|\\|
 |\\\\\\\|  |\\\\\|
 |\\\|\\\|  |\\|\\|
 |\\\\\\\|  |\\\\\|
 |\\\|\\\|  |\\|\\|

highway-2-extraline
|\\\\|\\\|\|   |
|\\\\\\\\\\|   |
|\\\\|\\\|\|   |

highway-3-unsyncedlanedividers
   |\\\\|\\\\\\|
   |\\\\\\\\|\\|
   |\\\\|\\\\\\|
   |\\\\\\\\|\\|
   |\\\\|\\\\\\|

highway-4-emptyroad
|   |   |\\\\\\\|\\|
|   |   |\\\|\\\\\\|
|   |   |\\\\\\\|\\|
|   |   |\\\|\\\\\\|

highway-5-falseroads
|   |\|\|   |
|   |\\\|   |
|   |\|\|   |
|   |\\\|   |

highway-6-hardlanedivider
|\\|\\|\\|\\|
|\\\\\|\\\\\|
|\\|\\|\\|\\|
|\\\\\|\\\\\|

highway-7-adjacentlanedividers
|\\\||\\||
|\\\\\|\||
|\\\||\\||
|\\\\\|\||
|\\\||\\||

highway-8-nolanes
|    |     |  |
|    |     |  |
|    |     |  |

highway-9-oneline
       |
       |
       |

highway-A-nolines

```
> 2 votes

# Answer
# Husk, ~~21~~ ~~20~~ 15 bytes

<sup>*-5 bytes thanks to Zgarb!*</sup>

```
Tṁ?mσ' '\IV≠ġ▼T

```

Try it online! Takes input as a list of rows. Works by transposing rows and columns, splitting the columns into groups based on whether they have any spaces, adding rain to the column groups with lane divisions, recombining the column groups, and transposing back.
> 2 votes

# Answer
# Charcoal, 33 bytes

```
ＷＳ⊞υ⪫⪪ι ψＰ⪫υ¶Ｆ⊟υ¿⊖№ＫＤ²↓|ＫＫ«¤\↓¤\↗

```

Try it online! Link is to verbose version of code. Expects rectangular input with newline terminator. Explanation:

```
ＷＳ⊞υ⪫⪪ι ψ

```

Read the input but change spaces into nulls.

```
Ｐ⪫υ¶

```

Copy the input to the output; nulls turn into fillable spaces.

```
Ｆ⊟υ

```

Loop over the width of the input.

```
¿⊖№ＫＤ²↓|

```

Is this a lane divider? It isn't if it doesn't alternate between `|`s and empty cells.

```
ＫＫ

```

If it's not a divider then print the current character thus moving the cursor one step right. Simply moving right doesn't help because this needs to be a two-character Move command to avoid confusion with printing a lambda in a rightwards direction, and negating the condition doesn't help because when there are no lanes then Charcoal prints nulls instead of spaces for some inexplicable reason.

```
«¤\↓¤\↗

```

Fill the area with rain. Both the current cell and the cell below need to be checked as we don't know which one is empty. The cursor is then moved to the right of its original position.
> 1 votes

---
Tags: code-golf, ascii-art
---


title: Geohash my positions

text:
# Question
Title: Geohash my positions
**About geohash**

Geohash is one of many encoding systems for geographic positions. Geohash positions have some advantages. It provides a short code instead of the two usual numbers for latitude and longitude.

**The challenge**

Given two numbers, the latitude and longitude, compute and return or print the geohash string of length 8. A longer geohash would give more accurate positions, here we use length 8. Latitudes and longitudes are given as floating point numbers (degrees). Latitudes are between -90 and +90 (south to north) and longitudes between -180 and +180 (west to east).

**Algorithm with example**

A geohash code is a base32 encoded bitstring. In this example the conversion goes the other way than the challenge, we convert geohash `ezs42` into latitude and longitude. Geohashes uses a set of 32 digits represented by 5 bits. The 32 digits are `0 – 9` for the first 10 and the lower case letters between `b – z` except `i`, `l` and `o` for the next 22. That is: `0123456789bcdefghjkmnpqrstuvwxyz`.

The first char in `ezs42` is e which is at the 0-indexed position 13, which has the 5 bits 01101. The chars have these bits:

* `e` → 13 → *01101*
* `z` → 31 → *11111*
* `s` → 24 → *11000*
* `4` → 4 → *00100*
* `2` → 2 → *00010*

When joining the bits we get *0110111111110000010000010*.

Starting from left, the even bits (2nd, 4th, 6th, ...) are for latitude (*101111001001*) and the odd bits (1st, 3rd, 5th, ...) are for longitude (*0111110000000*).

With each bit we go left or right to narrow down the number by halving the range. The first bit of the longitude bits (`0`) are used to decide if the longitude is between -180 – 0 or 0 – 180. Bit `0` means we go left, that is -180 – 0. The next bit of the longitude decides if we chose -180 – -90 or -90 – 0. Since it's `1` here we go right for the next range: -90 – 0. For every bit we go left(0) or right(1) halving the min-max range. When all bits are spent, we return the mid position (average) of the last min and max.

We repeat for latitude, except now we start at choosing between -90 – 0 and 0 – 90 with the first bit.

The latitude for *101111001001* becomes +42.605.

The longitude for *0111110000000* becomes -5.603.

This example is taken from https://en.wikipedia.org/wiki/Geohash#Algorithm\_and\_example which has a more visual walk-through.

When encoding 0° (equator or zero meridian) you can choose between 01111... and 10000... The http://geohash.co/ site have chosen 01111...

**Test cases**

```
(+48.8583, +2.2945)      → u09tunqu    # Eiffel Tower
(+40.68925, -74.04450)   → dr5r7p62    # Statue of Liberty
(+29.9753, +31.1377)     → stq4s8cf    # The Great Sphinx at Giza
(-22.95191, -43.21044)   → 75cm2txp    # Statue of Christ, Brazil
(+71.17094, +25.78302)   → usdkfsq8    # North Cape
(+90, +180)              → zzzzzzzz    # North Pole
(-90, -180)              → 00000000    # South Pole
(+42.605, -5.603)        → ezs42s00    # Léon, Spain from example above

```

More tests can be created or checked with http://geohash.co/ and Google Maps.

(GPS positions are also often written as degrees, arcminutes and arcseconds. The position of the Eiffel Tower is latitude 48° 51' 29.88" N, longitude 2° 17' 40.20" E. For north (N) and east (E) positive numbers are used so we get position \[48 + 51/60 + 29.88/3600, 2 + 17/60 + 40.20/3600\] = \[+48.8583, +2.2945\]. Geohash codes can be stored and indexed in databases for quick proximity searches. Nearby positions share the same code prefixes, but edge cases needs to be dealt with. A single index search on the geohash code on one or a small set of code prefixes is normally much quicker than using two indexes, i.e. one for latitude and one for longitude.)

# Answer
# Perl 5 (`-ap -MList::Util+sum`), 136 bytes

```
@a=([-90,90],[-180,180]);map{$y=0;$a[--$|][$,=$F[$|]<($m=.5*sum@{$a[$|]})]=$m,$y+=$y+!$,for 0..4;$\.=(0..9,grep!/[ilo]/,b..z)[$y]}0..7}{

```

Try it online!

Verify all test cases
> 4 votes

# Answer
# Python 3, 250 bytes

```
lambda b,a:(lambda l:"".join("0123456789bcdefghjkmnpqrstuvwxyz"[int("".join(map(str,l[i*5:][:5])),2)]for i in range(8)))(sum(zip(f(a,180,-180),f(b,90,-90)),()))
f=lambda a,u,l,p=20:p and([1]+f(a,u,(u+l)/2,p-1)if u+l<a*2else[0]+f(a,(u+l)/2,l,p-1))or[]

```

Try it online!

I think using named functions would probably be better... anyway. I don't have time to golf this further yet, so just posting it here first.
> 5 votes

# Answer
# 05AB1E, ~~64~~ ~~63~~ ~~61~~ ~~42~~ 41 bytes

```
90x‚R/>19o*î<Dd*b20jð0:SÅ=5ôJCžhA«„ŠÙaмsè

```

-19 bytes by porting *@Neil*'s Charcoal answer, so make sure to upvote him as well!
-1 byte by taking the input in reversed order.

Try it online or verify all test cases.

**Original ~~64~~ ~~63~~ ~~61~~ 60 bytes answer:**

```
εd©ˆ¾ƵΔN>÷‚19FÐÆÄ;UÅmyÄ‹®Qˆε¯θ®QNÊiXNi-ë+]¯Å=5ôJCžhA«„ŠÙaмsè

```

Try it online or verify all test cases.

Both take the input as `[longitude, latitude]` and output as a list of characters.

**Explanation:**

```
90                # Push 90
  x               # Double it to 180 (without popping)
   ‚              # Pair them together: [90,180]
    R             # Reverse it: [180,90]
     /            # Divide the (implicit) input-pair by these
      >           # Increase both by 1
       19o        # Push 2^19: 524288
          *       # Multiply both decimals by this 524288
           î      # Ceil both to an integer
            <     # Then decrease them by 1
                  # (ceil + decrement cannot be floor, if they already are integers)
             Dd   # Create a copy, and check if it's >=0 (1 if >=0; 0 if <0)
               *  # Multiply this to the pair (-1 becomes 0, else it stays the same)
b                 # Convert both integers to a binary string
 20j              # Pad them with leading spaces up to a length of 20
    ð0:           # Replace all spaces with 0s
       S          # Convert it to a flattened list of digits
Å=                # Shuffle this list ([a,b,c,d,e,f] → [a,d,b,e,c,f])
  5ô              # Split this into parts of size 5
    J             # Join each inner list together to a string
     C            # Convert each binary string to a base-10 integer
žh                # Push builtin "0123456789"
  A«              # Append the lowercase alphabet
    „ŠÙa          # Push dictionary string "oila"
        м         # Remove those characters from the string
         s        # Swap to get the list of integers at the top again
          è       # And (0-based) index them into the string
                  # (after which the list of characters is output implicitly

```

```
ε                 # Map both values in the pair to:
 d                #  Pop and check if it's non-negative (1 if >=0; 0 if <0)
  ©               #  Store this in variable `®` (without popping)
   ˆ              #  And pop and add it to the global_array
 ¾                #  Push 0
  ƵΔ              #  Push compressed 180
    N             #  Push the 0-based map-index
     >            #  Increase it by 1 to make it 1-based
      ÷           #  Divide the 180 by this (longitude=180; latitude=90)
       ‚          #  Pair it together with the 0
 19F              #  Loop 19 times:
    Ð             #   Triplicate the current pair
     ÆÄ           #   Pop one, and get the absolute difference
       ;          #   Halve this
        U         #   Pop and store this halved difference in variable `X`
     Åm           #   Pop another copy, and take its average
         ‹        #   Check that it's smaller than
       yÄ         #   the absolute value of the current map value
                  #   (1 if truthy; 0 if falsey)
          ®Q      #   Check if this is equal to `®`
                  #   (this will invert the boolean for negative values)
            ˆ     #   Pop and add this to the global_array
     ε            #   Map over the third pair:
      ¯θ          #    Push the last value of the global_array
        ®Q        #    Check it this is equal to `®`
                  #    (to invert for negative values again)
          NÊi     #    If this is NOT equal to the 0-based inner map-index:
             X    #     Push variable `X`
              Ni  #     If the 0-based inner map-index is 1:
                - #      Subtract `X` from the current value we're mapping over
               ë  #     Else:
                + #      Add it instead
]                 # Close both if-statements, both maps, and the loop
 ¯                # Push the global_array
Å=5ôJCžhA«„ŠÙaмsè # Same as above

```

See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress large integers?*) to understand why `„ŠÙa` is `"oila"` and `ƵΔ` is `180`.
> 4 votes

# Answer
# Charcoal, 65 bytes

```
Ｆ²⊞υ⌈×Ｘ²¦¹⁹⊕∕Ｎ×⁹⁰⊕ιＵＭυ◧⎇‹ι²ω⍘⊖ι !²⁰⭆⪪⭆²⁰⭆⮌υ§λι⁵§⁺⭆χλΦβ¬№ailoλ⍘ι !

```

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

```
Ｆ²⊞υ⌈×Ｘ²¦¹⁹⊕∕Ｎ×⁹⁰⊕ι

```

Input both numbers. Divide the first by 90 and the second by 180, then increment both, then multiply by 524288, then round up.

```
ＵＭυ◧⎇‹ι²ω⍘⊖ι !²⁰

```

If the result is greater than 2, then decrement and convert to base 2 using a custom digit set, and pad to 20 "digits". (This doesn't work for 0 because it would become negative and it doesn't work for 1 because of a bug in the version of Charcoal on TIO.)

```
⭆⪪⭆²⁰⭆⮌υ§λι⁵§⁺⭆χλΦβ¬№ailoλ⍘ι !

```

Shuffle the bits, split into groups of five, decode each group from base 2 using the same digit set, then look up the digit in a table of digits and letters excluding `ailo`.
> 3 votes

# Answer
# , ~~149~~ ~~147~~ ~~144~~ 128 bytes

*Edit: -16 bytes thanks to Giuseppe, by using more code-efficient matrix operations (`rbind`, `%*%`)*

```
function(l,m,d=function(x)((x+180)*5825.422)%/%2^(20:1)%%2)c(0:9,letters[-c(1,3:5*3)])[1+2^(4:0)%*%matrix(rbind(d(m),d(l*2)),5)]

```

Try it online!

Outputs vector of characters.

**How?** (before Giuseppe's golfing)

```
geohash=
function(l,m,               # l=latitude, m=longitude
d=function(x)               # d=helper function to calculate bits from lat or long
  ((x+180)*5825.422)        #   scale by 5825.422 == 2^20/180
  %/%2^(20:1)%%2            #   convert to binary bits
)
c(0:9,                      # encode using digits 0..9, joined to
letters[-c(1,9,12,15)])     # letters except a,i,l,o
[1+                         # 1-based indexing
  colSums(                  # sums of each column of matrix
                            # columns represent each 5-bit character
    matrix( ... ,5,8)       # format numbers into matrix with 5 rows & 8 columns
      t(                    # using transpose of
        matrix(             # matrix of
          c(d(m),d(l*2)),,2)# longitude bits, latitude bits x2, in rows
      )
    *2^(4:0))]              # times powers of 2 to convert sums to numbers

```
> 2 votes

# Answer
# Python 3, 174 bytes

```
f=lambda a,b,c='',n=1,x=0,y=0,z=(-45,45):n<7**7and f(a,b,c+'%i%i'%(b>y,a>x),n*2,x+z[a>x]/n,y+z[b>y]/n*2)or c and'0123456789bcdefghjkmnpqrstuvwxyz'[int(c[:5],2)]+f(*z,c[5:],n)

```

Try it online!

Keeps track of the average values `x` and `y` for latitude and longitude, respectively. The function increases or decreases these values by steps of `45/n` and `90/n`, where `n` is equal to `2**(current cycle)`. The comparisons are stored in the bit-string `c`. This continues for 20 cycles, until `n` exceeds `2**19`, which is approximated by `7**7`. When this value is reached, it converts the `c` to the final result.
> 1 votes

---
Tags: code-golf
---


title: Recording xiangqi moves

text:
# Question
Title: Recording xiangqi moves
The game of xiangqi, also known as Chinese chess, is a chess-like game popular in China, Vietnam, Taiwan, and other East Asian countries. The colours of the two sides in xiangqi are red and black. There are 16 black pieces in xiangqi: the 1 general (G), 2 advisor (A), 2 elephant (E), 2 horse (H), 2 chariot (R), 2 cannon (C), and 5 soldier (S). The vertical lines are known as files (columns), and the horizontal lines are known as ranks (rows).

A notation system partially described in A Manual of Chinese Chess and used by several computer software implementations describes moves in relative terms as follows:

```
[single-letter piece abbreviation][former file][operator indicating direction of movement][new file, or in the case of purely vertical movement, number of ranks traversed]

```

The file numbers are counted from each player's right to each player's left. For black, the file numbers are shown in the picture, white background.

In case there are two identical pieces in one file, symbols `+` (front, higher rank) and `-` (rear, lower rank) are used instead of former file number. If there are more than two, `+`(highest rank), `2`(2nd highest rank), `3`(3rd highest rank), ... is used. It's fine either you use the number or `-` to mean the lowest rank if more than two exist. If more than one file contain multiple identical pieces, both former file and order can't be omitted, but the piece abbreviation can be omitted.

```
[former order in the file][single-letter piece abbreviation][operator indicating direction of movement][new file, or in the case of purely vertical movement, number of ranks traversed]
[former order in the file][former file][operator indicating direction of movement][new file, or in the case of purely vertical movement, number of ranks traversed]

```

A plus sign(`+`) is used to indicate forward movement. A minus sign(`-`) is used to indicate backwards movement. A dot or period(`.`) or equal sign(`=`) is used to indicate horizontal or lateral movement. For a piece that moves diagonally, the plus or minus sign is used rather than the period.

Thus, if the five soldiers are at `(5,6), (7,6), (9,6), (5,8), (7,8)`, then each of them moving one rank forward are expressed as `-5+1, -7+1, S9+1, +5+1, +7+1`; two horses at `(3,4)` and `(3,8)` each moving to `(4,6)` are expressed as `-H+4` and `+H-4`; five soldiers are at `(5,6), (7,6), (5,4), (5,8), (7,8)`, then each of them moving one rank forward are expressed as `25+1, -7+1, 35+1, +5+1, +7+1`; two horses at `(3,4)` and `(5,8)` each moving to `(4,6)` are expressed as `3H+4` and `5H-4`.

Given the current position and destination of the piece to move, and a list/set containing all positions of the same kind of pieces, output its expression. Input format is quie flexible. Shortest code win.

Samples: (use format that first item of the array is moved)

```
S [(5,6), (7,6), (9,6), (5,8), (7,8)] (5,7) -> -5+1 or -S5+1
S [(7,6), (5,6), (9,6), (5,8), (7,8)] (7,7) -> -7+1 or -S7+1
S [(9,6), (5,6), (7,6), (5,8), (7,8)] (9,7) -> S9+1
S [(5,8), (5,6), (7,6), (9,6), (7,8)] (5,9) -> +5+1 or +S5+1
S [(7,8), (5,6), (7,6), (9,6), (5,8)] (7,9) -> +7+1 or +S7+1
H [(3,4), (3,8)]                      (4,6) -> -H+4
H [(3,8), (3,4)]                      (4,6) -> +H-4
H [(3,8)]                             (4,6) -> H3-4
S [(5,4), (5,8), (7,8), (5,6), (7,6)] (5,5) -> 35+1 or -5+1 or 3S5+1 or -S5+1
S [(5,6), (5,8), (7,8), (5,4), (7,6)] (5,7) -> 25+1 or 2S5+1
S [(5,8), (5,6), (7,8), (5,4), (7,6)] (5,9) -> +5+1 or +S5+1

```

Pieces starting places and moving rules about from place`(x0,y0)`, to place`(x,y)` and their distance `r`, if that helps:

```
G (5,1)      r=1 & 3<x<7 & y<4
A (4,1)(6,1) r^2=2 & 3<x<7 & y<4
E (3,1)(7,1) r^2=8 & y<6
H (2,1)(8,1) r^2=5
R (1,1)(9,1) (x-x0)(y-y0)=0
C (2,3)(8,3) (x-x0)(y-y0)=0
S (1,4)(3,4)(5,4)(7,4)(9,4)
             r=1 & y>=y0 & (y>y0 | y>5)

```

# Answer
# Stax, 63 bytes

```
÷Qa9═wë•Θ╣äUuâ£▼+∙8WU▓kw≈▲!.┤α@∟┐₧╨═ºî⌂z▼0╬⌂6╕ú▄O&⌂¼^Mgâ╗╕.î¡☼:

```

Run and debug it

Takes input as `<position before> <piece type> [<other pieces>] <position after>`.

## Unpacked:

```
;x\EE-c:+"=+-"@s|aaE=s,h?$+Ydx]+MEsxh|I@|oc%vcaHX-xn^$'-?'+?z?,b'S<*!,h$*++y+

```

Run and debug it

### Explanation:

The first part calculates the last part: The direction of movement and the resulting file/change in rank:

```
;x\EE-c:+"=+-"@s|aaE=s,h?$+Yd
;x                            Push position after and before
  \                           Zip -> [[file after, file before], [rank after, rank before]]
   E                          Push files and ranks separately
    E-                        Difference in ranks (after - before)
      c:+                     Copy and get the sign (-1, 0, +1)
         "=+-"@               Index into the string "=+-" (-1 means last one)
               s|a            Get the absolute value of the difference in rank
                  aE=         Check whether file before = file after (pure vertical movement)
                     s        Swap with abs of difference in rank
                      ,h      Get file after
                        ?     If file before = file after:
                                abs(rank after - rank before)
                              Else:
                                file after
                              (this is the number in the end)
                         $    Convert to string
                          +   Concat the sign (-=+) and number.
                           Yd Store in Y register and delete from stack.

```

The second part calculates the index in the file (`+`, `-` or a digit):

```
x]+MEsxh|I@|oc%vcaHX-xn^$'-?'+?z?
x]+                               Append the position before to the list of other pieces
   ME                             Push list of files, then list of ranks
     s                            Swap the two
      xh|I                        Find indices with file = file before
          @                       Get ranks of these
           |o                     Calculate destination index of each element if the ranks were sorted
             c%v                  Get length of the array - 1
                                    (no. of other pieces in file)
                ca                Get the array of dest. indices again
                  HX              Get the last index (= index of the moving pieces)
                                    and store in register X
                    -             Then subtract from the no. of other pieces
                     xn^          ... and increment the result
                                    -> That's the index from big rank to small
                        $         ... and convert to string
                         '-?      If register X = 0 (lowest rank): "-"
                                  Else: The index from big to small
                            '+?   If index from big to small = 0 (high rank): "+"
                                  Else: Result from above
                               z? If length of array = 1: ""
                                  Else: Result from above

```

So this means:

* If there are no other pieces in this rank, ""
* Else if we have the highest rank, "+"
* Else if we have the lowest rank, "-"
* Else, the index of the rank as a string

These conditionals work in a somewhat special way: First, all the conditions are produced, most important to least important, then the `true` branch of the first condition is made (the index as a string). After this we push the falsy value for each condition, least important to most important, directly before performing the conditional `?`.

The third part checks whether we need to add the file number:

```
,b'S<*!,h$*
,           Get the piece type
 b          Copy both the result of part 2 and the piece type
  'S<       Test whether the piece type is NOT "S"
              (actually less than "S", because all other piece types come before S in ASCII)
     *      Repeat the result of part 2 by the result of this test:
            "" if the piece type is "S"
            the result of part 2 otherwise
      !     Negate this, "" is falsey.
            => This means NOT (part 2 is empty AND NOT piece type is "S")
            => Part 2 is empty iff this is the only piece in the file
            => NOT (only piece in file AND NOT piece type is "S")
            => NOT only piece in file OR piece type is "S"
       ,h   Push the file before
         $  and convert it to string
          * Repeat that string by the result of above check:
            "" unless other pieces in file or piece type is "S"

```

So, after parts 1-3, the stack looks like this:

```
<position in the file (+, -, or number)> <piece type> <file if necessary>

```

And the Y register contains the movement itself (from part 1).

The final part combines these into a single string:

```
++y+ "<position in the file>" "<piece type>" "<file if necessary>"
+    "<position in the file>" "<piece type><file if necessary>"
 +   "<position in the file><piece type><file if necessary>"
  y  "<position in the file><piece type><file if necessary>" "<movement>"
   + "<position in the file><piece type><file if necessary><movement>"

```

This final result is implicitly output.
> 8 votes

---
Tags: code-golf, chess
---


# Question
Title: The Camouflage Color Changing Chameleon Challenge
Chameleon challenges are a bad thing, apparently. Too bad, chameleons are beautiful creatures. Time for a change!

As we all know, many chameleons posses a remarkable ability to blend in with their surroundings by changing the color of their skin. Which is also the objective of this challenge.

## Challenge

Imagine a square of nine pixels. Eight pixels are the surroundings. At the center is the chameleon.

*Like this:*

The chameleon naturally tries to blend in with its surroundings. It does so by changing its color to the average of that of the surrounding pixels. So, in this case, the chameleon would change its color to .

## Objective

Given the colors of the surrounding pixels, output the color of the chameleon.

The color of the chameleon is defined as the total of all red, green and blue in the pixels ÷ 8.

## Input

An array of color values for the eight surrounding pixels, starting at the top left and continuing clockwise, like this:

```
[[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>]]

```

You may choose to receive input in a different form, as long as it consists of eight triples of decimal numbers 0-255.

If you receive input in a different form, numbers must either be of a consistent length or have a non-numeric separator between them. Triples must have a separating character unless they are 0-padded to 9 digits. (E.g. `044200255044200255044200255044200255044200255044200255044200255044200255` is valid, so are `44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255` and `44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255`, but `4420025544200255442002554420025544200255442002554420025544200255` is not.)

## Output

An array / string / etc. containing the colors of the center pixel (in decimal), like this:

```
[<red>,<green>,<blue>]

```

In case you output something other than an array: Numbers must either be of a consistent length or have a non-numeric separator between them. (E.g. `044200255` is valid, so is `44 200 255`, but `44200255` is not.)

The numbers may not contain decimal points, so e.g. `44.0 200 255.0` is invalid.

### Rounding

Output must be rounded to the nearest integer. (Halves must be rounded up.) E.g., if the sum of all red is *1620*, you must output `203`, not `202` or `202.5`.

## Examples

**Pictures are for illustration only.** The middle pixel is the output, the surrounding pixels are the input.

### Input:

```
[[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200]]

```

### Output:

```
[200,200,200]

```

---

### Input:

```
[[0,0,0],[255,255,255],[0,0,0],[255,255,255],[255,255,255],[0,0,0],[255,255,255],[0,0,0]]

```

### Output:

```
[128,128,128]

```

---

### Input:

```
[[0,200,200],[200,0,200],[200,200,0],[60,200,0],[200,0,200],[0,200,220],[2,200,0],[0,0,0]]

```

### Output:

```
[83,125,103]

```

---

### Input:

```
[[0,56,58],[65,0,200],[33,200,0],[60,33,0],[98,0,200],[0,28,220],[2,200,0],[99,0,5]]

```

### Output:

```
[45,65,85]

```

Submissions can be a full program or a function. Standard I/O and loophole rules apply.

# Answer
# MATL, ~~8~~ 4 bytes

```
YmYo

```

Try it online!

*4 bytes saved thanks to beaker!*

Explanation:

```
Ym          "Get the average of each column
  Yo        "And round up

```
> 8 votes

# Answer
## Python, 38 bytes

```
lambda l:[sum(r)+4>>3for r in zip(*l)]

```

Rounds the average (towards the nearest integer, with halves rounding up) by adding 4 to the sum, then floor-dividing by 8 via the bit-shift `>>3`.
> 11 votes

# Answer
# Jelly, 5 bytes

```
S+4:8

```

Test suite. (Slightly modified so as to verify all testcases at once.)

```
S+4:8
S      sum (vectorized)
 +4    add 4
   :8  floor division by 8

```
> 5 votes

# Answer
# C, ~~151~~ ~~123~~ ~~103~~ 91

Requires 24 parameters passed to the program, in the order R G B R G B ... and outputs the triplet R G B without a newline.

```
i,t;main(c,v)char**v;{for(i=0;t=4,i++<3;printf("%d ",t/8))for(c=i;c<24;c+=3)t+=atoi(v[c]);}

```
> 4 votes

# Answer
# JavaScript, ~~75~~ ~~64~~ 55 bytes

```
a=>a.reduce((p,c)=>p.map((e,i)=>e+c[i])).map(x=>x+4>>3)

```

A JavaScript answer to get you started.

**Edit:** Saved 11 bytes thanks to Dendrobium, and another 9 thanks to Neil.
> 1 votes

# Answer
# Pyth, 8 bytes

```
m.R.Od0C

```

Test suite.

```
m.R.Od0C     input: Q
m.R.Od0CQ    implicit arguments
        Q    input
       C     transpose
m    d       for each:
   .O            take average
 .R   0          round off

```
> 1 votes

# Answer
## Pyke, 7 bytes

```
,FsOO8f

```

Try it here!
> 1 votes

# Answer
# J, 11 bytes

```
0.5<.@++/%#

```

Takes the input as an 8x3 array where each row is an RGB value

## Explanation

```
0.5<.@++/%#  Input: a
          #  Count the number of rows
       +/    Sum along the columns
         %   Divide each sum by the count to get the averages
0.5   +      Add 0.5 to each average
   <.@       Floor each value and return

```
> 1 votes

# Answer
# Lisp - 180 179 bytes

EDIT: Formatted for further golfing.

```
(defun a(l)(/(apply #'+ l)(length l)))(defun r(a)(if(integerp(* a 2))(ceiling a)(round a)))(defun c(s)(mapcar(lambda(i)(r(sqrt(a(mapcar(lambda(x)(expt(nth i x)2))s)))))'(0 1 2)))

```

Does it the correct way, I guess. Untested.

* `a` is just average
* `r` is this challenge's proper rounding, since Lisp `round` rounds to the nearest even integer
* `c` does the real work, taking in input in the format `'((R G B) (R G B) (R G B) (R G B) (R G B) (R G B) (R G B) (R G B))`, and returning a `'(R G B)` list containg the answer.
> 1 votes

# Answer
# Nim, ~~134~~ ~~126~~ ~~115~~ ~~108~~ 78 bytes

```
import math,future
x=>lc[(lc[x[j][i]|(j<-0..7),int].sum+4)shr 3|(i<-0..2),int]

```

Defines an anonymous procedure, which requires the input passed in as a double-nested sequence and outputs as a 3-element array. The procedure can only be used as an argument to another procedure; to test, use the following wrapper:

```
import math,future
import strutils
proc test(x: seq[seq[int]] -> seq[int]) =
 echo x(#[ Insert your input here ]#)
test(x=>lc[(lc[x[j][i]|(j<-0..7),int].sum+4)shr 3|(i<-0..2),int])

```

A Nim sequence is an array with `@` in front, like `@[1, 2, 3]`. An input to this procedure could therefore be:

```
@[@[0,0,0],@[255,255,255],@[0,0,0],@[255,255,255],@[255,255,255],@[0,0,0],@[255,255,255],@[0,0,0]]

```
> 1 votes

# Answer
# Japt v2.0a0, ~~8~~ 7 bytes

```
y_x÷8 r

```

Try it

```
y_x÷8 c     :Implicit input of 2D array
y           :Transpose
 _          :Map
  x         :  Reduce by addition
   ÷8       :  Divide by 8
      r     :  Round

```
> 1 votes

# Answer
# Forth (gforth), 65 bytes

```
: f 3. do 8. do 3 j - i * 2 + roll loop 4 8. do + loop 8 / loop ;

```

Try it online!

Takes input as stack arguments (r g b order)

### Explanation

For each of the 3 color channels:

* move all the numbers of that channel to the top of the stack
* add them together
* add 4 (to handle rounding)
* divide by 8

### Code Explanation

```
: f            \ start new word definition
  3. do        \ start a counted loop from 0 to 2
    8. do      \ start a counted loop from 0 to 7
      3 j -    \ get the offset of the channel
      i * 2 +  \ get the absolute position of the channel value
      roll     \ move the value to the top of the stack
    loop       \ end the inner loop
    4          \ add 4 to the top of the stack
    8. do      \ loop from 0 to 7
      +        \ add the top two stack numbers
    loop       \ end loop. (Result on top of stack with be sum of values for channel + 4)
    8 /        \ divide by 8
  loop         \ end outer loop
;              \ end word definition

```
> 1 votes

# Answer
# Runic Enchantments, 41 bytes

```
>iRi+ i+ i+ i+ i+ i+ i+8,'rA' q$;
>iU
>iU

```

Try it online!

Utilizes 3 instruction pointers to parse the input in the correct order (as the input values are always in the order `RGB, RGB,...`) and as long as each of the three IPs don't merge, and don't advance to the next read `i`nput command too early (hence all the spaces), it works out and saves bytes over having to continuously rotate the stack to keep the correct value on top in order to calculate the sums.

*Technically* this code contains an error in correctly rounding `x.5` values for some inputs, but this is due to the default rounding method used by C#, which is to round to the nearest event number, rather than upwards and is due to issues in floating point accuracy loss, and I was unaware of this issue prior to writing this answer and checking the test cases. This will be fixed in a future build, along with a few other things such as this unhandled exception.

In the meantime, this modification makes the necessary adjustment.
> 1 votes

# Answer
# Husk, 8 bytes

```
mȯ÷8+4ΣT

```

Try it online! Transposes the array and does the usual transformation.
> 1 votes

---
Tags: code-golf, math, number, arithmetic, color
---


title: Simple "hyena" program

text:
# Question
Title: Simple "hyena" program
Write a program that takes a string as an input. For the input:

* If the input **doesn't** match the source code, the program shall output the input intact. (Hence a cat)
* Otherwise, the program shall fall in an infinite loop. (So actually not a cat)

# Answer
> 4 votes
# Ruby `-0p`, <sup>~~38~~ ~~37~~</sup> 32 bytes

*Saved 5 bytes thanks to a comment by @Sisyphus on another answer.*

```
eval s="1until$_!='eval s=%p'%s"

```

Try it online!

The `-0` flag sets the null byte as the input record separator. Without `-0`, a loop would also be entered if the input consisted of the code repeated on more than one line.

---
Tags: code-golf, quine
---


title: Looks prime to me!

text:
# Question
Title: Looks prime to me!
Figuring out whether a given number is prime, while not very complicated, is kind of hard. But making a guess doesn't need to be.

Seeing whether a number is a multiple of 2 or 5 is easy - you can just look at the last digit. Multiples of 3 isn't much harder, just add up the digits and see if you end up with a multiple of 3. Multiples of 11 are also easy enough, at least as long as they're fairly small. Any other number might not *be* prime, but at least they look like they *might* be prime. Or at least, that's how it works in base ten. As a person who frequently uses base ten, you can probably also identify the single-digit primes, and know that 11 is a prime as well.

We can generalize this to other bases. In some base \\$b \ge 2\\$, you can find fairly simple divisibility rules for any factor of \\$b, b-1 \text{ or }b+1\\$. You also presumably know all the prime numbers up to and including \\$b+1\\$.

But in any base, you eventually start running into numbers that *look* prime, but *aren't*. And I want to know when that happens. I know that in base 10, the first such number is 49 (not divisible by 2, 3, 5 or 11, but also not prime), in base 12 it's 25 (not divisible by 2, 3, 11 or 13), and in base 27, it's 55 (not divisible by 2, 3, 7 or 13, and unlike 25 it's also big enough to require two digits!). But for other bases? That's where you come in!

## Rules

Your task is to write a program or function which takes as input some integer \\$b\ge2\\$ and outputs the first integer which, when written in base \\$b\\$ *looks* like it might be prime, but *isn't*. That is to say, the smallest integer that

* Is a composite number and
* Is greater than \\$b\\$ and
* Is coprime with (does not share any prime factors with) \\$b-1\\$, \\$b\\$ and \\$b+1\\$

This is related to OEIS A090092, but starts to diverge at \\$b=27\\$

This is , so save those bytes!

## Test cases

```
Base -> Smallest pseudo-prime
2 -> 25
5 -> 49
6 -> 121
10 -> 49
12 -> 25
27 -> 55
32 -> 35
34 -> 169
37 -> 49
87 -> 91
88 -> 91
89 -> 91
121 -> 133
123 -> 125
209 -> 289

```

# Answer
# Haskell, 53 bytes

```
f b=[x|x<-[b..],k<-[2..x-1],mod x k+gcd(b^3-b)x<2]!!0

```

Try it online!
> 9 votes

# Answer
# JavaScript (ES6),  ~~91 83 79~~  76 bytes

```
f=(b,n=b,k=n)=>(g=d=>k<2?d<n:k%d?g(d+1):b*~-b*~b%d&&g(d,k/=d))(2)?n:f(b,n+1)

```

Try it online!

### How?

Given the base \\$b\\$, we look for the smallest integer \\$n\ge b\\$ with a prime divisor \\$d\\$ which is neither \\$n\\$ itself nor a divisor of \\$b-1\\$, \\$b\\$ or \\$b+1\\$.

### Commented

```
f = (                  // f is a recursive function taking:
  b,                   //   b = input base
  n = b,               //   n = candidate number, starting at b
  k = n                //   k = copy of n
) => (                 //
  g = d =>             // g is a recursive function taking a divisor d
    k < 2 ?            // if k = 1:
      d < n            //   successful if d is smaller than n
    :                  // else:
      k % d ?          //   if d is not a divisor of k:
        g(d + 1)       //     do recursive calls with d + 1 until it is
      :                //   else:
        b * ~-b * ~b   //     if b(b - 1)(b + 1) ...
        % d &&         //     ... is not divisible by d:
          g(d, k /= d) //       do a recursive call with k divided by d
  )(2)                 // initial call to g with d = 2
  ?                    // if successful:
    n                  //   return n
  :                    // else:
    f(b, n + 1)        //   try again with n + 1

```
> 8 votes

# Answer
# Gaia, ~~21~~ ~~20~~ 18 bytes

```
1⟨+:ṗ!¤@3*@⁻S&⟩#e+

```

Try it online!

-2 thanks to Arnauld!

```
1⟨	      ⟩#	% Find the first 1 positive integers n where:
  +:			% b + n
    ṗ!			% is not prime
	    S&		% and is coprime with
      ¤@3*@⁻		% b^3 - b, the product of b-1,b,b+1
		e+	% and return b + n

```
> 5 votes

# Answer
# Husk, 13 bytes

```
ḟȯ≥3Λ`%-¹^3¹p

```

Try it online!

## Explanation

```
ḟȯ≥3Λ`%-¹^3¹p   Input is a number b.
ḟ               Find first number ≥b that satisfies:
 ȯ              Composition of 3 functions:
                 Argument is a number n.
            p    1) Prime factors of n (with repetitions).
    Λ            2) All of them satisfy this:
           ¹      b
         ^3       cubed
       -¹         minus b
     `%           modulo the prime (is nonzero).
                  Λ returns either 0 or length+1.
  ≥3             3) Is at least 3.
                  This means n has at least 2 prime factors and none of them divide b^3-b = b*(b+1)*(b-1).

```
> 5 votes

# Answer
# Jelly, 15 bytes

```
’r‘Ɗg’;Ẓ}E
ç@1#

```

Try it online!

## How it works

```
’r‘Ɗg’;Ẓ}E - Helper link. Takes b on the left and n on the right
   Ɗ       - Run the previous 3 commands over b:
’          -   Yield b-1
  ‘        -   Yield b+1
 r         -   Yield [b-1, b, b+1]
    g      - Take the GCD between each of these and n
     ’     - Decrement, yielding 0 for co-primes
       Ẓ}  - Is n prime?
      ;    - Concatenate to the list of decremented GCDs
         E - Are they all equal i.e. do they all equal 0?

ç@1# - Main link. Takes b on the left
  1# - Count up from b and return the first integer, n, which is true when:
ç@   -   run through the helper link with b on the left and n on the right

```
> 4 votes

# Answer
# Scala, ~~97~~ ~~96~~ 91 bytes

```
b=>{def g(i:Int):Int=if(BigInt(b*b*b-b).gcd(i)>1|2.to(i-1).forall(i%_>0))g(i+1)else i
g(b)}

```

Try it online!
> 4 votes

# Answer
# Python 3.8, ~~115~~ ~~98~~ 89 bytes

Saved a whopping 17 bytes thanks to the man himself Arnauld!!!

```
f=lambda b,m=9:(m>b)*(perm(m-1)**2%m!=1)*m*(gcd(b**3-b,m)<2)or f(b,m+1)
from math import*

```

Try it online!

### Explanation

```
f=lambda  b                       # recursive function taking b
           ,m=9                   # init possible answer to largest single
                                  # digit (of which none of them can be
                                  # the solution because they're either
                                  # prime or divisible by 2 or 3)
               :                  # the start of a chain of logical
                                  # tests, if any of them are False the
                                  # chain will be 0 invoking recursion
    (m>b)*                        # first one makes sure m is >= b + 1
      (perm(m-1)**2%m!=1)*        # second tests that m isn't prime using
                                  # one of xnor's tricks
        *(math.gcd(b**3-b,m)<2)   # third tests that m is coprime with
                                  # (b - 1)*b*(b + 1) == b**3 - b
            *m                    # if all this is True return m
               or f(b,m+1)        # otherwise try m + 1

```
> 3 votes

# Answer
# Husk, ~~18~~ 17 bytes

```
ḟ(EM⌋m+¹ṡ1)fo¬ṗ↓N

```

Try it online! or Verify all test cases

-1 byte after rearranging stuff.

## Explanation

```
ḟ(EM⌋m+¹ṡ1)fo¬ṗ↓N
               ↓N drop first b elements from natural numbers.
           fo¬ṗ   filter out primes
ḟ                 get first element which satisfies the following:
 (        )       co-prime check
        ṡ1        range -1..1
     m+¹          add each to b
   M⌋             GCD of each and b
  E               are all equal?

```
> 3 votes

# Answer
# Brachylog, 22 16 bytes

*-6 thanks to Zgarb*

```
^₃;?-ḋF&<.ḋṀ;Fx×

```

Try it online!

* `^₃;?-ḋF`: all the prime factors of `B^3-B`
* `&<.`: the output `N` is greater than `B`
* `ḋṀ`: `N`'s prime factors are at least 2
* `;Fx×`: and the product of the prime factors without the ones in `F` unifies with the output `N`.
> 3 votes

# Answer
# Jelly, 13 bytes

```
’r‘²Pg€ƊỤẒÞḊḢ

```

A monadic Link accepting an integer, \\$b\\$, which yields the first integer that "looks prime but isn't".

**Try it online!** (Too inefficient for even quite small inputs due to golfing.)

### How?

This is really just a golfed version of this 15 byter which is not so ridiculously inefficient: `’r‘ṀÆn²g€ƲỤẒÞḊḢ`.

```
’r‘²Pg€ƊỤẒÞḊḢ - Link: b
’             - decrement -> b-1
  ‘           - increment -> b+1
 r            - inclusive range -> [b-1, b, b+1]
       Ɗ      - last three links as a monad:
   ²          -   square -> [(b-1)², b², (b+1)²]
    P         -   product -> (b(b-1)(b+1))²
                  (this is always greater than ṀÆn²
                     - the square of the next prime above b+1
                   and saves us two precious bytes)
      €       -   for each (v in [1..(b(b-1)(b+1))²]:
     g        -     greatest-common-divisor (between v and each of [b-1, b, b+1])
        Ụ     - grade-up -> 1-based indices sorted by the values at those positions
          Þ   - sort by:
         Ẓ    -   is prime?
           Ḋ  - dequeue (since 1 gets GCDs [1,1,1] so it also looks prime and isn't prime)
            Ḣ - head -> the smallest number that looks prime and isn't prime

```
> 3 votes

# Answer
# Japt, 16 bytes

```
@Jõ+U ejX «Xj}aU

```

Try it or run all test cases

```
@Jõ+U ejX «Xj}aU     :Implicit input of integer U
@                    :Function taking an integer X as argument
 J                   :  -1
  õ                  :  Range [-1,1]
   +U                :  Add U to each
      e              :  All
       jX            :    Co-prime with X
          «          :  Logical AND with the boolean negation of
           Xj        :  Is X prime?
             }       :End function
              aU     :Starting from U, get the first X that returns true

```
> 2 votes

# Answer
# Retina 0.8.2, 58 bytes

```
.+
$*11¶$&$*
+`^(11+)\1*1?1?¶\1+$|¶(?!(11+)\2+$)
$&1
r`1\G

```

Try it online! Link includes test cases. Explanation:

```
.+
$*11¶$&$*

```

Convert `b` to unary, and make a copy as `b+1`, which will be used for GCD testing.

```
+`^(11+)\1*1?1?¶\1+$|¶(?!(11+)\2+$)
$&1

```

Keep incrementing the result while it's prime or shares a common factor with either `b+1`, `b` or `b-1`.

```
r`1\G

```

Convert the result back to decimal.
> 2 votes

# Answer
# Stax, 12 bytes

```
öα•○¼¿¼╓♫├û•

```

Run and debug it
> 2 votes

# Answer
# C (gcc), ~~87~~ ~~86~~ 84 bytes

Saved a byte thanks to the man himself Arnauld!!!

```
i;q;p;m;f(b){for(p=m=b;p|!q;++m)for(q=p=i=1;++i<m;)q=m%i<1?p=0,q&&b*~-b*~b%i:q;--m;}

```

Try it online!

Port of my Python answer.
> 2 votes

# Answer
# Python 3, 81 bytes

```
f=lambda b,k=1,p=1:(k<b)|p%k|math.gcd(b**3-b,k)-1and f(b,k+1,p*k)or k
import math

```

Try it online!

---

Uses xnor's corollary to Wilson's theorem. I still find it unbelievable that the shortest way to test for coprimality is `import math;math.gcd(x,y)<2`, but I couldn't find a shorter way.

-2 due to xnor, since we only need the regular factorial here (instead of factorial squared). The special case `k=4` is taken care of by the other conditions.
> 2 votes

# Answer
# Python 3, ~~145~~ ~~143~~ 137 bytes

```
from math import*
p=lambda b,h=2,c=inf:h>c and c or p(b,h+1,([h*i for i in range(2,h+1)if 2>gcd(h*i,b**3-b)and h*i<c and b<h*i]or[c])[0])

```

Try it online!

* -2 bytes by reformatting the condition in the list comprehension and removing an unnecessary space.
* -6 bytes from removing a special case when `c` is `0` by making it default to `math.inf` instead

Wanted to test how a solution that doesn't involve prime checking might fare, just out of curiosity. Worse than the competition, it seems. Oh well, at least I had fun.

Works by generating all composite numbers. On each pass, we generate some numbers that are definitely composite, then update our best guess (which we'll call \\$x\\$) to be the smallest number we find that's between \\$b\\$ and \\$x\\$ and also coprime with \\$b^3 - b\\$ \- if we didn't end up generating a number like that, we keep our existing \\$x\\$. Eventually we reach a point where we know we'll no longer generate any numbers that are below our current \\$x\\$, which means \\$x\\$ must be the correct answer.

## Ungolfed

```
from math import gcd, inf

def pseudoprime(base, high=2, candidate=inf):
    if high > candidate:
        # We can no longer find anything that's small enough to care about
        return candidate
    else:
        valid_multiples = [high * i for i in range(2, high+1) if # Generate all multiples of "high", then filter them
            base < high * i and # Exclude single-digit numbers
            math.gcd(high * i, base ** 3 - base) < 2 and # Check for coprimality
            high * i < candidate # Make sure it's not bigger than our best guess, assuming we've found one
        ]
        if valid_multiples:
            return pseudoprime(base, high + 1, valid_multiples[0])
        else:
            return pseudoprime(base, high + 1, candidate)

```
> 2 votes

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

```
∞+.ΔαD3mαy¿yp+

```

Inspired by *@Giuseppe*'s Gaia answer, so make sure to upvote him as well!

Try it online or verify all test cases.

**Explanation:**

```
∞            # Push an infinite positive list: [1,2,3,...]
 +           # Add the (implicit) input `n` to each: [n+1,n+2,n+3,...]
  .Δ         # Find the first `n+b` which is truthy for:
    α        #  Take the absolute difference with the (implicit) input: [1,2,3,...]
     D       #  Duplicate this `b`
      3m     #  Cube it: b³
        α    #  Take the absolute difference with the `b` we've duplicated: |b-b³|
         y¿  #  Get the greatest common divisor with the current `b+n`: gcd(|b-b³|,b+n)
    yp       #  Check whether `b+n` is a prime number (1 if prime; 0 if not)
    +        #  Add them together: gcd(|b-b³|,b+n)+isPrime(b+n)
             #  (NOTE: only 1 is truthy in 05AB1E)
             # (after which the result is output implicitly as result)

```
> 2 votes

# Answer
# , ~~100~~ ~~81~~ ~~73~~ 72 bytes

*Edit1: -19 bytes by abandoning the nice all-in-one check-for-primality-and-shared-divisors, and instead using clunkier but shorter separate checks*

*Edit2: -8 bytes, and then -1 more byte thanks to Giuseppe*

```
f=function(b,n=b)`if`(sum(a<-!n%%2:n)>1&all(!a|(b^3-b)%%2:n),n,f(b,n+1))

```

Try it online!

Sadly, although checking for primality by counting divisors and checking for **co**-primality by counting **shared** divisors could be elegantly combined, the ugly code below is actually (quite a bit) shorter...

Thanks to Giuseppe for ruthlessly pruning all the unneccessary variables, parentheses, square-brackets and so on...

**How?** (code before golfing by Giuseppe)

```
f=function(b,               # f is recursive function taking argument b (=base)
  n=b,                      # n is number to test for pseudo-primeness; start at b
  a=!n%%2:n,                # a is zero-values of n MOD 2..n = divisors (excluding 1)
  c=!(b^3-b)%%2:n           # c is zero-values of (b-1).b.(b+1) MOD 2..n = divisors of b-1, b or b+1
)
`if`(                       # Now, check whether:
(sum(a)>1)                  #   a is not prime (if it has >1 divisor including itself)
  &!sum(c[a]),              #   and it has no shared divisors with b-1, b or b+1
  n,                        # If both are Ok, then n is a pseudo-prime: return it
  f(b,n+1)                  # otherwise, do recursive call with n+1
)

```
> 2 votes

# Answer
# Charcoal, 35 bytes

```
Ｎθ≔Ｘ²⁻Ｘθ³θηＷ∨﹪Π…¹θθ﹪÷Ｘηθ⊖η⊖Ｘ²θ≦⊕θＩθ

```

Try it online! Link is to verbose version of code. Uses @xnor's formulas (see @Sisyphus's answer), so slow for large inputs (seems to be OK up to \\$ b = 27 \\$ at least). Explanation:

```
Ｎθ

```

Input \\$ n \\$, which is initially equal to \\$ b \\$.

```
≔Ｘ²⁻Ｘθ³θη

```

Calculate \\$ 2 ^ { b (b - 1) (b + 1) } \\$ which is used in @xnor's GCD calculation.

```
Ｗ∨

```

While either...

```
﹪Π…¹θθ

```

... \\$ n \\$ does not divide \\$ (n - 1)! \\$, meaning that \\$ n \\$ is 4 or prime, or...

```
﹪÷Ｘηθ⊖η⊖Ｘ²θ

```

... \\$ 2 ^ n - 1 \\$ does not divide \\$ \left \lfloor \frac { 2 ^ { n b (b - 1) (b + 1) } } { 2 ^ { b (b - 1) (b + 1) } - 1 } \right \rfloor \\$, meaning that \\$ n \\$ is not coprime to all of \\$ b - 1 \\$, \\$ b \\$ and \\$ b + 1 \\$, ...

```
≦⊕θ

```

... increment \\$ n \\$.

```
Ｉθ

```

Output the final value of \\$ n \\$.

Much faster 38-byte version which performs separate coprimaility testing on \\$ b - 1 \\$, \\$ b \\$ and \\$ b + 1 \\$:

```
Ｎθ≔Ｅ³Ｘ²⊖⁺θιηＷ∨﹪Π…¹θθ⊙η﹪÷Ｘκθ⊖κ⊖Ｘ²θ≦⊕θＩθ

```

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

# Answer
# Java 8, ~~106~~ ~~105~~ ~~104~~ 100 bytes

```
n->{for(int b=0,p,g,i;;){for(g=p=++n;n%--p>0;);for(i=++b*b*b-b;i>0;)i=g%(g=i);if(p>1&g<2)return n;}}

```

-1 byte thanks to *@ceilingcat*.

Try it online.

**Explanation:**

```
n->{                 // Method with integer as both parameter and return-type
  for(int b=0,       //  Start integer `b` at 0
          p,         //  Temp-integer to check for primes
          g,i;       //  Temp-integers to check for the gcd
      ;){            //  Loop indefinitely:
    for(g=p=++n;     //   Increase n by 1 first with `++n`
                     //   And then set both g and p to this new n
        n%--p>0;);   //   Decrease p by 1 before every iteration with `--p`
                     //   and continue looping as long as n is NOT divisible by p
    for(i=++b*b*b-b; //   Then increase b by 1 first with `++b`
                     //   And set i to b³-b
        i>0;)        //   Loop as long as i is still positive:
      i=g%(g=i);     //    First set g to i
                     //    And then set i to old_g modulo-new_g
    if(p>1           //   If `p` is larger than 1 (this means it's NOT a prime)
       &g<2)         //   and the greatest common divisor is 1:
      return n;}}    //    Return the modified n as result

```
> 1 votes

---
Tags: code-golf, primes, factoring
---