title: What is the standard scratch?

text:
# Question
Title: What is the standard scratch?
In golf, the standard scratch of a course is calculated using this formula:

```
(3*num_of_3_par_holes + 4*num_of_4_par_holes + 5*num_of_5_par_holes) - difficulty_rating

```

Your task is to calculate the standard scratch of a golf course, given these 4 inputs.

You should take input in any standard form in the format

```
[num_of_3_pars, num_of_4_pars, num_of_5_pars], difficulty rating

```

but if it saves bytes, you many take input in a different way.

You should output the final result by any accepted method on meta, such as returning from a function.

Shortest code wins because this is !

# Answer
> 31 votes
# Scratch, 145 bytes

<sup>-2 thanks to boboquack
-??? because writing it in Oto is shorter than English</sup>

(Because Scratch is the standard scratch.)

Here's a sample run:

.

# Answer
> 19 votes
# Jelly, 6 bytes

```
JḊ~æ.N

```

Try it online!

### How it works

```
JḊ~æ.N  Main link. Argument: [a, b, c, d]

J       Indices; yield [1, 2, 3, 4].
 Ḋ      Dequeue; yield [2, 3, 4].
  ~     Bitwise NOT; yield [-3, -4, -5].
     N  Negate; yield [-a, -b, -c, -d].
   æ.   Dot product; yield
        (-3)(-a) + (-4)(-b) + (-5)(-c) + (-d) = 3a + 4b + 5c - d.

```

# Answer
> 10 votes
# Java (OpenJDK 8), 24 bytes

```
(a,b,c,d)->a*3+b*4+c*5-d

```

Try it online!

# Answer
> 6 votes
# Mathematica, 13 ~~14~~ bytes

```
{3,4,5,-1}.#&

```

Thanks to @GregMartin. Take input as a length-4 list.

# Answer
> 6 votes
# Haskell, 22 bytes

```
(a#b)c d=3*a+4*b+5*c-d

```

Try it online! Usage: `(3#2)5 7` yields `35`.

This not so nice input format is one byte shorter than the straight forward solution:

```
f a b c d=3*a+4*b+5*c-d

```

---

**Point-free and nice input format:** (23 bytes)

```
(-).sum.zipWith(*)[3..]

```

Try it online! Bind to `f` and call with `f [3,2,5] 7`.

# Answer
> 5 votes
# Julia 0.5, 15 bytes

```
!v=v⋅[3:5;-1]

```

Try it online!

# Answer
> 4 votes
# Python 3, 28 bytes

```
lambda a,b,c,d:3*a+4*b+5*c-d

```

Try it online!

# Answer
> 4 votes
# Jelly, ~~10~~ 7 bytes

```
3r5×⁸S_

```

Try it online!

-3 bytes thanks to Erik The Outgolfer!

## How it works!

```
3r5×⁸S_  Main link: a, the pars as a list and b, the difficulty rating

     S   The sum of
3r5        [3, 4, 5]
   ×       each element times
    ⁸      the left argument (a)
      _  Subtract the right argument (b)

```

# Answer
> 4 votes
# Javascript, 24 bytes

```
(a,b,c,d)=>3*a+4*b+5*c-d

```

# Answer
> 4 votes
# Perl6, 16 characters

```
3* *+4* *+5* *-*

```

(Yepp, that is a sub.)

Sample run:

```
> say 3* *+4* *+5* *-*
{ ... }

> say (3* *+4* *+5* *-*)(4, 3, 2, 1)
33

```

Try it online!

# Answer
> 3 votes
# C#, 24 bytes

```
(a,b,c,d)=>a*3+b*4+c*5-d

```

# Answer
> 3 votes
# x86-64 Machine Code, 14 bytes

```
8D 3C 7F 8D 14 92 8D 04 B7 01 D0 29 C8 C3

```

A function following the System V AMD64 calling convention (ubiquitous on Gnu/Linux systems) that takes four integer parameters:

* `EDI` = num\_of\_3\_par\_holes
* `ESI` = num\_of\_4\_par\_holes
* `EDX` = num\_of\_5\_par\_holes
* `ECX` = difficulty\_rating

It returns a single value, the standard scratch, in the `EAX` register.

**Ungolfed assembly mnemonics:**

```
; int ComputeStandardScratch(int num_of_3_par_holes,
;                            int num_of_4_par_holes,
;                            int num_of_5_par_holes,
;                            int difficulty_rating);
lea   edi, [rdi+rdi*2]    ; EDI = num_of_3_par_holes * 3
lea   edx, [rdx+rdx*4]    ; EDX = num_of_5_par_holes * 5
lea   eax, [rdi+rsi*4]    ; EAX = EDI + (num_of_4_par_holes * 4)
add   eax, edx            ; EAX += EDX
sub   eax, ecx            ; EAX -= difficulty_rating
ret                       ; return, leaving result in EAX

```

Just a simple translation of the formula. What's interesting is that this is essentially the same code that you would write when optimizing for *speed*, too. This really shows the power of the x86's `LEA` instruction, which is designed to *l*oad an *e*ffective *a*ddress, but can do addition and scaling (multiplication by low powers of 2) in a single instruction, making it a powerful multi-purpose arithmetic workhorse.

# Answer
> 3 votes
# dc, 14 characters

```
?3*?4*+?5*+?-p

```

The numbers need to be passed on separate lines.

Sample run:

```
bash-4.4$ dc -e '?3*?4*+?5*+?-p' <<< '4
> 3
> 2
> 1'
33

```

Try it online!

# Answer
> 3 votes
# Octave, 14 bytes

```
@(a)[3:5 -1]*a

```

Try it online!

About twice as long as the MATL answer. I initially literally ported this to MATL, but it turned out `iY*` is longer than just `*s`. Note that the input `a`, containing the holes in order and then the difficulty, should be a column vector.

# Answer
> 2 votes
## Julia, 21 bytes

```
f(a,b,c,d)=3a+4b+5c-d

```

Try it online!

# Answer
> 2 votes
# Swift 3, ~~25~~ 19 bytes

I realised you do not need the `var f=`, because you can call it like a Python lambda:

```
{$0*3+$1*4+$2*5-$3}

```

Test it online!

**Usage:** `{$0*3+$1*4+$2*5-$3}(a,b,c,d)`, where `a,b,c,d` are the parameters.

# Answer
> 2 votes
# Neim, 7 bytes

```
'πS

```

Explanation:

```
'π         Push 345
           The character ' pushes the next character's index in the codepage plus 100.
           The characters ", + and * do that same thing except add a different number.
           This means that in Neim, all 3 digit numbers can be expressed with 2 characters.
           This commit was pushed 8 days before the answer was posted.
          Get the characters
          Vectorised multiply with the input
           Sum the resulting list
     S    Subtract the input

```

Alternative program: `3ᛖS`

Instead of pushing `345` and then getting the characters, creates the array `[1 2 3]` using `3`, then adds 2 to each element with .

Try it online!

# Answer
> 2 votes
# C (gcc), 30 bytes

```
e;f(a,b,c,d){e=3*a+4*b+5*c-d;}

```

Try it online!

# Answer
> 2 votes
# ,,,, 12 bytes

```
↻5×↻4×↻3×↻-#

```

## Explanation

Take input 4, 3, 2, 1 for example.

```
↻5×↻4×↻3×↻-#

              implicit input                  [4, 3, 2, 1]
↻             rotate the stack clockwise      [1, 4, 3, 2]
 5            push 5                          [1, 4, 3, 2, 5]
  ×           pop 2 and 5 and push 2 * 5      [1, 4, 3, 10]
   ↻          rotate the stack clockwise      [10, 1, 4, 3]
    4         push 4                          [10, 1, 4, 3, 4]
     ×        pop 3 and 4 and push 3 * 4      [10, 1, 4, 12]
      ↻       rotate the stack clockwise      [12, 10, 1, 4]
       3      push 3                          [12, 10, 1, 4, 3]
        ×     pop 4 and 3 and push 4 * 3      [12, 10, 1, 12]
         ↻    rotate the stack clockwise      [12, 12, 10, 1]
          -   pop 10 and 1 and push 10 - 1    [12, 12, 9]
           #  pop 12, 12, 9 and push the sum  [33]
              implicit output

```

# Answer
> 2 votes
# Brachylog, ~~18~~ 16 bytes

```
∧5⟦₁↺b;?z×ᵐġ₃+ᵐ-

```

Try it online!

-2 thanks to Fatalize.

# Answer
> 2 votes
# brainfuck, 39 bytes

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

```

Try it online!

Takes input and prints output as ASCII characters; for example, the value 99 would be represented as c.

### Explanation:

```
,                                       Take the first input in Cell 0
 [      ]                               While the data being pointed to (Cell 0) is nonzero
  ->+++<                                Decrement Cell 0 and add 3 to Cell 1
                                        Now 4 times the first input is in Cell 1
         ,                              Take the second input in Cell 0
          [->++++<]                     Add 4 times the second input to Cell 1
                   ,[->+++++<]          Take the third input in Cell 0 and add five times its value to Cell 1
                              ,         Take the fourth input in Cell 0
                               [    ]   While the data being pointed to (Cell 0) is nonzero
                                ->-<    Decrement Cells 0 and 1
                                     >. Print the value in Cell 1

```

# Answer
> 2 votes
# Gallina, 38 bytes

```
Definition f a b c d := 3*a+4*b+5*c-d.

```

# Answer
> 2 votes
# Excel VBA, 20 Bytes

Anonymous VBE immediate window function that takes input from the range `[A3:A6]` of which `[A3:A5]` represent the number of `3`,`4` and `5` par holes, respectively and `[A6]` represents the difficulty. Outputs to the VBE immediate window

```
?[3*A3+4*A4+5*A5-A6]

```

The above is a condensed version of the call

```
Debug.Print Application.Evaluate("=3*A3+4*A4+5*A5-A6")

```

Where `"=3*A3+4*A4+5*A5-A6"` is given to be the formula of an anonymous cell, as indicated by the `[...]` wrapper, and `?` is the deprecated version of the `Print`  call with an implicit `Debug.` by context

### More fun Version, 34 Bytes

Anonymous VBE immediate window function with same I/O conditions as above.

```
?[SUMPRODUCT(A3:A5,ROW(A3:A5))-A6]

```

The above is a condensed version of the call

```
Debug.Print Application.Evaluate("=SUMPRODUCT(A3:A5,ROW(A3:A5))")

```

Where `"=SUMPRODUCT(A3:A5,ROW(A3:A5))"` is given to be the formula of an anonymous cell, as indicated by the `[...]` wrapper, and `?` is the deprecated version of the `Print`  call with an implicit `Debug.` by context. In this version, the range of `[A3:A5]` and the row numbers of that range (`ROWS(A3:A5)`) are passed as arrays

### Excel Version, 18 bytes

Of course, the versions above lend themselves thusly to excel versions of

```
=3*A3+4*A4+5*A5-A6

```

and

```
=SUMPRODUCT(A3:A5,ROW(A3:A5))-A6

```

# Answer
> 2 votes
# , ~~25~~ 23 bytes

```
cat(c(3:5,-1)%*%scan())

```

Try it online!

# Answer
> 2 votes
# Cubix, 36 bytes

```
w;r5*U4I;I3*r;UW;;r;<\r/;r-I/+p+O@;w

```

Try it online!

```
      w ; r
      5 * U
      4 I ;
I 3 * r ; U W ; ; r ; <
\ r / ; r - I / + p + O
@ ; w . . . . . . . . .
      . . .
      . . .
      . . .

```

Watch It Run

A fairly linear program that winds back around onto itself a few times. Basic steps:

* `I3*r;U;` get the first input, multiply by 3 and clean up stack
* `I4*/r\` get next input and multiply by 4. Rotate result down.
* `Iw5*Ur;w<;r;;W` get next input, multiply by 5 and clean up the stack
* `I-r;w;` get last input, subtract from par 5 result and clean up stack
* `/+p+O\@` add to par 4 result, bring par3 result to top add, output and halt

# Answer
> 2 votes
# HP-15C (RPN), 14 bytes

Instruction hex codes:

```
41 C4 F5 FC C5 F4 FC FA C5 F3 FC FA 31 FB

```

Readable version:

```
001 {       44  1 } STO 1
002 {          33 } R⬇
003 {           5 } 5
004 {          20 } ×
005 {          34 } x↔y
006 {           4 } 4
007 {          20 } ×
008 {          40 } +
009 {          34 } x↔y
010 {           3 } 3
011 {          20 } ×
012 {          40 } +
013 {       45  1 } RCL 1
014 {          30 } −

```

The four numbers are loaded into the stack in order before running the program.

# Answer
> 2 votes
# Husk, ~~10~~ 9 bytes

```
`-Σz*d345

```

Try it online!

# Answer
> 1 votes
# Befunge, 15 bytes

```
&3*&4*+&5*+&-.@

```

Try it online!

# Answer
> 1 votes
# Japt, 12 bytes

```
*3+V*4+W*5-X

```

Test it

# Answer
> 1 votes
# Braingolf, 14 bytes

```
3*>4*>5*>>++,-

```

Try it online!

# Answer
> 1 votes
# Batch, 28 bytes

```
@cmd/cset/a%1*3+%2*4+%3*5-%4

```

Can't believe I'm tying with Python!

# Answer
> 1 votes
# cQuents, 14 bytes

```
#|1:3A+4B+5C-D

```

Try it online!

Input is `3par 4par 5par diff`. cQuents is not at all built for this type of problem, but it still did fairly well.

## Explanation

```
#|1               Append 1 to the end of the user input - call it n
   :              Mode: sequence
    3A+4B+5C-D    Each item in the sequence equals the first input times three plus
                  the second input times four plus the third input times five minus
                  the fourth input. The last input, n, which came from the program's
                  parameters, prints the nth item in the sequece.

```

# Answer
> 1 votes
# 05AB1E, 7 bytes

```
3LÌ*O²-

```

Try it online!

# Answer
> 1 votes
# CJam, 12 bytes

```
{6,3>.*:+\-}

```

Try it online!

-1 thanks to Challenger5.

Takes input as `difficulty rating [num_of_3_pars num_of_4_pars num_of_5_pars]`.

# Answer
> 1 votes
# Pyth, 9 bytes

```
-s*V}3 5E

```

Try it here.

Takes input as `difficulty rating\n[num_of_3_pars, num_of_4_pars, num_of_5_pars]`.

# Answer
> 1 votes
# GolfScript, 23 bytes

```
~[.;3,]zip{~3+*}%{+}*\-

```

Try it online!

Takes input as `difficulty rating [num_of_3_pars num_of_4_pars num_of_5_pars]`.

# Answer
> 1 votes
# PHP\>=7.1, 43 bytes

```
[,$x,$y,$z,$d]=$argv;echo$x*3+$y*4+$z*5-$d;

```

PHP Sandbox Online

# Answer
> 1 votes
# MATL, 7 bytes

```
3:5*si-

```

Try it online!

Input vector times range `3:5` minus the second input. Contrary to my Octave answer, it's actually shorter to have the inputs as two separate inputs, and shorter to element-wise multiply, then sum, than to do a direct dot product.

# Answer
> 1 votes
# QBIC, 14 bytes

```
?:*3+:*4+:*5-:

```

Functionally equivalent to this.

# Answer
> 1 votes
# Pyt, ~~13~~ 8 bytes

```
35Ř←*Ʃ←-

```

Takes as input from stdin inputs separately in the following order: \[num\_of\_3\_pars,num\_of\_4\_pars,num\_of\_5\_pars\], difficulty\_rating

# Answer
> 1 votes
# K (ngn/k), 12 bytes

```
{-y-/x*3+!3}

```

Try it online!

Called like `f[1 2 3;4]`. Takes the number of par 3/4/5 holes as one list of three values, and the difficulty rating as the second arg.

* `x*3+!3` generate `3 4 5`, multiplying by the first input
* `-y-/` equivalent to `(-y)+/x`, or `(+/x)-y`. In this instance, the leading `-` negates the entire `y-/...` expression.

# Answer
> 1 votes
# Vyxal `as`, ~~8~~ 7 bytes

-1 thanks to Aaron Miller

```
2ʀ3+uJ*

```

Takes input as `par3 \n par4 \n par5 \n difficulty`. Try it Online!

```
2ʀ3+uJ*
2ʀ        # Push the range [0, 1, 2]
  3+      # Add 3: [3, 4, 5]
    uJ    # Append -1: [3, 4, 5, -1]
      *   # Multiply the list by its counterpart in...
          # the (implicit) input, and...
          # Print the sum of the result (s flag)

```

# Answer
> 1 votes
# MMIX, 24 bytes (6 instrs)

```
00000000: 2a020202 28000000 26020203 2a000100  *£££(¡¡¡&££¤*¡¢¡
00000010: 22000002 f8010000                    "¡¡£ẏ¢¡¡

```

```
scratch 4ADDU $2,$2,$2      // p5 *= 5
        2ADDU $0,$0,$0      // p3 *= 3
        SUBU  $2,$2,$3      // p5 -= diff
        4ADDU $0,$1,$0      // p3 += 4 * p4
        ADDU  $0,$0,$2      // p3 += p5
        POP   1,0           // return p3

```

I ordered the instructions to avoid as many short-term data dependencies as possible.

# Answer
> 1 votes
# BRASCA, 18 bytes

Takes input as `<3-par>,<4-par>,<5-par>,<difficulty>`

```
Ci',G,3*$4*+$5*+$-

```

Try it online!

## Explanation

```
C                   - Set implicit output to number mode
 i',G               - Use numbers instead of charcodes for 0-9. Then split by commas.
     ,              - Reverse stack so the 3par is at the top.
      3*            - 3par * 3
        $4*+        - 4par * 4, then add to 3par
            $5*+    - 5par * 5, then add to total
                $-  - total - difficulty
<implicit>          - Print it

```

# Answer
> 1 votes
# Factor, ~~23~~ 22 bytes

```
[ { 3 4 5 } v. - neg ]

```

Try it online!

*-1 thanks to @Bubbler*

The quotation takes the input as `difficulty list`.

* `{ 3 4 5 } v.` Take the dot product between the input list and `{ 3 4 5 }`.
* `- neg` Subtract the difficulty rating from the dot product.

# Answer
> 0 votes
# TI-Basic, 19 bytes

```
Prompt A,B,C,D:3A+4B+5C-D

```

Alternatively (21 bytes):

```
3Ans(1)+4Ans(2)+5Ans(3)-Ans(4

```

# Answer
> 0 votes
# Add++, 27 bytes

```
D,g,@@@@!,3 4 5 1ECBcB*0$_s

```

Try it online!

## How it works

```
D,g,        - Create a function called g...
    @@@@    - ...that takes 4 arguments...
    !,      - ...as a list. e.g.     [4 3 2 1]
    3 4 5 1 - Push 3 4 5 1; STACK = [[4 3 2 1] 3 4 5 1]
    EC      - Collect;      STACK = [[4 3 2 1] [3 4 5 1]]
    Bc      - Zip;          STACK = [[4 3] [3 4] [2 5] [1 1]]
    B*      - Products;     STACK = [12 12 10 1]
    0$_     - Negate;       STACK = [12 12 10 -1]
    s       - Sum;          STACK = [33]

```

# Answer
> 0 votes
# Ly, 13 bytes

```
3n*4n*5n*&+n-

```

Try it online!

# Answer
> 0 votes
# Desmos, 21 bytes

```
f(a,b,c,d)=3a+4b+5c-d

```

Try It On Desmos!

Input is a function where \\$a=3\ \text{par holes},b=4\ \text{par holes},c=5\ \text{par holes},d=\text{difficulty rating}\\$

Example Test Case:

# Answer
> 0 votes
# Stax, 13 bytes

```
╨E⌡u╥Diüaë¬~▼

```

Run and debug it

If I can find a way to read in the array and the number as is instead of evaluating them from string, this program will be shorter.

# Answer
> 0 votes
# PHP, 66 bytes

```
list($a,$b,$c,$d,$e)=$argv;echo eval("return 3*$b+4*$c+5*$d-$e;");

```

---

---

first attempt:

# PHP, 145 bytes

```
<?php $a=$_SERVER['argv'];$b=[0,3,4,5,-1];$r=array_map(function($x,$y){return$x*$y;},$a,$b);echo array_reduce($r,function($i,$c){return$i+=$c;});

```

## Ungolfed:

```
<?php
$a = $_SERVER['argv'];
$b = [0,3,4,5,-1]; // the first element always contains the filename, and is hereby disregarded
$r = array_map(function($x,$y){return $x*$y;},$a,$b);
echo array_reduce($r, function ($i,$c) {return $i+=$c;});

```

---

---

With 10, 5 and 3 holes respectivly, and a difficulty of 5, it's to be called with `$ php codegolf.php 10 5 3 5`

Note: it throws a warning, as we multiply a string with zero. Add 1 byte for the error-supression-operator to get rid if that.

# Answer
> 0 votes
# Julia 1.0, 13 bytes

```
v->[3:5;-1]'v

```

Try it online!

improvement of Dennis's Julia 0.5 answer

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


title: The Solitude of Prime Numbers

text:
# Question
Title: The Solitude of Prime Numbers
Recently I read the novel "The Solitude of Prime Numbers" where the main characters are somewhat compared to twin prime numbers ("*always together, but never touching*").

> A **twin prime** is a prime number that is either \\$\require{cancel}2\\$ less or \\$2\\$ more than another prime number —for example, the twin prime pair \\$(41, 43)\\$. In other words, a twin prime is a prime that has a prime gap of two. Sometimes the term twin prime is used for a pair of twin primes; an alternative name for this is prime twin or prime pair. Wikipedia

Although I didn't like much the depressing novel, and since I have fallen into PPCG lately, that raised a question in my mind...

## Task:

Given a positive integer number \\$N \> 4\\$, **find the *lonely prime numbers* (AKA isolated prime numbers) between the closest couples of twin primes**.

Please note that in this case with the term *lonely prime numbers*, I mean *all the prime numbers that are not twin primes and between couples of twin primes*. That's why \\$N \> 4\\$ because the first two couples of prime numbers are \\$(3, 5)\\$ and \\$(5, 7)\\$.

## Example:

1. \\$N = 90\\$.
2. Find the first two couples of twin primes \\$\< N\\$ and \\$\> N\\$. They are: \\$(71, 73)\\$ and \\$(101, 103)\\$.
3. Find the *lonely primes* in the range \\$\> 73\\$ and \\$\< 101\\$.
4. They are: \\$79, 83, 89, 97\\$.

## Special cases:

\- If N is in between two twin prime numbers, find the closest couples of twin primes \\$\> N+1\\$ and \\$\< N-1\\$. Example: \\$N=72\\$, find the closest couples of twin primes \\$\> 73\\$ and \\$\< 71\\$ then exclude from the list \\$71\\$ and \\$73\\$ because they are not \*lonely primes\*. So for \\$N = 72\\$ the expected result is: \\$67, \cancel{71}, \cancel{73}, 79, 83, 89, 97\\$ \- If N belongs to a couple of twin primes, for example \\$N = 73\\$, the closest couples of twin primes are \\$(71, 73)\\$ and \\$(101, 103)\\$. If \\$N = 71\\$, the closest couples of twin primes are \\$(59, 61)\\$ and \\$(71, 73)\\$.

## Test cases:

```
N = 70   >  Lonely primes are:  67
N = 71   >  Lonely primes are:  67
N = 72   >  Lonely primes are:  67, 79, 83, 89, 97 (not the twins 71 and 73)
N = 73   >  Lonely primes are:  79, 83, 89, 97
N = 90   >  Lonely primes are:  79, 83, 89, 97
N = 201  >  Lonely primes are:  211, 223
N = 499  >  Lonely primes are:  467, 479, 487, 491, 499, 503, 509

```

## Rules:

* Write a full program or function that will take the number N from standard input.
* Output the list of *lonely primes* in a readable format as csv, list, array, etc.
* Shortest code wins.
* Please include (when possible) a testable online fiddle.

# Answer
> 2 votes
# Actually, 47 bytes

This solution deals with the case where `n` is between two twin primes, by checking if the **lower bound** is the **larger** of a pair of twin primes (eliminating the twin prime to the left of us from being our lower bound) and if the **upper bound** is the **smaller** of a pair of twin primes (eliminating the twin prime to the right of us from being our upper bound). To prevent the twin primes from being included in our range once we have the lower and upper bounds, we need to remove primes `p` where `p-2` OR `p+2` are prime, hence the logical OR and negate in the code.

This is a little long and can probably be golfed further. Golfing suggestions welcome. Try it online!

```
╗1`╜+;⌐p@p&`╓F╜+1`╜-;¬p@p&`╓F╜-x`;;¬p@⌐p|Y@p&`░

```

**Ungolfing**

```
╗         Store implicit input n in register 0.

1`...`╓   Get the first value x for which the following function f returns a truthy value.
  ╜         Push n from register 0.
  +         Add x to n.
  ;⌐        Duplicate n+x and add 2 to a copy of n+x.
  p         Check if n+x+2 is prime.
  @p        Swap n+x to TOS and check if n+x is prime.
  &         Logical AND the two results.
F         Push the first (and only) result of previous filtering
╜+        Add that result to n to get the upper bound for our solitude.

1`...`╓   Get the first value x for which the following function f returns a truthy value.
  ╜         Push n from register 0.
  -         Subtract x from n.
  ;¬        Duplicate n-x and subtract 2 from a copy of n-x.
  p         Check if n-x-2 is prime.
  @p        Swap n-x to TOS and check if n-x is prime.
  &         Logical AND the two results.
F         Push the first (and only) result of previous filtering.
╜-        Subtract that result from n to get the lower bound for our solitude.

x`...`░   Push values of the range [a...b] where f returns a truthy value. Variable m.
  ;;        Duplicate m twice.
  ¬p        Check if m-2 is prime.
  @⌐p       Check if m+2 is prime.
  |Y        Logical OR the results and negate.
             This eliminates any numbers with neighboring primes.
  @p        Check if m is prime.
  &         Logical AND primality_check(m) and the previous negation.
             This keeps every other prime number in the range.

```

# Answer
> 8 votes
## PowerShell v2+, ~~237~~ ~~149~~ ~~147~~ ~~231~~ ~~216~~ ~~181~~ ~~174~~ ~~169~~ 166 bytes

```
param($n)filter f($a){'1'*$a-match'^(?!(..+)\1+$)..'}for($i=$n;!((f $i)-and(f($i+2)))){$i++}for(){if(f(--$i)){if((f($i-2))-or(f($i+2))){if($i-lt$n-1){exit}}else{$i}}}

```

Takes input `$n`. Defines a new function `f` as the regex prime function (here returning a Boolean if the input is a prime or not).

The next part sets `$i` to be equal to `$n`, then loops upward until we find the *bottom* half of our twin prime pair upper bound. E.g., for input `90`, this stops at `$i=101`.

Then, we loop from the upper bound downward. I know, it looks like an infinite loop, but it'll eventually end.

If the current number is a prime (`f(--$i)`), *but* its `+/- 2` *isn't* a prime, we add `$i` to the pipeline. However, if its `+/- 2` is a prime, we check whether we're lower than `$n-1` (i.e., to account for the situation when it's inside a twin prime pair), at which point we `exit`. At program completion, the pipeline is printed to screen via implicit `Write-Output`.

*NB - Due to the looping structure, prints the primes in descending order. OP has clarified that's OK.*

### Examples

*Output here is space-separated, as that's the default stringification method for an array.*

```
PS C:\Tools\Scripts\golfing> 70,71,72,73,90,201,499,982|%{"$_ --> "+(.\the-solitude-of-prime-numbers.ps1 $_)}
70 --> 67
71 --> 67
72 --> 97 89 83 79 67
73 --> 97 89 83 79
90 --> 97 89 83 79
201 --> 223 211
499 --> 509 503 499 491 487 479 467
982 --> 1013 1009 997 991 983 977 971 967 953 947 941 937 929 919 911 907 887

```

# Answer
> 4 votes
# Haskell, 105 bytes

```
p x=all((>0).mod x)[2..x-1]
a%x=until(\z->p z&&p(z+2*a))(+a)x
f n=[x|x<-[(-1)%n+1..1%n-1],p x,1%x>x,(-1)%x<x]

```

Try it Online

# Answer
> 3 votes
# JavaScript, ~~186~~ ~~183~~ ~~168~~ 158 Bytes

```
// solution:
function d(d){function p(n){for(i=n;n%--i;);return!--i}u=d;for(;!p(d--)||!p(--d););for(;!p(u++)||!p(++u););for(;++d<u;)if(p(d)&&!p(d-2)&&!p(d+2))console.log(d)}

// runnable test cases:
console.info('Test ' + 70);
d(70);
console.info('Test ' + 71);
d(71);
console.info('Test ' + 72);
d(72);
console.info('Test ' + 73);
d(73);
console.info('Test ' + 90);
d(90);
console.info('Test ' + 201);
d(201);
console.info('Test ' + 499);
d(499);
```

# Answer
> 3 votes
# Jelly, ~~29~~ 27 bytes

```
ÆRf+¥2ṪæRÆn+2Ẓ¬Ɗ¿ð_;+ẒẸµÐḟ2

```

Try it online!

-2 bytes thanks to Unrelated String

## How it works

```
ÆRf+¥2ṪæRÆn+2Ẓ¬Ɗ¿ð_;+ẒẸµÐḟ2 - Main link. Takes N on the left
ÆR                          - Yield all primes ≤ N; Z
    ¥2                      - Group the previous 2 links into a dyad f(Z, 2):
   +                        -   Add 2 to each element in Z
  f                         -   Keep all elements in both Z and Z+2
      Ṫ                     - Take the last number
                                 This is the largest twin prime < N, T

                ¿           - While loop:
               Ɗ            -   Condition f(X):
           +2               -     X+2
              ¬             -     Is not:
             Ẓ              -     Prime
         Æn                 -   Body: X is the next prime after X

       æR                   - Prime range; Yield a list of primes T ≤ P ≤ X

                 ð     µ  2 - Define a dyadic chain f(P, 2):
                  _         -   P-2
                    +       -   P+2
                   ;        -   [P-2, P+2]
                     Ẓ      -   Test if each is prime
                      Ẹ     -   Are either true?
                        Ðḟ  - Filter the range T ≤ P ≤ X, keeping those for which f(P, 2) is false

```

# Answer
> 2 votes
# PHP, 207 bytes

~~47~~ 54 bytes for the `is_prime` function that PHP does not have. I´d beat Mathematica without that. :-D

```
function p($n){for($i=$n>1?$n:4;$n%--$i;);return$i<2;}if(p($n=$argv[1])&p($n+2)|$z=p($n-1)&p($n+1))$n-=2;for($n|=1;!p($n)|!p($n-2);$n--);for($z++;$z--;$n+=2)for(;$n+=2;)if(p($n)){if(p($n+2))break;echo"$n,";}

```

run with `-r`. prints a trailing comma.

**breakdown**

```
// is_prime function:
// loops from $n-1 down to 1, breaks if it finds a divisor.
// returns true if divisor is <2 (==1)
// special case $n==1: initialize $i=4 to prevent warnings
function p($n){for($i=$n>1?$n:4;$n%--$i;);return$i<2;}

// is $n between primes?
if($z=p(1+$n=$argv[1])&p($n-1)) // set $z to go to the _second_ twin pair above
    $n-=2;
// no:
else
    if(p($n)&p($n+2))$n-=2;     // $n is part of the upper pair
    // p($n)&p($n-2):           // $n is part of the lower pair
    // else:                    // this is a lonely (isolated) prime

// 1. find closest twins <=$n
for($n|=1;!p($n)|!p($n-2);$n--);

// 2. list primes until the next twin primes
L:
for(;$n+=2;)if(p($n))
    if(p($n+2))break;       // next twin primes found: break loop
    else echo"$n,";         // isolated prime: print

// 3. if ($z) repeat (once)
$n+=2;  // skip twin pair
if($z--)goto L;

```

**Note**:

The `is_prime` function actually returns `true` for `$n<2`; but at least it doesn´t produce a warning. Insert `$n=` before `$n>1` to fix.

# Answer
> 1 votes
# Mathematica, ~~169~~ 157 bytes

```
Select[PrimeQ]@Sort@Flatten@{If[q@#,0,#],Most@NestWhileList[i-=2;#+i&,#,!q@#&]&/@(i=3;q=PrimeQ@#&&Or@@PrimeQ[{2,-2}+#]&;#+{1,-1}(1+Boole@PrimeQ[{1,-1}+#]))}&

```

# Answer
> 1 votes
## Racket 245 bytes

```
(λ(n)(let((pl(reverse(let lp((n n)(t 0)(ol '()))(set! t(prev-prime n))(if(and(>(length ol)0)
(= 2(-(car ol)t)))(cdr ol)(lp t 0(cons t ol)))))))(let lq((n n)(t 0)(ol pl))(set! t(next-prime n))
(if(= 2(- t(car ol)))(cdr ol)(lq t 0(cons t ol))))))

```

Ungolfed version:

```
(require math)
(define f
  (lambda(n)
    (let ((pl
           (reverse
            (let loop ((n n) (t 0) (ol '()))
              (set! t (prev-prime n))
              (if (and
                   (> (length ol) 0)
                   (= 2 (- (car ol) t)))
                  (cdr ol)
                  (loop t 0 (cons t ol)))))))
      (let loop2 ((n n) (t 0) (ol pl))
        (set! t (next-prime n))
        (if (= 2 (- t (car ol)))
            (cdr ol)
            (loop2 t 0 (cons t ol))))))
  )

(f 90)

```

Output:

```
'(97 89 83 79)

```

# Answer
> 1 votes
## Racket 228 bytes

```
(λ(n)(let*((t 0)(lr(λ(l i)(list-ref l i)))(pl(drop(reverse(for/list((i(in-naturals))#:when(prime? i)#:final(and(> i n)
(= 2(- i t))))(set! t i)i))2)))(for/list((i(length pl))#:break(= 2(-(lr pl i)(lr pl(add1 i)))))(lr pl i))))

```

Disadvantage of this version is that it finds all prime numbers till N and not just those around N.

Ungolfed version:

```
(define (f n)
  (let* ((t 0)
         (lr (λ(l i) (list-ref l i)))
         (pl (drop(reverse
                   (for/list ((i (in-naturals))
                              #:when (prime? i)
                              #:final (and
                                       (> i n)
                                       (= 2 (- i t))))
                     (set! t i)
                     i)) 2)))
    (for/list ((i (length pl))
               #:break (= 2 (- (lr pl i) (lr pl (add1 i)))) )
      (lr pl i)))
)

```

Testing:

```
(f 90)

```

Output:

```
'(97 89 83 79)

```

# Answer
> 1 votes
# Python 2.7: 160 bytes

```
t=lambda n:all(n%d for d in range(2,n))
def l(n):
 i=n
 while t(i)*t(i+2)-1:i+=1
 while t(n)*t(n-2)-1:n-=1
 print[x for x in range(n,i)if t(x)&~(t(x-2)|t(x+2))]

```

suggestions are welcome :)

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


title: Shotgun Numbers

text:
# Question
Title: Shotgun Numbers
The Shotgun numbers are a sequence with a rather simple definition but some interesting structure. Start with the natural numbers:

```
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

```

Now take all numbers at indices divisible by **2**, group them into pairs, and swap the numbers in each pair:

```
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ...
   ^     ^     ^     ^      ^       ^       ^
    <--->       <--->        <----->         <----
1, 4, 3, 2, 5, 8, 7, 6, 9, 12, 11, 10, 13, 16, ...

```

Now do the same with indices divisible by **3**:

```
1, 4, 3, 2, 5, 8, 7, 6, 9, 12, 11, 10, 13, 16, ...
      ^        ^        ^           ^
       <------>          <--------->
1, 4, 8, 2, 5, 3, 7, 6, 10, 12, 11, 9, 13, 16, ...

```

And then for **4**, **5**, **6**, and so on:

```
1, 4, 8, 2, 5, 3, 7, 6, 10, 12, 11, 9, 13, 16, ...
1, 4, 8, 6, 5, 3, 7, 2, 10, 12, 11, 14, 13, 16, ...
1, 4, 8, 6, 12, 3, 7, 2, 10, 5, 11, 14, 13, 16, ...
1, 4, 8, 6, 12, 14, 7, 2, 10, 5, 11, 3, 13, 16, ...
...

```

After **k** such steps, the first **k+1** numbers will be fixed. So we can define the infinite sequence of Shotgun numbers as the limit of letting **k** go to infinity. The first 66 numbers are:

```
1, 4, 8, 6, 12, 14, 16, 9, 18, 20, 24, 26, 28, 22, 39, 15, 36, 35, 40, 38, 57, 34, 48, 49, 51, 44,
46, 33, 60, 77, 64, 32, 75, 56, 81, 68, 76, 58, 100, 55, 84, 111, 88, 62, 125, 70, 96, 91, 98, 95,
134, 72, 108, 82, 141, 80, 140, 92, 120, 156, 124, 94, 121, 52, 152, 145, ...

```

**Fun fact:** Despite being obtained by only permuting the natural numbers, this sequence does not contain any primes.

## The Challenge

Given an integer `n > 0`, find the `n`th Shotgun number. You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and return the output or print it to STDOUT (or closest alternative).

This is code golf, so the shortest submission (in bytes) wins.

## Leaderboards

This is getting more answers than I thought, as well as several people competing in the same language. So here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

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

```
# Language Name, N bytes

```

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

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

```

```
function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;var n=e.body_markdown.split("\n");try{t|=/^#/.test(e.body_markdown);t|=["-","="].indexOf(n[1][0])>-1;t&=LANGUAGE_REG.test(e.body_markdown)}catch(r){}return t}function shouldHaveScore(e){var t=false;try{t|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading);answers.sort(function(e,t){var n=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0],r=+(t.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0];return n-r});var e={};var t=0,c=0,p=-1;answers.forEach(function(n){var r=n.body_markdown.split("\n")[0];var i=$("#answer-template").html();var s=r.match(NUMBER_REG)[0];var o=(r.match(SIZE_REG)||[0])[0];var u=r.match(LANGUAGE_REG)[1];var a=getAuthorName(n);t++;c=p==o?c:t;i=i.replace("{{PLACE}}",c+".").replace("{{NAME}}",a).replace("{{LANGUAGE}}",u).replace("{{SIZE}}",o).replace("{{LINK}}",n.share_link);i=$(i);p=o;$("#answers").append(i);e[u]=e[u]||{lang:u,user:a,size:o,link:n.share_link}});var n=[];for(var r in e)if(e.hasOwnProperty(r))n.push(e[r]);n.sort(function(e,t){if(e.lang>t.lang)return 1;if(e.lang<t.lang)return-1;return 0});for(var i=0;i<n.length;++i){var s=$("#language-template").html();var r=n[i];s=s.replace("{{LANGUAGE}}",r.lang).replace("{{NAME}}",r.user).replace("{{SIZE}}",r.size).replace("{{LINK}}",r.link);s=$(s);$("#languages").append(s)}}var QUESTION_ID=47338;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/;var NUMBER_REG=/\d+/;var LANGUAGE_REG=/^#*\s*([^,]+)/
```

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

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

# Answer
> 5 votes
# Pyth, 19 ~~22~~

```
u-G*H^_!%GH/GHrhQ2Q

```

A fairly naive implementation of @PeterTaylor's golfscript answer.

Try it online here

This uses the same tricks to convert a while loop into a fold as the other Pyth program below does.

---

```
u+G**H!%GHty%/GH2rhQ2Q

```

A naive copy of @Sp3000's algorithm translated to Pyth.

You can try it online here

Uses reduce (python's name for fold) to emulate the while loop. It enumerates over the `range(input, 2)` which in Pyth works out to `range(2, input)[::-1]`. The other Pyth-related golfs involves using `not` instead of `<2` and using `y`'s hidden mode of doubling the value of numeric arguments.

# Answer
> 21 votes
# \>\<\>, ~~52~~ 45 bytes

**Esolangs page for \>\<\>**

```
i:&&:&1-?vn;
2*1-*+20.>:&:&%1(&:&*{:}&:1-&,2%

```

There's a lot of copying and moving elements around, thanks to the several modulo and multiplications needed. The logic is exactly the same as my Python solution.

Takes input via a code point from STDIN, e.g. `"!" = 33 -> 75`.

# Answer
> 17 votes
# Python 2, 58 bytes

```
i=n=input()
while~-i:n+=(n%i<1)*i*(n/i%2*2-1);i-=1
print n

```

Like most of the other answers, the idea is to work backwards.

---

Let's call step `k+1` step `i`, so that on step `i` all the multiples of `i` are swapped. We need two simple observations:

* Position `n` in the array is only swapped at step `i` if `n` is divisible by `i`,
* To tell whether you're the lower number or the higher number in the swap, look at `n/i mod 2`. If this is 1 you're the lower number (and will swap up), otherwise you're the higher number (and will swap down).

This gives us an algorithm for working backwards. Let's try it with 6, starting from the last step (step `i = 6`):

```
Step 6: Position 6 swaps with position 12 (6 is divisible by 6, 6/6 = 1 == 1 mod 2)

```

So now we know the number came from position 12. Then:

```
Step 5: No swap (12 not divisible by 5)
Step 4: Position 12 swaps with position 16 (12 is divisible by 4, 12/4 = 3 == 1 mod 2)

```

So now we know it came from 16 before that. Finally:

```
Step 3: No swap (16 not divisible by 3)
Step 2: Position 16 swaps with position 14 (16 divisible by 2, 16/2 = 8 == 0 mod 2)

```

Since this is the first step (remember, `k+1`), we're done and the number that ends up in position 6 originally came from position 14, i.e. the 6th shotgun number is 14.

So now for the Python explanation:

```
i=n=input()             Read input, and store into i (step) and n (position)
while~-i:               while i-1 != 0:, or since we're descending with i this is just while i>1:
  n+=                   Add to the current position...
    (n%i<1)*            1* whatever's next if n is divisible by i, otherwise 0* (i.e. nothing)
    i*                  How many positions n might go up/down
    (n/i%2*2-1)         n/i%2 tell us higher/lower, *2-1 maps 0 or 1 to -1 (down) or +1 (up)
  i-=1                  Decrement the step number
print n                 Output

```

# Answer
> 6 votes
# Haskell, 68 bytes

```
n#k|mod k(2*n)<1=k-n|mod k n<1=k+n|k>0=k
s n=foldr((.).(#))id[2..n]n

```

Probably further golfable, especially the first row. This defines a function `s` that takes `n` and returns the `n`th shotgun number.

```
map s [1..66]
[1,4,8,6,12,14,16,9,18,20,24,26,28,22,39,15,36,35,40,38,57,34,48,49,51,44,46,33,60,77,64,32,75,56,81,68,76,58,100,55,84,111,88,62,125,70,96,91,98,95,134,72,108,82,141,80,140,92,120,156,124,94,121,52,152,145]

```

### Explanation

The helper function `#` takes in two numbers `n` and `k`, and returns the `k`th number in the list defined by applying the pair swap operation to every `n`th number. For example, applying it to the first 20 numbers with `n = 4` yields this:

```
map (4#) [1..20]
[1,2,3,8,5,6,7,4,9,10,11,16,13,14,15,12,17,18,19,24]

```

The result of `s n` is obtained by reducing ("folding") the list `[2..n]` by the second-order function `(.).(#)`, which takes in a number `m` and a function `f` (initially the identity function `id`), and returns a function that takes `k` and returns `f (m # k)`. For example, in the case `n = 4` the list `[2,3,4]` is reduced to a function that takes `k` and returns `id (4 # (3 # (2 # k)))`. The `id` is only needed for the base case `n = 1`, where the list is empty. Finally, we give this function the input `k = n`, obtaining the `n`th shotgun number.

# Answer
> 6 votes
# CJam, 32 bytes

Just following the spec to the point. Running the instructions on a larger set so as to not affect the nth number.

```
ri:N)2#,:)N{))/2/{:)~\@}%:+}/N(=

```

Try it online here

# Answer
> 5 votes
# Python 2, ~~97~~ 79 chars

```
g=lambda n,k:n>1and g(n-1,k-(k%n<1)*n*(-1)**(k/n%2))or k
n=input()
print g(n,n)

```

It determines for each index the correct value by recursively chasing the number backwards. The algorithm was independent discovered.

edit: Now it only prints the `n`th number instead of the first `n` numbers. Of course an iterative approach would be shorter, but I don't want to copy Sp3000's code.

# Answer
> 5 votes
# Ruby, 92 bytes

```
def s(d,n)
d==1?n:s(d-1,n%d==0?n+(n%(d*2)==0?-d :d):n)
end
n=ARGV[0].to_i
print s(n,n).to_s

```

My first code golf effort. Not based on any other answer.

---

Now that I've looked at some of the others though, I notice that most just define a function, not a complete program that accepts input and produces output. The OP asked for a complete program with input and output. Is it customary to ignore such requirements?

---

# 84 Bytes

```
n=ARGV[0].to_i
d=n
while d>1
n+=(n%d==0?(n%(d*2)==0?-d :d):0)
d-=1
end
print n.to_s

```

After looking at other answers and realizing that an iterative solution is possible.

# Answer
> 4 votes
# Common Lisp, ~~113~~ 91

(iterative: 91)

```
(defun s(n)(do((r n(1- r)))((= r 1)n)(if(= 0(mod n r))(incf n(* r(if(oddp(/ n r))1 -1))))))

```

(original, recursive: 113)

```
(defun s(n &optional(r n))(cond((= r 1)n)((= 0(mod n r))(s(+ n(* r(if(oddp(/ n r))1 -1)))(1- r)))(t(s n(1- r)))))

```

## Example

With the recursive version:

```
(trace s)
(s 10)

  0: (S 10)
    1: (S 20 9)
      2: (S 20 8)
        3: (S 20 7)
          4: (S 20 6)
            5: (S 20 5)
              6: (S 15 4)
                7: (S 15 3)
                  8: (S 18 2)
                    9: (S 20 1)
                    9: S returned 20
         ...
    1: S returned 20
  0: S returned 20

```

## Tests

Checks and measures for iterative version:

```
(let ((list '(1 4 8 6 12 14 16 9 18 20 24 26 28 22 39 15 36 35 40 38 57 34 48 49 51 44
              46 33 60 77 64 32 75 56 81 68 76 58 100 55 84 111 88 62 125 70 96 91 98 95
              134 72 108 82 141 80 140 92 120 156 124 94 121 52 152 145)))
  (time
   (loop for r in list
         for n from 1
         always (= r (s n)))))

 => T

Evaluation took:
  0.000 seconds of real time
  0.000000 seconds of total run time (0.000000 user, 0.000000 system)
  100.00% CPU
  807,160 processor cycles
  32,768 bytes consed

```

# Answer
> 4 votes
# Haskell, 79 bytes

```
1#i=i
s#i|i`mod`(2*s)==0=(s-1)#(i-s)|i`mod`s==0=(s-1)#(i+s)|1<2=(s-1)#i
p n=n#n

```

Usage: `p 66` which outputs `145`

Not much to explain: The function `#` recursively calculates the shotgun number at position `i` of step `s`. `p n` returns the number at position `n` of step `n`.

# Answer
> 4 votes
## k, 41 bytes

`{{x+$[y!x;0;$[2!_x%y;y;-y]]}/[x;|2+!x-1]}`

```
 / apply to an int
 {{x+$[y!x;0;$[2!_x%y;y;-y]]}/[x;|2+!x-1]} 42
111
 / apply to 1 through 66
 {{x+$[y!x;0;$[2!_x%y;y;-y]]}/[x;|2+!x-1]}'1+!66
1 4 8 6 12 14 16 9 18 20 24 26 28 22 39 15 36 35 40 38 57 34 48 49 51 44 46 33 60 77 64 32 75 56 81 68 76 58 100 55 84 111 88 62 125 70 96 91 98 95 134 72 108 82 141 80 140 92 120 156 124 94 121 52 152 145

```
* `{...}` lambda, x and y are the implicit 1st and 2nd argument
* `$[b;t;f]` ternary operator, evaluates b followed by t/f respectively
* `b!a` a modulo b
* `_` floor, casts the result of the division to an int
* `%` division
* `{...}/[x;y]` prime {...} with x and apply over the list y, is equivalent to f\[f\[..f\[f\[x;y0\];y1\];..yn-1\];yn\]
* `|` reverse
* `!` iota function, generate list 0 through n-1

# Answer
> 4 votes
# Mathematica, ~~53~~ 49 bytes

```
(For[i=n=#,n>1,--n,If[n∣i,i+=Mod[i,2n]2-n]];i)&

```

I decided to golf my reference implementation. The  is the Unicode symbol for "divides", and counts for 3 bytes. Otherwise, this uses the same algorithm as everyone else.

It defines an unnamed function which takes `n` as a single parameter and returns the `n`th Shotgun number.

# Answer
> 4 votes
# Julia, ~~61~~ 57 bytes

```
n->(i=n;while~-i!=0 n+=(n%i<1)*i*(n÷i%2*2-1);i-=1;end;n)

```

This creates an unnamed function which takes a single argument `n` and returns the `n`th shotgun number. To call it, give it a name, e.g. `f=n->(...)`.

Examples:

```
julia> for i = 1:10 println(f(i)) end
1
4
8
6
12
14
16
9
18
20

```

Currently this is based on @Sp3000's awesome Python answer. I'll revisit this soon because there must be a shorter way to do this in Julia than what I've done here. Any input is welcome, as always.

# Answer
> 4 votes
## GolfScript, 27 chars

```
~.,(~%{):i\.@%!~)1$i/?i*-}/

```

### Explanation

If `f(i, n)` is the value at position `n` after `i-1` transformations, we have

```
f(1, n) = n
f(i, n) = f(i - 1, n % i == 0 ? (((n / i - 1) ^ 1) + 1) * i : n)  for i > 1

```

where `^` denotes bitwise xor; given input `n`, we want to compute `f(n, n)`.

The conversion from a recursive function to a loop is uninteresting; what is interesting is the way in which

```
n % i == 0 ? (((n / i - 1) ^ 1) + 1) * i : n

```

can be rewritten. The more obvious approach is to say that it must be

```
n + (n % i == 0 ? i : 0) * g(n / i)

```

for some `g`. Obviously `g` alternates between `1` and `-1`, as the positions swap alternately up and down; since `g(1) = 1` (because `1` swaps up to `2`), we have

```
n + (n % i == 0 ? i : 0) * -1**(1 + n / i)

```

where `**` denotes exponentiation. The final savings come from rewriting this as

```
n - i * (n % i == 0 ? -1 : 0)**(n / i)

```

### Dissection

```
~             # Evaluate input to get n
.,(~%{        # For n-1 downto 1...
  ):i         #   Let i be that value + 1, so for i = n downto 2...
  \.@%!       #   Find n % i == 0 ? 1 : 0
  ~)          #   Negate
  1$i/?       #   Raise to the power of n/i
  i*-         #   Multiply by i and subtract
}/

```

# Answer
> 4 votes
## CJam, 24 bytes

```
l~__(,f-{_Imd!~)\#I*-}fI

```

Online demo

This is a port of my GolfScript answer, borrowing the loop from Martin's CJam answer and exploiting CJam's `divmod` operator. (I said it would be useful!).

# Answer
> 3 votes
# J, ~~34~~ 32 bytes

```
   (]+[*(1-~2*2|%~)*0=|)/@(_1}2+i.)

   ((]+[*(1-~2*2|%~)*0=|)/@(_1}2+i.)) every 1+i.20  NB. running with inputs 1..20
1 4 8 6 12 14 16 9 18 20 24 26 28 22 39 15 36 35 40 38

```

Will try to golf it a bit more and add some explanation later.

Try it online here.

# Answer
> 3 votes
# GML, 76 bytes

```
n=argument0;i=n;while~-1{n+=(n mod i<1)*i*(n/i mod 2*2-1)i--}show_message(n)

```

Information about GML

# Answer
> 3 votes
# CJam, ~~28~~ 27 byte

So this is slightly embarrassing... before posting this, I tried golfing this myself and got to 30 bytes in CJam. None of the existing answers have beaten that yet. In the meantime I also managed to shave off three more bytes. There *is* a shorter Pyth solution in a comment, but nothing shorter has been posted in an answer, so here it is. Maybe it inspires the APL/J people to try a bit harder (or someone actually post the Pyth solution), before I have to accept my own answer. ;)

```
l~__(,f-{_I_+%_+I-_zI=*+}fI

```

Test it here.

## Explanation

```
l~                          "Read input N and eval.";
  __(,                      "Duplicate twice, create range [0 1 2 ... N-2].";
      f-                    "Subtract each from N, giving [N N-1 N-2 ... 2].";
        {               }fI "For each element, storing the element in I.";
         _I_+%_+I-          "Compute 2(N % 2I)-I - the shuffling offset";
                  _zI=      "Check that this offset is ±I.";
                      *+    "Multiply the offset by this boolean and update to N.";

```

# Answer
> 2 votes
# TI-Basic 83/84, 40 bytes

```
Input A:For(I,A,2,~1:A+(AfPart(I/2)-1)I(1>IfPart(A/I->A:End:A

```

Information about TI-Basic

# Answer
> 1 votes
# Ruby, ~~57~~ 47 bytes

This is essentially Sp3000's Python solution (with xnor's suggestion) translated to Ruby. I could probably golf it down in a few places though.

```
->n{n.downto(2).map{|i|n+=i*(n/i%2-~-n/i%2)};n}

```

# Answer
> 0 votes
# Stax, 13 bytes

```
╠¼│σ╣Gp☺πΩ■φ├

```

Run and debug it

Same idea as Peter Taylor's answer, and almost the same code.

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


title: Print the Najdorf Sicilian

text:
# Question
Title: Print the Najdorf Sicilian
The Najdorf Variation of the Sicilian Defence is an opening often played at the highest level of chess. It is named after GM Miguel Najdorf and is known for being extremely sharp and theory heavy.

Your task is to write a program that, given a Boolean-like input, prints a chessboard representation of the opening from either White or Black perspective.

## I/O format

Your program can take any input that has two possible values. Boolean, Integer, etc.

Your program must output a square chessboard using your language's standard output (usually the console). Each piece must have a corresponding character (your choice). Black and white pieces must be different. Black and white squares are allowed to be the same, but you are allowed to have different characters for them if you wish.

Using standard notation and uppercase for white and lowercase for black, here are the two chessboards, though you are free to represent the pieces differently:

```
True               False

R   B K Q B   R    r n b q k b   r
P P P     P P P      p     p p p p
          N        p     p   n
      P N
                         N P
    n   p     p        N
p p p p     p      P P P     P P P
r   b k q b n r    R   B Q K B   R

```

This is , so shortest program in bytes wins!

# Answer
> 2 votes
# JavaScript (Node.js), ~~114~~ ~~89~~ 124 bytes

```
x=>`RNBQKB R
P  PPPP
P  P N

   np
  n
ppp  ppp
r bqkb r`.split`
`.sort(_=>x-1).map(n=>[...n].sort(_=>x-1).join``).join`
`

```

Try it online!

Take the grid and flip if needed.

# Answer
> 2 votes
# Jelly, 45 bytes

```
“¤d2ʂẠ⁽ÞWƓż:§ßẸ:ȯlEØƘƑṀ°@œḥƥßıẠ’ṃ“Œ⁼L»s8UṚ$¡G

```

`0` outputs from White's perspective, `1` from Black's.

As allowed in the question this uses other characters, the mapping is:

```
     Black  White
R      u      t
N      y      i
B      n      a
Q      p      b
K      r      l
P      d      c
empty  e      e

```

**Try it online!**
Or see **this version** which uses the letters from the question's example output and `.` for empty.

### How?

```
“...’ṃ“Œ⁼L»s8UṚ$¡G - Main Link: integer (from [0,1]), is_Black
“...’              - a large integer (stored in base 250)
      “Œ⁼L»        - dictionary word = "unpredictably"
     ṃ             - base-decompress (i.e. use "unpredictably" as the base-13 digits)
           s8      - split into slices eight long
                ¡  - repeat (is_Black) times:
               $   -   last two links as a monad:
             U     -     reverse each
              Ṛ    -     reverse
                       (equivalent to rotating a 1/2 turn)
                 G - format as a grid

```

# Answer
> 1 votes
# Jelly, 64 bytes

```
“¢ƙ]Ŀ°Mė8Ḃ“¢Ɠt:bẎ€^E“¡ṣḂƘ3^Q““¡⁽Ñ<Ṅ“Ṛ"ß“¡żN5Aʠṭm“¡ƬọG¢2|ie»UṚ$¡G

```

Try it online!

-6 bytes thanks to Lyxal by compressing the string using Jelly's built-in dictionary compressed string type.

## Explanation

```
“...»       The grid itself
     UṚ$    Reverse the order of rows and rows themselves (180 degree rotation)
        ¡   N times
         G  Formatted as a grid

```

# Answer
> 1 votes
# Vyxal `j`, ~~49~~ ~~45~~ 42 bytes

```
»¬℅→⁺w½]
oꜝ}l÷₄ǒẇ‡⋎ḋ∩P,*ø:⁺Ȯ∞J₀»k63ȯτ?ßṘ8/

```

Try it Online!

```
»...»           # Push compressed integer
     k6         # Push constant `0123456789abcdef`
       3ȯ       # Slice from 3rd character (`3456789abcdef`)
         τ      # Custom base conversion (to base13 with above)
          ?ßṘ   # If input is truthy, reverse
             8/ # Divide into 8 pieces
                # Implicit join by newline

```

# Answer
> 0 votes
# Charcoal, 46 bytes

```
”⟲.>Ｘc'eΣＺ\`KＯＸW⟲w‴PVＣτΣ\⁻μ⊖[⊖Ｕ×Ｋ↙mψQ{π!J”ＵＥ¹⟲Ｎ

```

Try it online! Link is to verbose version of code. Uses `0` for White's view and `4` for Black's view. Assumes that Black wants to see the board rotated rather than flipped. Explanation:

```
”⟲.>Ｘc'eΣＺ\`KＯＸW⟲w‴PVＣτΣ\⁻μ⊖[⊖Ｕ×Ｋ↙mψQ{π!J”

```

Print the compressed board.

```
ＵＥ¹

```

Space the characters out horizontally.

```
⟲Ｎ

```

Rotate the board as necessary.

42 bytes without the horizontal spacing:

```
✳Ｎ”⟲.>Ｘc'eΣＺ\`KＯＸW⟲w‴PVＣτΣ\⁻μ⊖[⊖Ｕ×Ｋ↙mψQ{π!J

```

Try it online! Link is to verbose version of code. Explanation: Prints the same compressed string, but in the input direction, which means that the string terminator is no longer required.

30 bytes by using a custom output format:

```
✳Ｎ“↶⊟∨dO9Ｒξ1d"⁼¦Q≕τm×↖ＷSLＱg℅R₂

```

Try it online! Link is to verbose version of code. Uses the following key:

```
.   Black pawn
!   White pawn
"   Black rook
#   Black knight
$   Black bishop
%   White rook
&   White knight
'   White bishop
(   Black king
)   Black queen
*   White king
+   White queen

```

---
Tags: code-golf, ascii-art, kolmogorov-complexity, chess
---


title: Make a Geiger Counter

text:
# Question
Title: Make a Geiger Counter
A Geiger counter is a device that is used to detect radiation.

We will be making a Geiger counter program.

As we all know, when radiation hits a computer program it removes exactly 1 byte at random. So a Geiger counter program is a program that itself does nothing, but when any byte is removed the modified program prints `beep`, to indicate the presence of radiation.

Answers will be scored in bytes with fewer bytes being better. Answers must be at least 1 byte.

Your program may print `beep` with trailing a newline or print a single newline for empty output, so long as it does so consistently. Your program may also use a different case for `beep` such as `BEEP`, `bEEP`, or `Beep` so long as it does so consistently.

# Answer
> 29 votes
# Lost, ~~303 293 263 253 238~~ 228 bytes

```
v^"peeb"<\>"beepvv"((>@@>>%%>>(((((([[[[[[\
>>>>>>>>>//>>>>>>>>>>>>>>/>>/>>>>>>>>>>>>>\\
>>>>>>>>//>>>>\>>>>>>>>>>/>>>>>>>>>>>>>>>>>\\
>/>>>>>>>/>>>>>>>>>>>>\>>>>>>>>>>>>>>>>>>>>>\\
>>>>>>>>>>>>>>>>>>>>>>\\>>>>\>>>>>>>>>>>>>>>>\

```

Try it online!

Verification script (borrowed from user 202729's answer). Unfortunately this can only test half of the code at a time, but rest assured I've tested the whole program.

Ouch, this was a tough one. I'll quote WW's deleted answer:

> Lost is perhaps the most interesting language for this challenge. In Lost the start location and direction of the pointer is entirely random, thus to make deterministic programs you must account for every possible start location and direction. At the same time, by the nature of this challenge you must also account for any single byte being removed.

Unfortunately, his answer didn't take into account removing newlines, which screwed everything up.

### Explanation:

(note that a few bytes might be off here and there)

First let's talk about the general structure of the code:

```
v^^"peeb"<<\/"beepvv"((>>>@@>>%%>>(((((([[[[[[[\       Processing line
>>>>>>>>>>>//>>>>>>>>>>>>>>>>>>>/>>>>>>>>>>>>>>\\      Beep line
>>>>>>>>>//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\     Back-up beep line
>//>>>>>>>>>>>>>>>>>>>>\\>>>>>>>>>>>>>>>>>>>>>>>>\\    Back-up return line
>>>>>>>>>>>>>>>>>>>>>>>>\\>>>>>>\>>>>>>>>>>>>>>>>>\    Return line

```

Everything but the processing line must be entirely composed of either `>` or one of `\/`. Why? Well, as an example, let's remove a newline:

```
v^^"peeb"<<\/"beepvv"((>>>@@>>%%>>(((((([[[[[[[\>>>>>>>>>>>//>>>>>>>>>>>>>>>>>>>/>>>>>>>>>>>>>>\\
>>>>>>>>>//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\
>//>>>>>>>>>>>>>>>>>>>>\\>>>>>>>>>>>>>>>>>>>>>>>>\\
>>>>>>>>>>>>>>>>>>>>>>>>\\>>>>>>\>>>>>>>>>>>>>>>>>\

```

The first line is now *way* longer than the rest of the block. If a pointer were to spawn on a non-`>\/` character with vertical movement, then it would get stuck in an infinite loop.

---

The biggest radiation detector part is the section at the end of each line.

```
 \
 \\
 >\\
 >>\\
 >>>\

```

Normally an IP passing through this from the first line would exit out the last line. However, if any character on the line is removed, then that line shifts down one, e.g:

```
 \
 \\
 >\\
 >\\
 >>>\

```

And the IP instead exits out the line that is missing a byte (with the exception of the last line, where it exits out the second to last).

From there, each of the first four lines will redirect to the second line:

```
v
>>>>>>>>>>
>>>>>>>>//
>/

```

Which will then lead into either one of the two `beep`ers.

```
v^"peeb"<<\/"beepvv"((>
>>>>>>>>>>//

```

If any of the bytes in the first `beep`er have been removed, then it instead goes to the second:

```
v^^"peb"<<\/"beepvv"((>
>>>>>>>>>>>//

```

Both `beep`ers then lead back to the first line and the terminating `@`.

Some other miscellaneous parts:

The `(((((([[[[[[[` is used to clear the stack when the pointer starts inside a pair of quotes and ends up pushing the whole first line to stack. It has to be so unfortunately long because the first newline can be removed to make the first line twice the size. Experimenting in generating the `beep` using arithmetic instead of quotes ended up longer.

The `\`s and `/`s scattered across the lines are there to golf bytes in the top line of code by redirecting the pointer to the correct lines. As most of the bottom lines are just filler, only the top line is able to be golfed. If anyone has any ideas for a shorter radiation proof stack clearer then what I've got now, feel free to comment.

# Answer
> 24 votes
# Hexagony, 38 bytes

```
.....;p;<>b;e;/<b;e;;p...@@.......;@..

```

Try it online!

Verification program.

---

## Explanation

We make use of Hexagony's auto-detection of hexagon side-length here.

If no bytes are removed, the program has side length 4 and looks like this:

If however, a byte is removed. There are 2 cases.

1. The removed byte is after the second `<`.

The execution flow would be:

There are 2 consecutive `@` on the 5th line, so even if one of them are removed, the IP will safely hit a `@`.
2. The removed byte is at or before the second `<`.

Then the second half will stay intact, and the IP is no longer redirected upwards by that `<`. Image of execution flow:

# Answer
> 24 votes
# Klein XXX, ~~144~~ ~~136~~ ~~128~~ ~~122~~ 114 bytes

This answer completes JoKing's challenge to make a Geiger counter that works in every Klein topology.

```
\..//!?......\
!>>>.>>>>>>>\\\
!.//@"peeb"(<.\.\
!\\\@"peeb"(<..//
>>>>>>>>>>>>////
\\>.>....(.////
>\....?!/1!!./

```

Try it online! Verification script

I don't believe it is really possible to make a perfectly satisfactory explanation. There are definitely aspects of this that *I'm* not aware of. It's just got too much going on. So the explanation below is a bit rough. I just want to get the *idea* across even if I gloss over a lot of the details.

The obvious next step is to create a version of Lost that can run on different Klein topologies, and create a Geiger counter in Lost that works in every topology. I don't know if really should be encouraging people to spend there time on such a awful and frustrating task, but I would certainly be willing to give a 500 rep bounty to someone who does the above.

## Explanation

The idea for this is to make a program with 2 parts.

The first is the path taken during normal execution. This path doesn't cross any boundaries, so we can avoid having to deal with the topology, and most importantly is very, very fragile. The idea here being that any disturbance to the program breaks the path and sends the ip flying off randomly.

The second part is a robust core. This part is sort of the opposite, it's role is to catch pointers that have gone off the path and direct them to the beeper. It needs to be impervious to radiation and it needs to catch as many stray pointers as possible.

The general strategy here was to build a program like this and just keep fixing the problems.

### The Path

The path looks like this:

```
\   / ?......\
!   .        \\
    @         \.\
!              //
              //
\\           //
 \....?! 1! ./

```

Some important about this things are

* We mostly use mirrors (`\` and `/`) rather than hard redirects. They are more fragile, and make it harder to get back on the path.
* The last character of every line is part of the path. This is required since removing them needs to break the path.
* It is sort of hexagon shaped. This is because a right angle turn can be simulated by a pole (e.g. the NE corner in 101) in the topology. So if we try to make a right angle turn at the corner there will end up being a topology that doesn't even need the mirror to make the turn.
* We have `?!/1` at the bottom and `?` near the end. This is to make sure that the bottom portion gets executed exactly once. Sometimes the pointer ends up back on the path after getting knocked off. This makes sure that if it hits the bottom portion of the path it doesn't get stuck in a loop there, and if it skips that portion it can't get to the end of the path.
* It covers basically the entire perimeter of the program. Hypothetically we only really need the left edge of the program but a full circuit is more fragile and we have to get to the other side anyway.

I experimented with both clockwise and anticlockwise paths. Ultimately clockwise should be better since you can make a shorter path. But I could not get it to work and some earlier attempts using this approach just never worked out. I managed to make an anticlockwise path so that's what's here. I might take some time with the lessons learned here to try clockwise again.

### The Core

The core is nothing too special. It is based off of the method used by pretty much every 2D Geiger counter we have two lines each which print `beep`, and we use the length of each to figure out which is damaged, so we can execute the other one. We surround this with ton of `>`s to force ips where we want them, this is the classic strategy for Lost programs.

# Answer
> 21 votes
# Hexagony, ~~34~~ 29 bytes

```
//..>;e;<b@;p;/|/;e;;\.b@;p<@

```

Try it online! Verification!

### Explanation:

Here is the normal code formatted into a proper hexagon using HexagonyColorer:

The double `//` at the beginning ensures that this path is always taken. If any character is removed, the `@` is removed from the path, either being shifted one back or being removed itself:

In this case, we've removed a character after the `|`, which makes it follow this path, printing `beep`:

If we instead remove a character from before the `|` (or the `|` itself), we follow the other beep printer:

We've then accounted for all possibilities and we only `beep` using the un-irradiated parts of the program.

# Answer
> 15 votes
# Self-modifying Brainfuck, ~~73~~ 63 bytes

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

```

Try it online! Verification!

The spaces in the middle of the code are actually representing NUL bytes.

### Explanation:

The code is split into two sections by 3 NUL bytes in the middle. Both of them basically prints `beep` if the other section is irradiated (with a couple of exceptions).

First, the `<<[[` at the beginning is to ensure that all `]`s are matched at any time. `[`s won't attempt to look for a matching `]` if the cell is positive, while `]`s *do*. If any `]` jumps back to one of these brackets it usually jumps back straight away because the cell is `0`.

The next part, `[[<<]]>` then checks if the length of section 2 is even. If so, it executes the other half of section 1, which prints `beep` using the `bbeepp` at the start of section 2.

```
[[.>>..>>.[,>]]]]

```

It then clears all of section 2 so it doesn't execute.

In section 2, we check if the length of section 1 and the NUL bytes is divisible by `3` with `+[<<<]>>`.

```
[[>]>>>.>>..>>.,+]

```

Similarly, we print `beep`.

# Answer
> 13 votes
# Z80Golf, ~~53~~ ~~36~~ 34 bytes

*-16 bytes thanks to @Lynn*
*-2 byte thanks to @Neil*

Since this is just Z80 machine code, there is a lot of unprintables in this one, so have a `xxd -r`-reversible hexdump:

```
00000000: ddb6 2120 10dd b615 280c 003e 62ff 3e65  ..! ....(..>b.>e
00000010: ffff 3e70 ff76 003e 62ff 3e65 ffff 3e70  ..>p.v.>b.>e..>p
00000020: ff76                                     .v

```

Try it online! (exhaustive tester in Python)

## Explanation

z80golf is Anarchy Golf's hypothetical Z80 machine, where `call $8000` is a putchar, `call $8003` is a getchar, `halt` makes the interpreter exit, your program is placed at `$0000`, and all other memory is filled with zeroes. Making programs radiation-proof in assembly is pretty hard, but a generically useful technique is using one-byte idempotent instructions. For example,

```
or c        ; b1    ; a = a | c

```

is just one byte, and `a | c | c == a | c`, so it can be made radiation-proof by just repeating the instruction. On the Z80, an 8-bit immediate load is two bytes (where the immediate is in the second byte), so you can load *some* values into registers reliably too. This is what I originally did at the beginning of the program, so you can analyze the longer variants I archived at the bottom of the answer, but then I realized that there is a simpler way.

The program consists of two independent payloads, where one of them could have been damaged by radiation. I check whether a byte was removed, and whether the removed byte was before the second copy of the payload, by checking the values of some absolute memory addresses.

First, we need to exit if no radiation was observed:

```
    or a, (ix+endbyte) ; dd b6 21 ; a |= memory[ix+0x0021]
    jr nz, midbyte     ; 20 10    ; jump to a halt instruction if not zero

```

If any byte was removed, then all the bytes will shift and `$0020` will contain the last `76`, so `$0021` will be a zero. We can afford radiating the beginning of the program, even though there is virtually no redundancy:

* If the jump offset `$10` is removed, then radiation will correctly be detected, the jump will not be taken, and the offset will not matter. The first byte of the next instruction will be consumed, but since it's designed to be resistant to byte removals, this doesn't matter.
* If the jump opcode `$20` is removed, then the jump offset `$10` will decode as `djnz $ffe4` (consuming the next instruction byte as the offset -- see above), which is a loop instruction -- decrement B, and jump if the result is not zero. Because `ffe4-ffff` is filled with zeroes (`nop`s), and the program counter wraps around, this will run the beginning of the program 256 times, and then finally continue. I am amazed this works.
* Removing the `$dd` will make the rest of the snippet decode as `or (hl) / ld ($1020), hl`, and then slide into the next part of the program. The `or` will not change any important registers, and because HL is zero at this point, the write will also cancel out.
* Removing the `$b6` will make the rest decode as `ld ($1020), ix` and proceed as above.
* Removing the `$21` will make the decoder eat the `$20`, triggering the `djnz` behavior.

Note that using `or a, (ix+*)` saves two bytes over `ld a, (**) / and a / and a` thanks to the integrated check for zero.

We now need to decide which of the two copies of the payload to execute:

```
    or (ix+midbyte)  ; dd b6 15
    jr z, otherimpl  ; 28 0c
    nop              ; 00
    ; first payload
    ld a, 'b'        ; 3e 62
    rst $0038        ; ff
    ld a, 'e'        ; 3e 65
    rst $0038        ; ff
    rst $0038        ; ff
    ld a, 'p'        ; 3e 70
    rst $0038        ; ff
midbyte:
    halt             ; 76
otherimpl:
    nop              ; 00
    ld a, 'b'        ; 3e 62
    ; ...            ; ...
    rst $0038        ; ff
endbyte:
    halt             ; 76

```

The two copies are separated by a nop, since a relative jump is used to choose between them, and radiation could have shifted the program in a way that would make the jump skip the first byte after the destination. Additionally, the nop is encoded as a zero, which makes it easy to detect shifted bytes. Note that it doesn't matter which payload is chosen if the switch itself is corrupted, because then both copies are safe. Let's make sure that it will not jump into uninitialized memory, though:

* Deleting `$dd` will make the next two bytes decode as `or (hl) / dec d`. Clobbers D. No big deal.
* Deleting `$b6` will create an undocumented longer encoding for `dec d`. Same as above.
* Deleting `$15` will read the `$28` instead as the offset, and execution will proceed at the `$0c`, as below.
* When `$28` disappears, the `$0c` is decoded as `inc c`. The payload does not care about `c`.
* Deleting `$0c` \- that's what the nop is for. Otherwise, the first byte of the payload would have been read as the jump offset, and the program would jump into uninitialized memory.

The payload itself is pretty simple. I think the small size of the string makes this approach smaller than a loop, and it's easier to make position-independent this way. The `e` in `beep` repeats, so I can shave off one `ld a`. Also, because all memory between `$0038` and `$8000` is zeroed, I can fall through it and use a shorter `rst` variant of the `call` instruction, which only works for `$0`, `$8`, `$10` and so on, up to `$38`.

## Older approaches

### 64 bytes

```
00000000: 2e3f 3f2e 3f3f 7e7e a7a7 201f 1e2b 2b1e  .??.??~~.. ..++.
00000010: 2b2b 6b00 7ea7 2814 003e 62cd 0080 3e65  ++k.~.(..>b...>e
00000020: cd00 80cd 0080 3e70 cd00 8076 003e 62cd  ......>p...v.>b.
00000030: 0080 3e65 cd00 80cd 0080 3e70 cd00 8076  ..>e......>p...v

```

### 58 bytes

```
00000000: 2e39 392e 3939 7e7e a7a7 2019 3a25 00a7  .99.99~~.. .:%..
00000010: 2814 003e 62cd 0080 3e65 cd00 80cd 0080  (..>b...>e......
00000020: 3e70 cd00 8076 003e 62cd 0080 3e65 cd00  >p...v.>b...>e..
00000030: 80cd 0080 3e70 cd00 8076                 ....>p...v

```

### 53 bytes

This one has an explanation in the edit history, but it's not too different.

```
00000000: 3a34 00a7 a720 193a 2000 a728 1400 3e62  :4... .: ..(..>b
00000010: cd00 803e 65cd 0080 cd00 803e 70cd 0080  ...>e......>p...
00000020: 7600 3e62 cd00 803e 65cd 0080 cd00 803e  v.>b...>e......>
00000030: 70cd 0080 76                             p...v

```

## What if: any non-empty output was fine instead of beep

### 1 byte

```
v

```

`halt`s the program normally, but if radiation removes it, then the memory will be full of zeroes, making `$8000` execute an infinite number of times, printing a lot of null bytes.

# Answer
> 8 votes
# \>\<\>, 23 bytes

```
<|o<"beep"/
>o<"beep"<\

```

Try it online! Verification.

It's honestly really surprising how short I got this. Ends with an error.

### Non-erroring version, 29 bytes

```
<<;oooo"beep"/
 ;oooo"beep"<\

```

Try it online!

# Answer
> 6 votes
# Klein, one of each topology, totaling 291 bytes

After seeing WW's answer using the `001` topology, I decided to see how hard it would be to do a Geiger Counter for each topology. (Spoiler: very hard. It's difficult to figure out where the pointer will go without hand gestures that make me look like I'm figuring out which hand is my left)

Verification!

(I also thought about writing a program that is a valid Geiger counter on all topologies, but that might have to wait. If anyone else wants to try though, I'm offering a 500 rep bounty)

### 000 and 010, 21 bytes

```
<<@"peeb"/
.@"peeb"<\

```

Try 000 online! and Try 010 online!

This is ported from my `><>` solution. This obviously works in `000`, since that's the default topology for most 2D languages, but I was surprised that it also works in `010`.

### 001 and 011, 26 bytes

```
!.<<@"peeb"/
.@"peeb"..<..

```

Try 001 online! and Try 011 online!

This one is copied directly from WW's answer. Thanks!

### 100, 21 bytes

```
//@"peeb"\
@"peeb".</

```

Try it online!

### 101, 21 bytes

```
//@"peeb"/
@"peeb".<!

```

Try it online!

### 110, 26 bytes

```
<.<@"peeb"\\
.\@."peeb".\<

```

Try it online!

### 111, 24 bytes

```
<<@"peeb"<\
...@"peeb"//

```

Try it online!

### 200, 21 bytes

```
<<@"peeb"\
@"peeb".!/

```

Try it online!

### 201, 31 bytes

```
\\.\.@"peeb"</./
./...@"peeb"<\

```

Try it online!

By far the most annoying.

### 210, 26 bytes

```
/\\@"peeb"</\
/@.."peeb"<\

```

Try it online!

### 211, 27 bytes

```
\\."peeb"((</
!/@@<"peeb"<\

```

Try it online!

The only one where I had to handle entering the beeper through the right side.

# Answer
> 4 votes
# Klein 0X1, 26 bytes

*Works in both 011, and 001.*

```
!.<<@"peeb"/
.@"peeb"..<..

```

Try it online!

Verify!

## Explanation

This program takes advantage of Klein's unique topologies in particular the **001** and **011** topology, which are the Klein bottle and the real projective plane. This explanation will focus on **001**, the klein bottle.

Unedited the program follows the execution path:

Removing a byte from the program can effect the program in 4 ways (each in a different color):

The first thing to note is that `<<` will always deflect the ip to the left of the origin at the start. If one of the `<`s is deleted the other takes its place. So if any byte is removed from the red section the following execution path will be followed:

If the blue byte is removed we get the very simple path:

If the newline is removed we get the path:

The yellow path is a bit more complex. Since the bottom line is one longer than the top line, when the program is squared at the beginning of execution a virtual character is added to the end of the first line to make them the same size. If any byte on the second line is removed the line is shortened and that virtual character is not added. This is important because `!` normally jumps over the virtual character, but in its absence it jumps over `/` instead.

# Answer
> 3 votes
# Self-modifying Brainfuck, ~~144~~ 102 bytes

Unprintables are displayed as escape sequence (for example `\x01`).

```
\xa8<<[[<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<[[[.<-]>[>-]\x01qffb\x00\x00beep\x00]]]<[>]<<[>[-<+>]+<<]>[[>]>>[.>]]\x01

```

Verification!

# Answer
> 2 votes
# Backhand, ~~25~~ 21 bytes

```
vv""ppeeeebb""jjHH@

```

Try it online! Verification!

This uses Backhand's ability to change the pointer step value to skip an instruction every step and neatly solve the redunancy issue. It then uses the `j` command to check if the code is irradiated by jumping to the last character (`@`, halt) if not, and jumping to the second last (`H`, halt and output stack) if so.

# Answer
> 2 votes
# Runic Enchantments, 29 bytes

```
>>yyLL@"peeb"/
     @"peeb"L\

```

Try it online!

Essentially the same as the Klein 000 answer or \>\<\> answer (I started with the Klein one). The only change really needed was to turn the `<` into `L` and `.` into  (translation of command symbols), inserting the IP entry points (need 2, otherwise a deletion would result in a non-compiling program) and the insertion of the dela`y` command to get the two IPs to merge (thus printing only one `beep`), again, needing two. Also required inserting additional NOPs to keep line lengths the same. Klein conveniently also uses `@` for "print and terminate."

No ability to utilize the whitespace in the lower left, as any reflectors to change direction inhibits the ability to detect radiation. e.g. (26 bytes, irradiated `y`):

```
/yLL@"peeb"/
\<<  @"peeb"L\

```

Prints no output, due to the bent entry segment causing a re-reflection back to the lower line's terminator.

# Answer
> 1 votes
# Befunge-93, 55 bytes

```
<< >       vv
>,,@#"beep"<"
v  |   _ #-<_
>"peeb",,,,@>

```

Try it online! Verification!

I'd hoped to get it a little smaller than this, but the length of the `beep` printer is the bottleneck.

# Answer
> 1 votes
# Wumpus, ~~37 34 32~~ 31 bytes

```
777*7..@ $o&4"beep"|"@peeb"4&o@

```

Try it online! Verification!

This solution uses the fact that `.` jumps to a position modulus the length of the program.

Alternatively for the same amount of bytes

```

" @o&4"beep"}@
@o&4"beep"}$}

```

Try it online! Verification!

This one utilises the difference in the direction of the pointer for odd and even line lengths. (I don't really know how the first `"` actually works when the newline is removed)

---
Tags: code-golf, source-layout, radiation-hardening
---


title: Exact generalised harmonic numbers

text:
# Question
Title: Exact generalised harmonic numbers
The generalised harmonic number of order \\$m\\$ of \\$n\\$ is

$$H\_{n,m} = \sum\_{k=1}^n \frac 1 {k^m}$$

For example, the harmonic numbers are \\$H\_{n,1}\\$, and \\$H\_{\infty,2} = \frac {\pi^2} 6\\$. These are related to the Riemann zeta function as

$$\zeta(m) = \lim\_{n \to \infty} H\_{n,m}$$

Given two positive integers \\$n \> 0\\$, \\$m \> 0\\$, output the *exact* rational number \\$H\_{n,m}\\$. The fraction should be reduced to its simplest term (i.e. if it is \\$\frac a b\\$, \\$\gcd(a, b) = 1\\$). You may output as a numerator/denominator pair, a rational number or any clear value that distinguishes itself as a rational number. You **may not** output as a floating point number.

This is , so the shortest code in bytes wins

## Test cases

```
n, m -> Hₙ,ₘ
3, 7 -> 282251/279936
6, 4 -> 14011361/12960000
5, 5 -> 806108207/777600000
4, 8 -> 431733409/429981696
3, 1 -> 11/6
8, 3 -> 78708473/65856000
7, 2 -> 266681/176400
6, 7 -> 940908897061/933120000000
2, 8 -> 257/256
5, 7 -> 2822716691183/2799360000000

```

# Answer
> 9 votes
# , 4 bytes

```
Rİ*S

```

Try it online!

Obligatory trivial answer ;-;

```
Rİ*S  Main Link; takes n on the left and m on the right
R     Range: [1, 2, 3, ..., n]
 İ    Inverse/Reciprocal: [1, 1/2, 1/3, ..., 1/n]
  *   Exponent: [1, 1/2^m, 1/3^m, ..., 1/n^m]
   S  Sum

```

# Answer
> 6 votes
# Wolfram Language (Mathematica), 14 bytes

```
HarmonicNumber

```

Try it online!

Naturally.

---

Alternatively, **16 bytes** without the built-in:

```
Tr[Range@#^-#2]&

```

Try it online!

# Answer
> 5 votes
# Raku, 29 bytes

```
{sum((1/1..$^n)X**-$^m).nude}

```

Try it online!

This function takes two arguments, `$^m` and `$^n`. `1/1 .. $^n` is a sequence of rational numbers from `1` to the second argument. `X** -$^m` produces the exponentiated cross product of that list with the negative of the first argument. `sum` sums those rational numbers, and `.nude` produces a two-element list of the numerator and denominator of the sum.

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

A 1-byte shorter, slightly less readable version with a single recursive call. This is otherwise identical to the commented version below.

```
m=>g=(n,N=0,D=1)=>D?g(n-!!n,n?p=N*n**m+D:D,n?q=D*n**m:N%D):[p/N,q/N]

```

Try it online!

---

# JavaScript (ES7), 69 bytes

Expects `(m)(n)`. Returns `[numerator, denominator]`.

```
m=>g=(n,N=0,D=1)=>n?g(n-1,p=N*n**m+D,q=D*n**m):D?g(0,D,N%D):[p/N,q/N]

```

Try it online!

### How?

The recursive function \\$g\\$ first computes the unreduced numerator and denominator \\$(N,D)\\$ of \\$H\_{n,m}\\$ and saves a copy of the final result into \\$(p,q)\\$:

```
n ? g(n - 1, p = N * n**m + D, q = D * n**m) : ...

```

When \\$n=0\\$, it enters its 2nd phase where the GCD of \\$(p,q)\\$ is computed in \\$N\\$:

```
... : D ? g(0, D, N % D) : ...

```

When \\$D=0\\$, it eventually returns:

```
... : [p / N, q / N]

```

# Answer
> 5 votes
# , 13 bytes

```
1#.(%@^~1+i.)

```

Try it online!

# Answer
> 4 votes
# Jelly, ~~13~~ 12 bytes

```
*€:@S,:gɗɗP$

```

Try it online!

A byte less than `*€µP:¹S,P:g/$`, but the abuse of `ɗ` leads me to believe this can be shorter yet.

```
*€              Raise each 1 .. n to the power of m.
         ɗP$    For that list and the product of its elements:
  :@            divide each by the product
    S           and sum;
        ɗ       for that sum:
     ,          pair it with the product,
      :         and divide both by
       g        the GCD of the sum and product.

```

# Answer
> 4 votes
# Java, ~~155~~ 138 bytes

```
int g(int a,int b){return b<1?a:g(b,a%b);}
m->n->{int p=1,d=0,t;for(;n>0;d=d*t+p,p*=t)t=(int)Math.pow(n--,m);return d/g(d,p)+"/"+p/g(d,p);}

```

Try it online!

$$Denominator\_{n, m} = \prod\_{k=1}^n k^m$$

$$Numerator\_{n,m} = \sum\_{k=1}^n \frac {Denominator\_{n,m}} {k^m} = Numerator\_{n-1,m} \times k^m + Denominator\_{n-1,m}$$

# Java + Commons Lang 2, 127 bytes

```
m->n->{org.apache.commons.lang.math.Fraction x=null;for(x=x.ZERO;n>0;)x=x.add(x.getFraction(1,(int)Math.pow(n--,m)));return x;}

```

# Answer
> 3 votes
# Factor \+ `math.unicode`, ~~35~~ 24 bytes

```
[ [1,b] 0 rot - v^n Σ ]

```

Try it online!

*-11 thanks to @Bubbler!*

## Explanation:

It's a quotation (anonymous function) that takes two integers from the data stack as input and leaves a fully-reduced mixed fraction (it's simply the way that Factor is) on the data stack as output.

* `[1,b]` Make a range from `1` to `n`.
* `0 rot` Push `0` and bring `m` to the top of the stack.
* `-` Subtract `m` from `0`.
* `v^n` Raise every element in the range to the `-m` power.
* `Σ` Sum.

# Answer
> 3 votes
# , 11 bytes

```
1#.#\@$^-@]

```

Try it online!

TFW J beats Jelly...

Used as `n f m`, where `n` and `m` are given as extended-precision integers.

### How it works

```
1#.#\@$^-@]    NB. dyadic train; left = n, right = m
   #\@$        NB. 1..n in a dyadic context:
     @$        NB.   reshape m into dimension n, and then
   #\          NB.   get the lengths of prefixes
       ^       NB. each raised to the power of
        -@]    NB. -m
1#.            NB. sum of them

```

# Answer
> 3 votes
# Vyxal, 14 bytes

```
ɾ$eDΠ$/∑$Π":ġ/

```

Try it Online!

# Answer
> 3 votes
# Nim, 81 bytes

```
import math,rationals
func H(n,m:int):any=
 var r=0//1;for i in 1..n:r+=1//i^m
 r

```

Try it online!

# Answer
> 2 votes
# Haskell, 28 bytes

```
n#m=sum$map((1%).(^m))[1..n]

```

# Answer
> 2 votes
# Stax, 6 bytes

```
ê☺σ;vù

```

Run and debug it

just another trivial answer.

# Answer
> 2 votes
# Ruby, 27 bytes

```
->n,m{(1..n).sum{|x|x**-m}}

```

Try it online!

# Answer
> 2 votes
# Python 3.8, 91 bytes

```
import math
f=lambda n,m,N=0,D=1:n and f(n-1,m,N*n**m+D,D*n**m)or(N/(G:=math.gcd(N,D)),D/G)

```

Try it online!

Inputs \\$n\\$ and \\$m\\$ and returns the numerator and denominator of \\$H\_{n,m}\\$ as a tuple.

Uses the formula from Arnauld's JavaScript answer.

# Answer
> 2 votes
# APL(Dyalog Unicode), ~~31~~ 27 bytes SBCS

```
{(⊢÷∨/){⍵,⍨+/⍵÷x}∧/x←⍵*⍨⍳⍺}

```

Try it on APLgolf!

`(⊢÷∨/){⍵,⍨+/⍵÷x}∧/x←⍵*⍨⍳⍺` is equivelent to `x←(⍳⍺)*⍵⋄(⊢÷∨/){⍵,⍨+/⍵÷x}∧/x`. APL translated to Python:

```
from math import *

def H(n, m):
    x = [i**m for i in range(1,n+1)] # x←(⍳⍺)*⍵
    tmp = lcm(*x) # ∧/x
    tmp = (sum(tmp//i for i in x), tmp) # {⍵,⍨+/⍵÷x}
    tmp = [e//gcd(*tmp) for e in tmp] # (⊢÷∨/)
    return tmp

```

First I make a list from `1` to `n` -- `⍳⍺`. Then I raise every element of the list to the power of `m` to calculate the value of all the denominators, and assign it to the variable `x` -- `x ← (⍳⍺)*⍵`.

I then calculate the denominator after all the fractions are added together by taking the least common multiple of all the elements of `x` (all the denominators) -- `∧/x`.

Next I create a two element tuple, the second element of which is the denominator -- `{⍵,⍨...}`. The first element is the numerator, calculated as the sum of the denominator divided by each of the original denominators -- `+/⍵÷x`.

Lastly, I simplify the fraction by dividing it by it's gcd -- `(⊢÷∨/)`.

# Answer
> 1 votes
# Excel, 70 bytes

```
=LET(k,SEQUENCE(A1)^B1,d,PRODUCT(k),n,SUM(d/k),g,GCD(n,d),n/g&"/"&d/g)

```

Link to Spreadsheet

# Answer
> 1 votes
# Charcoal, 40 bytes

```
≔Ｘ…·¹ＮＮθ≔Πθη≔Σ÷ηθζ⊞υζ⊞υηＷζ«≔﹪ηιζ≔ιη»Ｉ÷υη

```

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

```
≔Ｘ…·¹ＮＮθ

```

Generate the first `n` powers of `m`.

```
≔Πθη≔Σ÷ηθζ

```

Calculate the product, then divide that by each power and take the sum.

```
⊞υζ⊞υη

```

Save the values for later.

```
Ｗζ«≔﹪ηιζ≔ιη»

```

Find the GCD.

```
Ｉ÷υη

```

Divide the saved values by the GCD.

# Answer
> 1 votes
# Core Maude, 111 bytes

```
fmod H is pr RAT . op __ : Nat Nat -> Rat . vars N M : Nat . eq 0 M = 0 . eq(s N)M = 1 / s N ^ M +(N M) . endfm

```

### Example Session

```
             \||||||||||||||||||/
           --- Welcome to Maude ---
             /||||||||||||||||||\
         Maude 3.1 built: Oct 12 2020 20:12:31
         Copyright 1997-2020 SRI International
           Tue May 18 23:37:06 2021
Maude> fmod H is pr RAT . op __ : Nat Nat -> Rat . vars N M : Nat . eq 0 M = 0 . eq(s N)M = 1 / s N ^ M +(N M) . endfm
Maude> red 3 7 .
reduce in H : 3 7 .
rewrites: 17 in 0ms cpu (0ms real) (17206 rewrites/second)
result PosRat: 282251/279936
Maude> red 6 4 .
reduce in H : 6 4 .
rewrites: 40 in 0ms cpu (0ms real) (~ rewrites/second)
result PosRat: 14011361/12960000
Maude> red 3 1 .
reduce in H : 3 1 .
rewrites: 17 in 0ms cpu (0ms real) (~ rewrites/second)
result PosRat: 11/6
Maude> red 2 8 .
reduce in H : 2 8 .
rewrites: 10 in 0ms cpu (0ms real) (~ rewrites/second)
result PosRat: 257/256
Maude> red 5 7 .
reduce in H : 5 7 .
rewrites: 32 in 0ms cpu (0ms real) (~ rewrites/second)
result PosRat: 2822716691183/2799360000000

```

### Ungolfed

```
fmod GENERALIZED-HARMONIC-NUMBERS is
    protecting RAT .
    op H : Nat Nat -> Rat .
    vars N M : Nat .
    eq H(0, M) = 0 .
    eq H(s N, M) = 1 / (s N ^ M) + H(N, M) .
endfm

```

`H(N, M)` is the naive recursive definition of \\$H\_{n, m}\\$. Maude's built-in rational number module automatically reduces fractions to lowest common denominator.

There's not *much* golfing we can do because only a handful of characters can separate identifiers (`(`, `)`, `[`, `]`, `{`, `}`, `,`, and space). I've renamed the function operator `H` to `__` (juxtaposition of two values) in the golfed version to save a few bytes.

# Answer
> 1 votes
# MATLAB/Octave, 25 bytes

```
@(n,m)sum(1./sym(1:n).^m)

```

Try it online!
Anonymous function. Returns accurate value of symbolic type, which can represent real numbers (so rational numbers including).
Unfortunatelly, to my suprise, MATLAB doesn't implement that function, only non-generalized harmonic numbers (so only for ).

---
Tags: code-golf, math, rational-numbers
---