# Question
Title: Find the program that prints this integer sequence (Cops' thread)
**This is the cops' thread. The robbers' thread goes here.**

The last thread was already 4 months ago.

## The cop's task

* The cop's task is to write a program/function that takes a positive (or non-negative) integer and outputs/returns another integer.
* **The cop must state it if the program is intolerant towards zero.**
* The cop will provide at least **2** sample inputs/outputs.
* For example, if I have decided to write the Fibonacci sequence, I would write this in my answer:

```
a(0) returns 0
a(3) returns 2

```
* The number of examples is up to the cop's discretion.
* However, the sequence must actually exist in the On-Line Encyclopedia of Integer Sequences®, so no pseudo-random number generator for you. `:(`
* **The cop can hide as many characters as is so wished.**
* For example, if my program is:

---

```
function a(n)
    if n>2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end

```

---

* Then I would hide these characters as I want:

---

```
function a(n)
    if ### then
        ########
    else
        ######################
    end
end

```

---

## The robber's task

* is obviously to find the original source code.
* **However, any proposed source code that produces the same set of output also counts as valid, as long as it is also found in OEIS.**

---

## Tips for the cops

* ~~The search function in the OEIS only works for consecutive terms, so if you want to hide your sequence, then just leave a hole anywhere.~~
* Apparently there is no way to hide the sequence. Put this in mind when you choose the sequence.

---

Your score is the number of bytes in your code.

The winner will be the submission with the lowest score that hasn't been cracked in 7 days.

Only submissions that are posted in 2016 April are eligible for the win. Submissions that are posted later than this are welcome, but cannot win.

In order to claim the win you need to reveal the full code and the OEIS sequence (after 7 days).

Your post should be formatted like this (NN is the number of characters):

---

# Lua, 98 bytes

Output:

```
a(0) returns 0
a(3) returns 2

```

Code (`#` marks unrevealed characters):

```
function a(n)
    if ### then
        ########
    else
        ######################
    end
end

```

---

If the code is cracked, insert `[Cracked](link to cracker)` in the header. If the submission is safe, insert "Safe" in the header and reveal the full code in your answer. Only answers that have revealed the full code will be eligible for the win.

# Answer
# Vim, 36 keystrokes -- Safe!

```
i****<esc>:let @q="^*i****$**@***"<cr><n>@qbD

```

(Note: `<n>` is where you type your input)

Here is the code unrelated to number generation:

```
          :let @q="              "<cr><n>@qbD

```

Meaning I am revealing 5 out of 19 characters.

`<n>` is the input. Here are some sample outputs:

```
1@q:    1
2@q:    3
6@q:    18

```

# Answer

This code prints The Lucas Numbers (A000032), which are just like The Fibonnaci Sequence, except that it starts on `2, 1` instead of `1, 1`. Here are the first 15 numbers:

```
2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322, 521, 843

```

Here's the revealed code:

```
i2 1 <esc>:let @q="^diwwyw$pb@-<c-v><c-a>"<cr><n>@qbD

```

Explanation:

```
i2 1 <esc>                          "Insert the starting numbers
          :let @q="....."<cr>       "Define the macro 'Q'

```

Explanation of the macro:

```
^                      "Move to the first non-whitespace character on the line.
 diw                   "(d)elete (i)nner (w)ord. This is different then 'dw' because it doesn't grab the space.
                      "It also throws people off since 'i' is usually used for inserting text.
    wyw$               "Move to the next number, yank it then move to the end of the line
        pb             "(p)aste the yanked text and move (b)ack
          @-     <c-a> "@- is the register holding the word we deleted. Increment the current number that many times.
            <c-v>      "Since we're adding <c-a> this from the command line, we need to type it as a literal.

```

Now, we just need to remove the second number, since the first number is the lucas number we want. So we do

```
b   "move (b)ack
 D  "(D)elete to the end of the line.

```

Also, if I'm not mistaken, this is the first safe submission! That's kinda cool.
> 11 votes

# Answer
# 05AB1E, 5 bytes, safe

Last one for today :p. Output:

```
a(0) = 9
a(5) = 4
a(10) = 89

```

Code:

```
___m_

```

Obfuscated characters are indicated with `_`. Try it online!-link. Uses **CP-1252** encoding.

---

### Solution:

```
žhžm‡

```

Explanation:

```
žh       # Short for [0-9].
  žm     # Short for [9-0].
    ‡    # Translate.

```

Try it online! or Try for all test cases!.
> 8 votes

# Answer
# Element, 7 bytes, cracked

Output:

```
a(3) = 111
a(7) = 1111111

```

The `#` are hidden characters, and they are all printable ASCII. I think this one is actually reasonably difficult (for only having 5 missing characters).

```
###,##}

```

For convenience, here's the Try It Online and Esolang wiki pages.

---

My original program was:

> `_'[,$`}`

The trick is that

> `]` and `}` are functionally identical (both translate to `}` in Perl). Also, I used `,$` to produce a `1` as an additional layer of confusion, although it is possible to ignore the `,` completely by doing `,1` instead.
> 6 votes

# Answer
# Jolf, 5 bytes, cracked

Output:

```
a(2) = 8
a(10) = 4738245926336

```

All of it is crucial, and I have shown 1 of 5.

```
####x

```

Original code:

```
mPm$x
mP     cube
  m$   catalan number
    x  input

```

Try it online!
> 5 votes

# Answer
# JavaScript (ES7), 10 bytes, Cracked

### Output

```
f(0) -> 1
f(1) -> -1

```

### Code

```
t=>~t##**#

```

**Test it in Firefox nightly.** The code is an anonymous function. This will probably be easy since there's only three characters hidden, but at least it's short! :P

---

My original code was:

> `t=>~top**t`

but after brute-forcing my own code for a solution, I soon realised

> `t=>~t.x**t` (where `x` can be any variable name character)

could also be used. This works because

> in the original ES7 exponentiation operator spec, the operator had lower precedence than unary operators (unlike conventional mathematics and most other languages). `~` performs a bitwise NOT on `t.x` (`undefined`) or `top` (`Object`) which casts them to a 32-bit signed integer (uncastables like these become `0`) before doing the NOT (so `0` becomes `-1`). I looked into further into this, and very recently, the spec has changed to disallow ambiguous references like this (not good for future golfing D: ), however most ES7 engines haven't updated to the latest version of the spec yet.
> 5 votes

# Answer
## 05AB1E, 4 bytes (Cracked)

Sample output :

```
a(5) = 51
a(8) = 257

```

And for the code :

```
###^

```

I revealed the last one. Should be easy enough though, I had quite a hard time finding a sequence :(

All hidden characters are printable.
> 4 votes

# Answer
# MATL, 5 bytes, cracked

Hidden characters are indicated by `%`.

```
%5%*%

```

Output:

```
a(1) = 3
a(2) = 6
a(4) = 12

```

Input `0` is valid.

---

Original code:

```
35B*s

```

that is,

```
35    % push number 35
B     % convert to binary: array [1 0 0 0 1 1]
*     % multiply element-wise by implicit input n: gives [n 0 0 0 n n]
s     % sum of array: gives 3*n

```
> 4 votes

# Answer
# SWIFT, 55 bytes, Cracked

```
func M(n:Int)->Int{
return(n*****) ?M(**n****):n***;
}

```

`*` marks a hidden character

Output:

```
M(30) -> 91
M(60) -> 91
M(90) -> 91
M(120)-> 110
M(150)-> 140

```

Function accepts `0`
> 4 votes

# Answer
# Ruby, 46 bytes, safe

Edit to add disclaimer/apology: This sequence starts with f\[0\], while the OEIS entry starts with f\[1\]. The values are the same.

Obfuscated code (`#` is any character):

```
->####or x##1###(#..##0#);x*=3;end;#.###ect:+}

```

Call like

```
->####or x##1###(#..##0#);x*=3;end;#.###ect:+}[3] (returns 39)

```

Output:

```
f[0] = 0
f[1] = 3
f[2] = 12
f[3] = 39
f[4] = 120
f[5] = 363
f[6] = 1092
f[7] = 3279
f[8] = 9840
f[9] = 29523

```

Solution:

> `f=->*x{for x[-1]in(0..x[0]);x*=3;end;x.inject:+}`

Sequence:

> http://oeis.org/A029858

Explanation:

> The minor trick here is that we declare the parameter as `*x` rather than `x`. This means that if you pass in `2`, `x` is set to `[2]`...at first. The *major* trick exploits bizarre, and justly obscure, Ruby syntax where you can set the iterator in a for loop to any valid left hand side of an assignment expression, instead of an iterator variable like `i`. So this loops through from 0 to (in this example) 2, assigning each number to `x[-1]`, meaning it overwrites the last value of x. Then the loop body `x*=3`, further mutates x by concatenating it to itself 3 times. So first x becomes `[0]`, then `[0,0,0]`. On the next loop it becomes `[0,0,1]`, then `[0,0,1,0,0,1,0,0,1]`. Finally we pass in 2 and it becomes `[0,0,1,0,0,1,0,0,2]`, then `[0, 0, 1, 0, 0, 1, 0, 0, 2, 0, 0, 1, 0, 0, 1, 0, 0, 2, 0, 0, 1, 0, 0, 1, 0, 0, 2]`. We then sum the result using the `inject` method, which reduces the array by applying `+` (the passed in method) to each element in turn. If we consider how each iteration changes the sum, we see that we effectively add 1 (by overwriting the last element with an element one higher), then multiply by 3. Since `3*(n+1) = 3*n + 3`, this implements Alexandre Wajnberg's recurrence relation for the sequence as described on the page.
> 4 votes

# Answer
# 05AB1E, 3 bytes, cracked

Output:

```
a(9) = 165
a(10) = 220

```

Hidden code:

```
##O

```

Try it online might come in handy.
> 3 votes

# Answer
# Hexagony, 7 bytes, cracked

Output:

```
a(1) = 2
a(2) = 4

```

Hidden code:

```
?#####@

```

Or alternatively:

```
 ? #
# # #
 # @

```

Try it online might come in handy.
> 3 votes

# Answer
# PHP, 41 bytes, cracked

Yeah, finally another Cops and Robbers challenge. Hope I didn't make it to easy.

**Output**

```
a(5)   = 0
a(15)  = 1
a(35)  = 0
a(36)  = 1
a(45)  = 1

```

**Source**

```
____________________$argv[1]____________;
####################        ############

```

**Notes**

---

**Cracked**

I obviously made it to easy and provided not enough examples. The sequence I had in mind was A010054:

> a(n) = 1 if n is a triangular number else 0.

Here's my original source code:

> `echo(int)($r=sqrt(8*$argv[1]+1))==$r?1:0;`

It tests whether the input is a *triangular number* and outputs `1` or `0` accordingly.
> 3 votes

# Answer
## Pyke, 15 bytes, SAFE

Output

```
a(2) = 21
a(15) = 17

```

Revealed code:

```
#R#D######+##)#

```

Solution:

> OEIS A038822
> `wR}DSR_Q*L+#P)l`
> I used a couple of red herrings here by using `wR}` to generate the number 100 and revealing the character `R` which is normally used to rotate the stack. I also used `#P)l` instead of the more simple `mPs` to count the number of primes in the sequence.
> 3 votes

# Answer
# C, 71 bytes cracked

```
############
#####
main(){
 scanf("%d",##);
 ###6#;
 printf("%d",##);
}

```

Output:

```
a(1) = 0   a(2) = 0   a(5) = 1
a(6) = 1   a(7) = 1   a(9) = 2

```

This works with gcc, and is a full program. It accepts 0 as input.
> 3 votes

# Answer
# Jolf, 11 bytes, Cracked , A011551

```
c*______x__

c*mf^+91x~P

```

Original code:

```
c*^c"10"x~P

```

Examples:

```
0 -> 1

12 -> 1618033988749

```
> 3 votes

# Answer
# Java, 479 bytes, Cracked

Outputs:

```
a(10) = 81
a(20) = 35890

```

(Inputs are provided via command line arguments)

Code (`#` marks hidden characters):

```
import java.util.*;
public class A{

    public static int#########
    public boolean###########

    static A a = new A();

    public static void main(String[] args){
        int input = Integer.parseInt(args[0]);

        LinkedList<Integer> l = new LinkedList<>();
        l.add(1);
        l.add(0);
        l.add(0);

        for(int ix = 0; ################if(##>##{
            ###########d#
            #######+##p##########+##########(#######
        }

        System.out.println(#########################
            ###(A.#############(#5#####)));
    }
}

```

The program starts at index 0.

(Note that SE replaces all of the `\t` indents with 4 spaces, bringing the byte total to 569. Click here to see the program with `\t` indents instead of space indents.)

Original code:

```
import java.util.*;
public class A{
    public static interface B{
    public boolean C(int i);}

    static A a = new A();

    public static void main(String[] args){
        int input = Integer.parseInt(args[0]);

        LinkedList<Integer> l = new LinkedList<>();
        l.add(1);
        l.add(0);
        l.add(0);

        for(int ix = 0; ix<input; ix++)cif(i->  {
            return l.add(
            l.pop()+l.peekFirst()+l.peekLast());});{
        }

        System.out.println(l.get(1));}static boolean
            cif(A.B b5){return (b5.C((0)));
    }
}

```

(Same code, but formatted normally):

```
import java.util.*;

public class A {
    public static interface B { //functional interface for lambda expression
        public boolean C(int i); //void would have given it away
    }

    static A a = new A(); //distraction

    public static void main(String[] args) {
        int input = Integer.parseInt(args[0]);//Input

        LinkedList<Integer> l = new LinkedList<>();
        l.add(1);//Set up list
        l.add(0);
        l.add(0);

        for (int ix = 0; ix < input; ix++)
            cif(i -> { //Fake if statement is really a lambda expression
                return l.add(l.pop() + l.peekFirst() + l.peekLast());
            });
        { //Distraction
        }

        System.out.println(l.get(1));//Output
    }

    static boolean cif(A.B b5) { //Used to pass in lambda expression.
                  //The A. and b5 were both distractions
        return (b5.C((0)));
    }
}

```
> 3 votes

# Answer
# Octave, 34 bytes, cracked

```
@(m)(m###m#####m##)&isprime(#)####

```

Outputs:

```
ans(1) = 0
ans(6) = 5
ans(7) = 10
ans(8) = 15

```

The sequence starts at `ans(1)` in OEIS.
> 3 votes

# Answer
# MATL, 9 bytes, Cracked

Code:

```
3#2###*##

```

Output:

```
a(1)  = 3
a(2)  = 6
a(4)  = 12
a(12) = 37

```

`a(0)` is valid.

---

### Cracked

Original sequence: A059563

Original code:

```
3L2^Ze*sk
3L          % Push [1 -1j] from the clipboard
  2^        % square
    Ze      % exp
      *     % times input
       s    % sum
        k   % floor

```
> 3 votes

# Answer
## Pyth, 70 bytes, Cracked

```
DhbI|qb"#"qb"#"R!1Iqb"#"#####+""s####2###;##lY+Q1Ih+""Z#####)=Z+Z1;@YQ

```

`#` are the hidden characters

Has been cracked, so here is the versionn without hidden chars :

```
DhbI|qb"4"qb"0"R!1Iqb"1"R!0Rh+""sm^sd2cb1;W<lY+Q1Ih+""Z=Y+YZ)=Z+Z1;@YQ

```

Sample outputs :

```
a(2) -> 10
a(4) -> 19

```

~~Good luck to find this on OEIS, I personally failed to find it from those examples (even tho the sequence is quite easy to spot.)~~
> 3 votes

# Answer
## Lua, 45 Bytes, Cracked

A small hint:

```
a(0) will make the program crash :)

```

### Output

```
a(1)=>0
a(2)=>1

```

### Code

Uses `#` to hide the code :).

```
a=function(n)#####n###### and #or ########end

```

I was using the OEIS A007814, with the following code:

```
a=function(n)return n%2>0 and 0or 1+a(n/2)end

```
> 3 votes

# Answer
# C, 82 bytes, safe

```
####=############
main(i){scanf("%d",##);
for(i=1;i++/4<#;)##=2;
printf("%d",##);}

```

Works with gcc, and it is a full program, which reads its input from stdin and prints its output to stdout. Here the sequence is ~~A004526, floor(n/2)~~.

```
a(0) = 0    a(1) = 0    a(2) = 1
a(3) = 1    a(4) = 2    a(5) = 2
a(6) = 3    a(7) = 3    a(8) = 4

```

**Solution:**

```
a;*b=(char*)&a+1;
main(i){scanf("%d",&a);
for(i=1;i++/4<2;)a*=2;
printf("%d",*b);}

```

This works only on little endian machines, and only if the size of `char` is 1 byte.
And only if the byte higher than the highest order byte of `a` has value 0. I think this is true for gcc since by default uninitialized global variables go into the bss segment, and initialized global variables go into the data segment (see https://stackoverflow.com/questions/8721475/if-a-global-variable-is-initialized-to-0-will-it-go-to-bss).
So only `a` goes into bss (the only other global variable `b` is initialized and thus goes into the data segment). If `a` is not at the end of bss, then the byte higher than the highest order byte of `a` is also in bss and thus has value 0.
> 3 votes

# Answer
# Ruby, 38 bytes, cracked

Obfuscated code (`#` can be any character):

```
->#{(s=#########).sum==#3333&&eval(s)}

```

Output:

Multiplies the input by 10 (A008592). Works for any integer, including 0. e.g.

```
->#{(s=#########).sum==#3333&&eval(s)}[3]  => 30
->#{(s=#########).sum==#3333&&eval(s)}[10] => 100

```
> 3 votes

# Answer
# 05AB1E, 5 bytes, cracked

Output:

```
a(0) = 0
a(1) = 0
a(2) = 1
a(3) = 1
a(4) = 1
a(5) = 1
a(6) = 1
a(7) = 1
a(8) = 1
a(9) = 1
a(10) = 0
a(11) = 0

```

Obfuscated code:

```
_____

```

Try it online!-link.
> 3 votes

# Answer
# 05AB1E, 4 bytes, cracked

Well then, I think I'm addicted to CnR's... Obfuscated code (`_` indicates a wild card):

```
____

```

Sequence:

```
a(1) = 2
a(4) = 6720

```

The sequence in **OEIS** starts at a(1) = 2.

Try it online!-link
> 3 votes

# Answer
## 05AB1E, 1 byte, Cracked

```
_

```

`_` denotes hidden code.

```
f(1) == 1
f(18) == 6

```
> 3 votes

# Answer
# Reng v.3.3, 36 bytes. Cracked, A005449

Output:

```
a(1) = 2
a(3) = 15

```

`#` denotes a gone character. There are no other `#`s in the program.

```
i#:#+##-##)####¡#~
##########!</div>

```

Alright this is the last one for a while. Other people need to answer \>\_\>. A description of each character can be found in the source code, where all the ops are defined. A comment proceeds each operator.

Original code:

```
i>:1+(1-?v)v/a+¡n~
~^<$:$:$:>!</div>

```
> 2 votes

# Answer
# Jolf, 11 bytes, Cracked.

Output:

```
a(10) = 4
a(20) = 6
a(30) = 8

```

And the partially hidden code:

```
####xd###x#

```

Hint:

> When I looked through the sequences in order, I didn't go very far before finding this one.

The cracked version isn't quite the same as my original code. I'm not currently at my computer, so I don't have it exactly, but it was something like this:

> `l fzxd!m%xH`

(The only part I'm unsure about is the `!m`. It's whatever checks if a variable is zero.)
> 2 votes

# Answer
# Element, 10 bytes, cracked

Output:

```
a(3) = 6561
a(4) = 4294967296

```

There's probably only a few ways to compute this sequence in Element. I found a 9-char solution, but I figured this 10-char solution is actually more difficult. The `#` are hidden characters.

```
#_####@^#`

```

For convenience, here's the Try It Online and Esolang wiki pages.

---

The original was

```
2_3:~2@^^`

```
> 2 votes

# Answer
# Pyth, 18 bytes

`#` marks unrevealed characters.

```
L?Jtb##5#m##S#2 #y

```

Outputs (starts from `1`):

```
1 -> 2
2 -> 3
3 -> 5
4 -> 7

```

Online interpreter
> 2 votes

# Answer
# 05AB1E, 5 bytes, cracked

I hope that this submission isn't as easy as my other ones :p. Outputs:

```
a(0) = 0
a(1) = 1
a(2) = 6
a(3) = 24
a(4) = 80
a(5) = 240

```

Obfuscated code:

```
####O

```

Contains some non-ASCII characters though, uses **CP-1252** encoding.

Try it online! might come in handy :p.
> 2 votes

# Answer
# JavaScript ES6, 119 bytes, Cracked.

Output:

```
a(0) = 0
a(5) = 10000

```

Code:

```
x=>##=#=>[[[##x####r(###f#n###;#####n####h.##w###<1##].c####t.##pl##[####nc#######y([###(###(#]###)######`#######h####`

```

Returns an anonymous function.

Original sequence: A016744.

Original code:

```
x=>{f=n=>[[[1,x] for(x of n)]];return Math.pow(x<<1,[].concat.apply([].concat.apply([],f(f(f([]))))).join``.length)}//`

```

I need to show more characters of obsfucated code next time :P
> 2 votes

# Answer
# Jolf, 13 bytes, safe!

Outputs:

```
a(5) = 40
a(8) = 128

```

Code:

```
#+~##~####xx#

```

Interpreter.

Revealed:

> OEIS A003600
>
> ```
> γ+~iu~iZCzxxγ
> γ              γ =
>          zx    range 1..x (input)
>        ZC      cumulutive sum
>      ~i        identity
>     u          sum of
>   ~i           identity
>  +         x   plus x
>             γ  out γ
> ```
> 2 votes

# Answer
## Pyke, 6 bytes, Cracked

```
###X#s

```

Output:

```
a(2) = 8
a(8) = 80
a(10) = 120

```

This doesn't work with N\<1

Original solution:

> `hSmX$s`
> 2 votes

# Answer
# Jolf, 16 bytes, safe!

Outputs:

```
a(0) = 0
a(4) = -2
a(51) = 26

```

Code:

```
#.‘###4#x##32#mA

```

Revealed:

> ```
> Sequence: A001057, the canonical enumeration of integers.
> *.‘01m4zx’m32xmA
>   ‘      ’        an array
>    0               0: 0
>     1              1: 1
>      m4zx          antisum of range 1..x (1 - 2 - 3 - 4 - ... - x)
>  .        m32x    get min(2, x) of that array
> *             mA  multiply that entry by the sign of x (implicit input); is zero when zero
> ```
> 2 votes

# Answer
# 05AB1E, 5 bytes, cracked

```
##s##

```

`#` indicates a hidden character.

Output:

```
a(4) = 8
a(6) = 144

```

The sequence starts at `a(1)`.

---

The original code was exactly as in @Adnan's answer to robbers' thread.
> 2 votes

# Answer
# J, 8 bytes, cracked

`#` marks unrevealed characters

```
(##-#)#.

```

(Online interpreter here.)

### Output:

No, I'm not hiding anything by using a long sample. If the input is **0**, it outputs **0**, if the input is between **1** and **29**, it outputs **1**.

**The outputs for the negative inputs do not match with the actual sequence.**

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

```
> 2 votes

# Answer
# 05AB1E, 28 bytes (Cracked)

```
#D>D>D>D>*##*#D<*#+*#n#n#**#

```

a(1) = 1

a(2) = 8

a(3) = 42

Behaviour for zero is unspecified.

Cracked:

```
 DD>D>D>D>****rD<*6+*6n2n5**/

```

There is no need for an explanation I think as the crack was almost 100% spot on. The only difference is I used r to reverse stack instead of swapping top two elements.
> 2 votes

# Answer
## 05AB1E, 10 bytes, Cracked

```
##3##1+*1+

```

0-indexed.

```
0 ==> 1
4 ==> 61
5 ==> 91
9 ==> 271

```

Original Program:

> `UX3*X1+*1+`
> 2 votes

# Answer
## S.I.L.O.S, 37 bytes (Cracked.)

### Code:

```
readIO
#=#
#+#
#*#
#*#
#+#
printInt i

```

`#`s are the hidden characters.

### Output:

```
a(0) = 1
a(4) = 41
a(9) = 181

```
> 2 votes

# Answer
# , 7 bytes, cracked

Output:

```
a(0) = 6
a(2) = 27

```

Code (I have shown more for added difficulty):

```
#+#:###

```

Is a tacit verb.
> 1 votes

# Answer
## Python 2, 87 bytes, cracked

```
n=input()
#####################################################################
print _

```

Output:

```
a(5) = 2
a(10) = 2
a(15) = 1
a(20) = 1
a(25) = 1

```

---

I really should have checked for other sequences before I posted, here's another one that works (A014709):

```
n=input()
g=lambda n:~n%2*(n/2%2+1)or g(n/2);_=g(n)############################
print _

```
> 1 votes

# Answer
# Jolf, 3 bytes Cracked, A001477

```
___

```

Examples:

```
0 -> 0

1 -> 1

4 -> 4

9 -> 9

```

Original Code:

```
 "%"

```
> 1 votes

# Answer
# PHP, 18 bytes, cracked

Here's a very short one, at least in terms of PHP. I wonder if it survives ~~this Sunday~~ the next thirty minutes.

**Output**

```
a(0) = -1
a(1) =  0

```

**Source**

```
____$____[1]+_+_0;
#### ####    # #

```

**Notes**

---

**Cracked**

The sequence was A023443:

> a(n) = n - 1

Here's my original source code, which is slightly different to the robber's:

> `echo$argv[1]+-+!0;`
> 1 votes

# Answer
# , 8 bytes (Cracked)

`#` marks unrevealed characters

```
(#1-#)#.

```

### The output:

No, I'm not hiding anything by using a long sample. If the input is **0**, it outputs **0**, if the input is between **1** and **29**, it outputs **1**.

**The outputs for the negative inputs do not match with the actual sequence.**

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

```
> 1 votes

# Answer
# PHP, 137 bytes, cracked

This is my final sequence. You should be feeling lucky when trying this one.

**Output**

```
a(3)  =   7
a(7)  =  21
a(23) =  99

```

**Source**

```
for(___range___303_______________________array_merge____)for(__________________________________________)unset________;echo___$argv[1]-1_;
    ###     ###   #######################           ####     ##########################################      ########     ###          #

```

**Notes**

* This sequence starts at `1`.
* The program works up to the last number given bei OEIS, but can easily be adjusted to go to any other value as well.
* It's a full program, not a function.
* Reads the input from command line (obviously).
* Does not contain any PHP opening tag.

---

**Cracked**

The wording "*feeling lucky*" and the value `303` in the source were hints to the sequence A000959:

> *Lucky* numbers

This is my original source, which is slightly different to the robber's:

> `for($n=range(1,303);$j<count($n);++$j,$n=array_merge($n))for($i=($x=$j?$n[$j]:2)-1;isset($n[$i]);$i+=$x)unset($n[$i]);echo$n[$argv[1]-1];`
> 1 votes

# Answer
# MATL, 10 bytes, safe!

```
2*##n##qn-

```

Starts at 1, `#` are hidden characters. Sample input/output:

```
a(3)=1
a(8)=2

```

Revealed

> The sequence is the number of primes between n and 2\*n. The code used was `2*ZqnGZqn-`. This takes implicit input, doubles it, and finds the number of primes less than that number, pushes the input again and finds the number of primes less than that, and then subtracts the two lengths from each other.
> 1 votes

# Answer
## Seriously, 14 bytes (Safe)

```
,???D*≈@??D*≈-

```

The `?`s denote the hidden code. This sequence starts at `a(0)`.

Output:

```
a(0) = 1
a(1) = 0
a(3) = 1

```

---

## Solution:

The sequence is:

> A005614 (the infinite Fibonacci word)

My solution:

> `,;uφD*≈@⌐φD*≈-`

The solution is a straightforward implementation of the formula found on the OEIS page (with an error corrected so that the sequence starts at `n=0` like the page shows, rather than `n=1`).
> 1 votes

# Answer
## Pyth, 51 bytes, Safe

`#` denote hidden characters:

~~`K"#"D#d=#:d"#|#"1Rs#?qd"#"####"##"b#W<#K+#1=KhK;@KQ`~~

```
K"0"Dhd=b:d"0|1"1Rsm?qd"0""01""10"b;W<lK+Q1=KhK;@KQ

```

## Outputs

```
a(0) -> 0
a(1) -> 1
a(2) -> 1
a(4) -> 0

```

This is a fair one.

Thue-morse sequence, A010060.
> 1 votes

# Answer
# C++, 55 bytes (Safe)

This one should be easy...

### source:

```
bool f(int###########;##r#;r###&1#####+######r######r;}

```

### Output:

```
f(1)=>0
f(2)=>1
f(3)=>1
f(4)=>0
f(5)=>1
f(6)=>0
f(7)=>1
f(8)=>0
f(9)=>0
f(10)=>0
f(11)=>1

```

## answer

Sequence:

> A010051 (Characteristic function of primes: 1 if n is prime else 0.)

code:

> bool f(int r){int i=2;for(;r%i&&1-r;i++);return i ==r;}
> 1 votes

# Answer
## Haskell, 51 bytes (Cracked)

Outputs:

```
f 0 -> 0
f 1 -> 1
f 2 -> 1
f 3 -> 0
f 4 -> 0
f 5 -> 3
f 6 -> 5

```

Code:

```
f e=sum[#########$#####(f######=#####e####)#######]

```

This defines a function named `f`, with `#` as the wildcard character. Shouldn't bee too hard to crack.
> 1 votes

# Answer
# Ruby, 11 bytes, cracked

Code:

```
->i{######}

```

Output:

```
f(0) = 0
f(1) = 0
f(2) = 0
f(3) = 1
f(4) = 0
f(5) = 0
f(6) = 0
f(7) = 1
f(8) = 0
f(9) = 0
f(10) = 0
f(11) = 1
f(12) = 0
f(13) = 0
f(14) = 0
f(15) = 1

```

And so on, forming A011765. Curious to see if there's more than one way to do this in 6 bytes.
> 1 votes

# Answer
# Python, 123 bytes, Cracked

Probably not winning any prizes, but fun nonetheless.

`#` marks a hidden character, it is not used anywhere in the code.

```
def #(#):
 if n<2:
  return n
 else:
  return #(n-1)+#(n-2)

def g(n):
 ######:
  return n
 else:
  return (#(n##)+#(##2))###

```

Sample cases:

```
g(1) -> 1
g(6) -> 8
g(10) -> 7

```

My sequence was A089911, Fibonacci Numbers mod 12.

Original code:

```
def f(n):
 if n<2:
  return n
 else:
  return f(n-1)+f(n-2)

def g(n):
 if n<2:
  return n
 else:
  return (f(n-1)+f(n-2))%12

```
> 1 votes

# Answer
# Javascript, 30 bytes, Cracked

`#` marks unrevealed characters.

`n=>M###.##w(n#!#[#+!#[#)-(n##)`

Examples:

```
0 -> 1
1 -> 1
7 -> 43
18 -> 307

```

Original Code:

```
n=>Math.pow(n,!+[]+!+[])-(n-1)

```
> 1 votes

# Answer
# Python, 17 bytes, Cracked

```
####a(n):########

```

Test cases:

```
a(1) -> 1
a(2) -> 2

```
> 1 votes

# Answer
# Python, 60 bytes, Cracked

```
def a(n):
 if n<#:
  return #
 else:
  return a(n-#)+a(n-#)

```

Test cases:

```
a(0) -> 1
a(1) -> 1
a(3) -> 2
a(6) -> 6

```
> 1 votes

# Answer
## Seriously, 16 bytes (safe)

```
???"Xi"?≈$?,?R??

```

Examples:

```
a(3) = 1
a(40) = 4

```

This sequence starts at `a(1)`.

---

Sequence:

> http://oeis.org/A001222 (prime divisors of `n` with multiplicity)

Code:

> `ΣM£"Xi"w≈$X,QR£ƒ`

Explanation:

> The neat thing about this code (and the reason why it's difficult to crack) is that the actual divisor-counting part is reversed. Going through the code, everything up until the `,` doesn't actually do anything when executed left-to-right (except for pushing `"Xi"` and then subsequently popping it). `,QR£ƒ` reads in the input (`n`) and executes the code reversed (`Q` pushes the source code, `R` reverses it, and `£ƒ` calls it). Now, the stack contains `n` and the code is `ƒ£RQ,X$≈w"iX"£MΣ`. The first 3 commands (`ƒ£R`) do nothing with an integer on the stack. `Q` pushes the source code (again), `,` does nothing because the input is exhausted, and `X` gets rid of the `Q` result. `$≈` converts the input to a string and back to an int (necessary in the reversed code to prevent unwanted stack items). `w` pushes a list of `[prime, exponent]` pairs for all the prime factors of `n`, and `iX"£MΣ` sums up all of the exponents.
> 1 votes

# Answer
# R 64 bytes

Code

```
##########################
a=function(x)sum(x*3,1,a(x-2):a(x-1))

```

Output

```
a(1) =1
a(2) =1
a(3) =2
a(4) =3
a(5) =5
a(6) =8
a(7) =13
a(8) =21
a(9) =34
a(10)=55
a(11)=89
a(12)=144
a(13)=233
a(14)=377
a(15)=610
a(16)=987
a(17)=1597
a(18)=2584
a(19)=4181
a(20)=6765

```

Simply, Fibonnaci sequence.

Hope it's fun enough.
> 1 votes

# Answer
# Jolf, 3 bytes, cracked

Output:

```
a(0)  =      0
a(4)  =    260
a(10) =  10010
a(23) = 279864

```

Code:

```
###

```

All these features are documented. Yeah, you don't get any parts of the code :P The sequence is off-by-one.

Original:

```
+ΤQ

```
> 1 votes

# Answer
# 05AB1E, 4 bytes, cracked

Outputs:

```
a(0) = 1
a(2) = 4
a(10) = 4444

```

Code:

```
____

```

`_` indicates an obfuscated character. Try it online!.
> 1 votes

# Answer
## 05AB1E, 3 bytes, Cracked

Output:

```
a(4) = 4
a(6) = 7

```

Code:

```
___

```

_ (underscore) indicates an obfuscated character

Try it online
> 1 votes

# Answer
## 05AB1E, 8 bytes, Cracked

Output:

```
a(3) = 2
a(4) = 7

```

Code:

```
___s_r__

```

_ (underscore) indicates an obfuscated character

Try it online

Original Code:

```
ÑDgs`rG^

```

Which is the sequence A178910 (Binary XOR of divisors of n.)
> 1 votes

# Answer
## 05AB1E, 3 bytes, Cracked

Output:

```
a(3) = 2
a(4) = 6

```

Code:

```
___

```

_ (underscore) indicates an obfuscated character

Try it online

Original Code:

```
D;^

```

Which is the sequence A003188 (Decimal equivalent of Gray code for n)
> 1 votes

# Answer
## LiveCode, 35 bytes, cracked

```
_un_t_on oeis _
    ___u___n__
En__oeis

```

oeis (2)==2

oeis (0)==0
> 1 votes

# Answer
## Python, 37 bytes, cracked

```
def a(n):
    return ______!______n____*_

```

a(2)==4 a(4)==16
> 1 votes

# Answer
## Python 3, 58 Bytes, Cracked

`#` marks unrevealed chars.

```
import math;x=int(input());print(int(x/math.####(#)*#**#))

```

If x \< 1, it will not work.

```
in    out
1     0
4     457
7     2578097
10    44721359549
13    1760848250285208
16    131994155879539032064
19    16810747184697114703691776

```
> 1 votes

# Answer
# Jelly, 5 bytes (safe)

### Code

```
??Œ??

```

Each `?` denotes a missing character.

### Output

```
n a(n)

0    1
1    3
2    9
3   21
4   45
5   93
6  189
7  381
8  765
9 1533

```

This is OEIS entry A068156.

### Solution

```
Ḷ¡ŒṘL

```

Try it online!

### How it works

As noted on the OEIS page, this sequence obeys the recursive formula **a(n + 1) = 2a(n) + 3**, with base cases **a(0) = 1, a(1) = 3**.

The code begins with the integer **n** and applies  (unlength) **n** times, which convert all integers **k** in the previous array into the range **\[0, ... k - 1\]**. The output after all **n** steps is similar to the set-theoretic definition of **n**.

For **n = 0, 1, 2, 3, 4**, the outputs of `Ḷ¡ŒṘ` (unlength **n** times, then generate Python's string representation) is as follows.

```
0: 0
1: [0]
2: [[], [0]]
3: [[], [[]], [[], [0]]]
4: [[], [[]], [[], [[]]], [[], [[]], [[], [0]]]]

```

If we examine the outputs for **3** and **4** closely, we can note the following pattern.

```
[[], [[]], [[], [0]]]XX[[], [[]], [[], [0]]]X
[[], [[]], [[], [[]]], [[], [[]], [[], [0]]]]

```

The output for **4** consists of two copies of the output for **3** (the actual characters differ, but we're only interested in the length), and three additional characters (**X** marks the spots). Thus, if we take the length with `L`, our program follows the desired recursive formula.
> 1 votes

# Answer
## Python 3, 108 bytes (Cracked)

Warning (and hint): my implementation is dreadfully slow...

```
>>> a(0)
0
>>> a(4)
2
>>> a(16)
8
>>> a(20)
42

```

`a(0)` is the first element of the series exactly as defined in OEIS. `#` is used to hide chars.

```
def a(n):
 ###n####0######n#0
 f=a#######
 return f #f#####a###### f ####a(##f###i#i###a####n##else a#######

```
> 0 votes

# Answer
## Python 3, 50 bytes (Cracked)

Another one, because I like this sequence

```
>>> a(1)
0
>>> a(10)
2303

```

The first number from the sequence is `a(0)`. `#` used to obfuscate characters.

```
from #### import ####
a=lambda n:####(###########)

```
> 0 votes

# Answer
# Python 3, 58 bytes (Cracked)

One last series

```
>>> a(0)
0
>>> a(4)
8
>>> a(5)
17

```

Sequence starts with `a(0)`.

```
a=lambda n:###(###(###)## if ###### else #####(#######)##)

```

Original was different than the cracked, because I can't golf Python :P

```
a=lambda n:int(3**(n/2)-1 if n%2==0 else 2*3**(n/2-1/2)-1)

```
> 0 votes

# Answer
# Python 2, 72 bytes, cracked

```
print####((#y##########.####c###6#####16#.######)#131963###input()#3###)

```

Outputs:

```
a(1) = 1
a(2) = 2
a(3) = 3
a(4) = 6
a(5) = 9
a(6) = 18

```

`a(1)` is the first element of the sequence. Tested on my personal computer, on repl.it and on ideone (which have versions 2.7.11, 2.7.2 and 2.7.10 respectively).

---

The sequence is finite, and all terms are listed - it's just the divisors of 18. However, I overlooked the idea that `#`s could be substituted for newlines...

The original one-liner was:

> `print len((BytesWarning.__doc__*6)[8::16].split()[1319648>>input()*3&7])`
> 0 votes

# Answer
## Pyth, 4 bytes, Cracked

`#` denote hidden characters:

```
###Q

```

## Output

```
a(1) -> 1
a(2) -> 2
a(3) -> 3
a(10) -> 42

```
> 0 votes

# Answer
## Pyth, 29 bytes

```
W##YQ#t^#Z=#h#I#_#=#+Y##;@#tQ

```

Probably not an easy one. Begins at 1.

```
a(1) -> 2
a(2) -> 3
a(3) -> 5
a(4) -> 7
a(5) -> 13

```
> 0 votes

# Answer
# Molecule (v5.5), 25 bytes (UTF-8)

```
"ᘰᜟᘄఄሳÝ̲"C`n

```

No characters are hidden here ;)
An input of `0` is allowed.

Output of 1: `16`
Output of 2: `21`
> 0 votes

# Answer
## Python, 42 bytes Cracked

```
def f(x):return # if x<#else ######+######

```

Where

```
f(0) -> 0
f(1) -> 1
f(7) -> 13
f(15) -> 610

```
> 0 votes

# Answer
# PHP, 118 Bytes, Safe

I hope that I'm understand the rules right

```
function f($n){for($a=[],$i=0,$n++;$n!=@@@@@@($a);$i++)if(@@@@@@@)if(@@@@@@@@(@@@@@@@@@@@@@@))$a[]=$i;return end($a);}

echo f(6); # 16
echo f(13);# 32
echo f(0); #2
echo f(1); #4
echo f(54); #128

```

Original code

```
function f($n){
  for($a=[],$i=0,$n++;$n!=sizeof($a);$i++){
      if($t=$i%7)if(in_array($t,array(2,4,6)))$a[]=$i;
  }
  return end($a);
}

```

generates this sequence
> 0 votes

---
Tags: number, sequence, cops-and-robbers
---


# Question
Title: Find the program that prints this integer sequence (Robbers' thread)
**This is the robbers' thread. The cops' thread goes here.**

In the cops thread, the task was to write a program/function that takes a positive (or non-negative) integer and outputs/returns another number (not necessarily integer). The robbers task is to unscramble the code the cops used to produce this output.

The cracked code doesn't have to be identical, as long as it has the same length and any revealed characters are in the correct positions. The language must also be the same (version numbers can be different). The output must of course be identical.

**No-ops can be used in robber's solution.**

The winner of the robbers thread will be the user who has cracked the most submissions by May 7th 2016. If there's a tie, the user who has cracked submissions with the longest combined code will win.

The submission should be formatted like this:

# Language, nn characters (including link to answer), Cop's username

Code:

```
function a(n)
    if n<2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end

```

Output

```
a(0) returns 0
a(3) returns 2

```

Optional explanation and comments.

# Answer
# MATL, 5 bytes, Luis Mendo

```
H5-*|

```

This code calculates `abs((2-5)*input)` which is just `a(n)=3*n` for positive numbers, which is http://oeis.org/A008585
> 7 votes

# Answer
## Hexagony, 7 bytes, Adnan, A005843

```
?{2'*!@

```

or

```
 ? {
2 ' *
 ! @

```

Try it online!

Simply doubles the input (and assumes positive input). The code is (for once) simply executed in reading order. The code uses three memory edges *A*, *B*, *C* with the memory pointer starting out as shown:

```
?    Read integer from STDIN into edge A.
{    Move memory pointer forwards to edge B.
2    Set edge B to 2.
'    Move memory pointers backwards to edge C.
*    Multiply edges A and B and store result in C.
!    Print result to STDOUT.
@    Terminate program.

```
> 5 votes

# Answer
# J, 7 bytes, Cᴏɴᴏʀ O'Bʀɪᴇɴ

### Code

```
2+*:@p:

```

### Output

```
   f =: 2+*:@p:
   f 0
6
   f 2
27

```

Try it with J.js.

### How it works

Sequence A061725 is defined as **a(n) := pn² + 2**, where **pn** is the **(n + 1)th** prime number.

```
2+*:@p:  Monadic verb. Argument: n

    @    Atop; combine the verbs to the right and to the left, applying one after
         the other.
     p:  Compute the (n+1)th prime number.
  *:     Square it.
2+       Add 2 to the result.

```
> 4 votes

# Answer
# 05AB1E, 5 bytes, Adnan, A001788

```
Læ€OO

```

Try it online! This uses an alternative definition given on the page. Explanation:

```
Læ€OO
L     range;      [1..n]
 æ    powerset;   [[], [1], ..., [1..n]]
  €O  mapped sum; [0, 1, ..., T(n)]
    O sum;        [a(n)]

```
> 4 votes

# Answer
# JavaScript, 10 bytes, user81655, A033999

*~~I think~~ I got it. Yeah.* This one was really hard. I like the submission because it relies heavily on precedences.

---

It's the sequence A033999:

> a(n) = (-1)^n.

**Source**

```
t=>~t.z**t

```

**Explanation**

If you split this code according to the JavaScript operator precedences you get:

1. `.` (precedence *18*) gets evaluated first and `t.z` will return `undefined`.
2. `~` (precedence *15*) tries to cast `undefined`, resulting in `0`, and returns `-1` after bitwise not.
3. `**` (precedence *14*) will return `-1 ^ t`, where `t` is *odd* or *even*, resulting in `-1` or `1`.

**Demo**

```
console.log(
    (t=>~t.z**t)(0),
    (t=>~t.z**t)(1),
);

```

Try before buy

---

I will award a 100 rep bounty on this cool Cop submission.
> 4 votes

# Answer
# Element, 7 bytes, PhiNotPi, A000042

```
_'[,1`}

```

Notes: I was misled by the `}` for soooooo long. So it also matches `[`.

Try it online!

---

### How it works:

```
_'[,1`}
_        main_stack.push(input());
 '       control_stack.push(main_stack.pop());
  [      Object temp = control_stack.pop();
         for(int i=0;i<temp;i++){
   ,         Object a = main_stack.pop(); //is actually zero
             main_stack.push(a.toChars()[0]);
             main_stack.push(a);
    1        main_stack.push(1);
     `       System.out.println(main_stack.pop());
      }  }

```
> 3 votes

# Answer
# 05AB1E, 4 bytes, Paul Picard, A001317

Code:

```
$Fx^

```

Try it online!

Explanation:

```
$      # Pushes 1 and input
 F     # Pops x, creates a for-loop in range(0, x)
  x    # Pops x, pushes x and 2x
   ^   # Bitwise XOR on the last two elements
       # Implicit, ends the for-loop
       # Implicit, nothing has printed so the last element is printed automatically

```

The sequence basically is a binary Sierpinski triangle:

```
f(0)=      1                    =1
f(1)=     1 1                   =3
f(2)=    1 0 1                  =5
f(3)=   1 1 1 1                 =15
f(4)=  1 0 0 0 1                =17

```

And translates to the formula **a(n) = a(n - 1) XOR (2 × a(n - 1))**

Luckily, I remembered this one :)
> 3 votes

# Answer
# PHP, 41 bytes, insertusernamehere, A079978

```
echo/* does n%3=0 */$argv[1]%3<1?1:0    ;

```

Returns 1 if its argument is a multiple of 3, and 0 otherwise. Not much beyond that.
> 3 votes

# Answer
# Jolf, 3 bytes, Easterly Irk, A001477

```
axx

```

Consists of a simple cat (`ax`) followed by a no-op. Not sure what the cop was going for here.
> 3 votes

# Answer
# MATL, 9 bytes, beaker, A022844

Code (with a whitespace at the end):

```
3x2xYP*k

```

Try it online!

Found the following three matches with a script I wrote:

```
Found match: A022844
info: "name": "Floor(n*Pi).",

Found match: A073934
info: "name": "Sum of terms in n-th row of triangle in A073932.",

Found match: A120068
info: "name": "Numbers n such that n-th prime + 1 is squarefree.",

```

I tried to do the first one, which is basically done with `YP*k`:

```
3x2x       # Push 3, delete it, push 2 and delete that too
    YP     # Push pi
      *    # Multiply by implicit input
       k   # Floor function

```
> 3 votes

# Answer
# Java, 479 bytes, Daniel M., A000073

Code:

```
import java.util.*;
public class A{

    public static int i=0;
    public boolean b;

    static A a = new A();

    public static void main(String[] args){
        int input = Integer.parseInt(args[0]);

        LinkedList<Integer> l = new LinkedList<>();
        l.add(1);
        l.add(0);
        l.add(0);

        for(int ix = 0; ix<=input; ix++)if(ix>2){
            l.add(0,l//d
            .get(1)+l.peekFirst()+     l.get(2));
        }

        System.out.println(input<2?0:l.pop()
              +(A.i        +(/*( 5*/ 0 )));
    }
}

```

If you miss non-revealed characters, they are replaced with spaces.
> 3 votes

# Answer
# Ruby, 38 bytes, histocrat, A008592

```
->o{(s="+o++o"*5).sum==03333&&eval(s)}

```

Could be different from the intended solution as I found this by hand.
> 3 votes

# Answer
# S.I.L.O.S, betseg, A001844

```
readIO
a=i
a+1
i*2
i*a
i+1
printInt i

```

Try it online!
> 3 votes

# Answer
# Jolf, 5 characters, Cᴏɴᴏʀ O'Bʀɪᴇɴ, A033536

Code:

```
!K!8x

```

Output:

```
a(2) = 8
a(10) = 4738245926336

```
> 2 votes

# Answer
# Reng v3.3, 36 bytes, Cᴏɴᴏʀ O'Bʀɪᴇɴ, A005449

```
iv:#+##->>)2%æ~¡#~
#>:3*1+*^##</div>

```

## Output

```
a(1) = 2
a(3) = 15

```

## Explanation

I completely ignored the prespecified commands, except the `)` because I did not have enough space.

The actually useful commands are here:

```
iv      >>)2%æ~
 >:3*1+*^

```

Stretched to a straight line:

```
i:3*1+*)2%æ~

```

With explanation:

```
i:3*1+*)2%æ~ stack
i            [1]      takes input
 :           [1,1]    duplicates
  3          [1,1,3]  pushes 3
   *         [1,3]    multiplies
    1        [1,3,1]  pushes 1
     +       [1,4]    adds
      *      [4]      multiplies
       )     [4]      shifts (does nothing)
        2    [4,2]    pushes 2
         %   [2]      divides
          æ  []       prints
           ~ []       halts

```

The formula is `a(n) = n(3n+1)/2`.
> 2 votes

# Answer
# 05AB1E, 3 bytes, Adnan, A000292

```
LLO

```

### Output

```
a(9) = 165
a(10) = 220

```

### How it works

```
LLO Stack
L   [1,2,3,4,5,6,7,8,9]                         range
 L  [1,1,2,1,2,3,1,2,3,4,...,1,2,3,4,5,6,7,8,9] range of range
  O sum all of them

```

The mathematical equivalent is `sum(sum(n))`, where `sum` is `summation`.
> 2 votes

# Answer
# Python 2, 87 bytes, Sp3000, A083054

```
n=input()
_=int(3**.5*n)-3*int(n/3**.5)########################################
print _

```

Not that hard, actually. Just searched for sequences that met the constraints until I found one that could be generated in the given space.
> 2 votes

# Answer
# Jolf, 11 bytes, QPaysTaxes, A000005

```
aσ0xxdxxxxx

```

Simple enough: `a`lert the `σ0` (number of divisors of) `x`, then put useless stuff at the end.

Try it online! The test suite button's a bit broke, but still shows proper results.

(You could've golfed it down to two bytes! Just `σ0` would've done nicely.)
> 2 votes

# Answer
# Jolf, 11 bytes, RikerW, A011551

Code:

```
c*mf^+91x~P

```

Explanation:

```
     +91     # add(9, 1) = 10
    ^   x    # 10 ** input
  mf         # floor function (no-op)
 *       ~P  # multiply by phi
c            # ¯\_(ツ)_/¯

```

Try it here.
> 2 votes

# Answer
# JavaScript (ES6), 119 bytes, Cᴏɴᴏʀ O'Bʀɪᴇɴ, A178501

```
x=>(n="=>[[["|x|"##r(###f#n###;##")|n?Math.pow("#<1##].c####t.##pl##[####nc#"|10,"y([###(###(#]###)"|x-1|``):0|`#h####`

```

I'm sure the actual code generates a trickier sequence than this, but with just the two outputs, this OEIS sequence is simple and matches them.

Without all the ignored characters, the algorithm is just `x=>x?Math.pow(10,x-1):0`.
> 2 votes

# Answer
# 05AB1E, 5 bytes, Luis Mendo, A051696

Code:

```
Ðms!¿

```

Explanation:

```
Ð      # Triplicate input.
 m     # Power function, which calculates input ** input.
  s    # Swap two top elements of the stack.
   !   # Calculate the factorial of input.
    ¿  # Compute the greatest common divisor of the top two elements.

```

So, basically this calculates **gcd(n!, nn)**, which is A051696.

Try it online!.
> 2 votes

# Answer
# PHP, 18 bytes, insertusernamehere, A023443

Code:

```
echo$argv[1]+0+~0;

```

Output:

```
a(0) = -1
a(1) = 0

```
> 2 votes

# Answer
# Octave (34 bytes) by Stewie Griffin

The sequence is A066911.

```
@(m)(mod(m,u=1:m  )&isprime(u))*u'

```
> 2 votes

# Answer
# PHP, 137 bytes, insertusernamehere, A000959

Code:

```
for($s=range(1,303);$i<($t=count($s));$s=array_merge($s))for($j=($k=++$i==1?2:$s[$i-1])-1;$j<$t;$j+=$k )unset($s[$j]);echo$s[$argv[1]-1];

```

Output:

```
a(3)  =   7
a(7)  =  21
a(23) =  99

```
> 2 votes

# Answer
## 05AB1E, 10 bytes, George Gibson, A003215

**Code:**

```
Ds3*s1+*1+

```

**Explanation:**

Computes 3\*n\*(n+1)+1 which is the oeis sequence A003215.
> 2 votes

# Answer
# Element, 10 bytes, PhiNotPi, A097547

```
2_4:/2@^^`

```

Try it online!

## Output

```
a(3) = 6561
a(4) = 4294967296

```
> 1 votes

# Answer
# Pyke, 6 bytes, muddyfish, A005563

```
0QhXts

```

Yay hacks! The `0Qh` and `s` are no-ops. `hXt` just computes `(n + 1) ^ 2 - 1`.
> 1 votes

# Answer
# J, 8 bytes, Kenny Lau, A057427

Code:

```
(-%- )\.

```

Output:

```
a(0) = 0
a(1..29) = 1

```

I don't think this is intended. And I don't know why J had this behavior. But it works.
> 1 votes

# Answer
# Pyth, 70 bytes, FliiFe, A070650

Code (with obfuscated version below):

```
DhbI|qb"#"qb"#"R!1Iqb"#";=^Q6+""s ]%Q27  ;.qlY+Q1Ih+""Z##;.q)=Z+Z1;@YQ
DhbI|qb"#"qb"#"R!1Iqb"#"#####+""s####2###;##lY+Q1Ih+""Z#####)=Z+Z1;@YQ (obfuscated)

```

This basically does:

```
=^Q6%Q27

```

It calculates **a(n) = n6 % 27**, which is A070650. Explanation:

```
=^Q6       # Assign Q to Q ** 6
    %Q27   # Compute Q % 27
           # Implicit output

```

Try it here
> 1 votes

# Answer
## Python, 108, CAD97, A005132

```
def a(n):
 if n == 0: return 0
 f=a(n-1)-n
 return f if f>0 and not f in(a(i)for i in range(n))else a(n-1)+n

```

Obfuscated code :

```
def a(n):
 ###n####0######n#0
 f=a#######
 return f #f#####a###### f ####a(##f###i#i###a####n##else a#######

```

Outputs:

```
>>> a(0)
0
>>> a(4)
2
>>> a(16)
8
>>> a(20)
42

```
> 1 votes

# Answer
# C (71 bytes) by mIllIbyte

The sequence is floor(n/4).

```
x;f(_){x/=4;
    }
main(){
 scanf("%d",&x);
 f( 6);
 printf("%d", x);
}

```
> 1 votes

# Answer
# Python 3 (58 bytes) by CAD97

The sequence is A062318. There were a lot of unnecessary characters in this one, so I commented some out.

```
a=lambda n: ~-( -~(n%2)
# if ###### else
*3**(n//2))#)##)

```
> 1 votes

# Answer
## Ruby, 11 bytes, histocrat, A011765

It only needs 5...

```
->i{i%4/3 }

```

I'd like to note though that the sequence is off-by-one compared to OEIS (which specifies that the first term corresponds to `A(1)`).
> 1 votes

# Answer
## Haskell, 51 bytes, Zgarb, A063866

```
f e=sum[1|1<-sum<$>mapM(flip(:)=<<pure.(0-))[1..e]]

```

Output: `map f [0..6]`: `[0,1,1,0,0,3,5]`.
> 1 votes

# Answer
# 05AB1E, 5 bytes, Adnan, A102669

Code:

```
TA«-g

```

Output:

```
a(0) = 0
a(1) = 0
a(2) = 1
a(3) = 1
a(4) = 1
a(5) = 1
a(6) = 1
a(7) = 1
a(8) = 1
a(9) = 1
a(10) = 0
a(11) = 0

```

Too bad you have designed the language in this inconvenient way.
> 1 votes

# Answer
## Python, 17 bytes, ASCIIThenANSI, A000027

```
def a(n):return n

```

Trivial?
> 1 votes

# Answer
## Python, 60 bytes, ASCIIThenANSI A000930

```
def a(n):
 if n<3:
  return 1
 else:
  return a(n-1)+a(n-3)

```

Still trivial
> 1 votes

# Answer
# 05AB1E, (4 bytes) by Adnan

The sequence is A126804, and the code to produce it is

```
D·ŸP

```

Try it online

I've never even looked at a program in 05AB1E before, it looks like a pretty cool language!
> 1 votes

# Answer
# Lua, 45 bytes, Katenkyo, A001477

```
a=function(n)return n-1<1 and 0or 1+a(n-1)end

```
> 1 votes

# Answer
## Swift, 55 bytes, Nefrin, A103847

The sequence is McCarthy's 91 Function.
It takes the value **91** for any **n** up to **101** and then continues with **92,93,94 ...**

I wonder what it's actually useful for.

```
func M(n:Int)->Int{
return(n<=100) ?M(M(n+11)):n-10;
}

```
> 1 votes

# Answer
## 05AB1E, 28 bytes, Lause, A256861

**Code:**

```
DD>D>D>D>****sD<*6+*6n2n5**/

```

**Explanation:**

```
              # implicit n on stack
DD>D>D>D>     # save n,n+1,n+2,n+3,n+4 on the stack
****          # multiply top 5 on stack together
              #     new stack: n,n(n+1)(n+2)(n+3)(n+4)
sD<*          # rotate, duplicate, decrease, multiply
              #     new stack: n(n+1)(n+2)(n+3)(n+4),n(n-1)
6+*           # add 6 to stack, add top 2, multiply top 2
              #     new stack: n(n+1)(n+2)(n+3)(n+4)(n(n-1)*6)
6n2n5**       # add 720 to stack
/             # divide
              # implicitly print n(n+1)(n+2)(n+3)(n+4)(n(n-1)*6)/720

```
> 1 votes

# Answer
## Jolf, 3 bytes, Cᴏɴᴏʀ O'Bʀɪᴇɴ, A091940

```
+QQ

```

Test it here.

Since the output is off-by-one, the second formula on OEIS reduces to `n + n^4`. Where we implement `n^4` by squaring the input twice.
> 1 votes

# Answer
## 05AB1A, 4 bytes, Adnan, A001127

**Code:**

```
$FÂ+

```

**Explained:**

```
$          # push 1 and input
 F         # input number of times, do:
  Â        # duplicate and reverse
   +       # add

```

The sequence starts at **1** and continues by adding the current number to its reverse.

```
0: 1
1: 1+1 = 2
2: 2+2 = 4
3: 4+4 = 8
4: 8+8 = 16
5: 16+61 = 77
6: 77+77 = 154
7: 154+451= 605
and so on...

```
> 1 votes

# Answer
# 05AB1E, 3 bytes, Emigna, A022559

Code:

```
!ÓO

```

Explanation:

```
!    # Compute the factorial of the implicit input.
 Ó   # Compute the exponents of the prime factors.
  O  # Sum that up together.

```

Resulting into **A022559**. Try it online!
> 1 votes

# Answer
## 05AB1E, 1 byte, mnbvc, A004085

Code:

```
Õ

```

Sequence is the sum of digits of Euler totient function of n.
> 1 votes

# Answer
## LiveCode, 35 bytes, mnbvc, A001477

I/O:

```
oeis (0) = 0
oeis (2) = 2

```

Code:

```
function oeis n
    return n*1
End oeis

```

Sequence returns the non-negative integers.
> 1 votes

# Answer
## Python, 37 bytes, mnbvc, A000290

I/O:

```
a(2) = 4
a(4) = 16

```

Code:

```
def a(n):
    return n*n#__!______n____*_

```

Sequence return square of input
> 1 votes

# Answer
# 05AB1E, 3 bytes, Emigna, A002994

Code:

```
3m¬

```

Explanation:

```
3m   # Compute input ** 3
  ¬  # Take the first digit

```

This gives us the *initial digits of the cubes*, which is **A002994**.

Uses **CP-1252** encoding. Try it online!.
> 1 votes

# Answer
# 05AB1E, 8 bytes, Emigna, A088666

Code (with obfuscated version below):

```
4m1s+rT%
___s_r__

```

Explanation:

```
4m         # Compute input ** 4
  1        # Add one to the stack
   s       # Swap the top two elements
    +      # Add the two numbers (result = input ** 4 + 1)
     r     # Reverse the stack
      T    # Add 10
       %   # Modulo

```

This comes down to the formula **a(n)** = **(n4 \+ 1) % 10**, which is **A088666**. I'm excited to see what the original code was.

Try it online!.
> 1 votes

# Answer
## J, 8 bytes, Kenny Lau, A057427

Code:

```
(>1-*)<.

```

Output:

```
a(0) = 0
a(i) = 1 for 0 < i < 30

```

The sequence is simply `signum(n)`. The program computes `floor(n) > 1 - signum(floor(n))`, which is `signum(n)` for non-negative integers `n`.
> 0 votes

# Answer
## Python 3, 50 bytes, CAD97, A004242

```
from math import    *
a=lambda n:ceil(1000*log(n))

```

Try it online

Output:

```
a(1) => 0
a(10) => 2303

```
> 0 votes

# Answer
# Python 2 (72 bytes) by Sp3000

There's an unbelievable amount of sequences starting with 1,2,3,6,9,18 from the 1 element. I was fortunate to find one on the 3rd page where these are the only 6 terms: Divisors of 18.

```
print[1,#((#y
2,3,6,9,#.####c###6#####16#.
18][#)#131963
~-input()#3
]#)

```
> 0 votes

# Answer
# Pyth, 4 bytes, FliiFe, A000041

Code:

```
l./Q

```

Explanation:

```
 ./Q  # Calculate the paritions of Q (input)
l     # Take the length, which counts the number of partitions.

```

Try it here.
> 0 votes

# Answer
# JavaScript, 30 bytes, Aplet123, A002061

It's the sequence A002061:

> Central polygonal numbers: `n^2 - n + 1.`

```
n=>Math.pow(n,!![]+!![])-(n-1)

```

See it in action on JSFiddle.
> 0 votes

# Answer
# Python, 123 bytes, ASCIIThenANSI, A089911

Code:

```
def f(n):
 if n<2:
  return n
 else:
  return f(n-1)+f(n-2)

def g(n):
 if n<2:
  return n
 else:
  return (f(n-1)+f(n-2))%12

```

The formula for this sequence is **g(n) = f(n) % 12**, whereas **f(n)** is the **nth** Fibonacci number.

This was actually a really nice puzzle! :)
> 0 votes

# Answer
# Python 3, 58 bytes, Mega Man

```
import math;x=int(input());print(int(x/math.sqrt(5)*x**x))

```

The sequence is:

```
(x/√5)*(x**x)

```
> 0 votes

# Answer
# Python, 42 bytes, TùxCräftîñg

```
def f(x):return x if x<2else f(x-1)+f(x-2)

```

This is the Fibonacci sequence.
> 0 votes

---
Tags: number, sequence, cops-and-robbers
---


title: Golf yourself a beer

text:
# Question
Title: Golf yourself a beer
It's friday! Which means it's time for beer!
Sadly though, today we will be golfing beer instead of drinking it. :(

### Challenge

Output a beer and drink it. The amount of sips you take changes your output.

### Sips

Your program should take one input string. This string can solely consist out of concatenated `sip`s.
If the input is an empty string, you should output a full beer glass, including foam.

The more sips you take, the emptier your beer glass will be.

If you take 0 sips, your beer still has foam. The output of this foam is always the same (see examples).

If you take 1 sip, you should output the beer glass, followed by a new line and the string `Yuck, foam.`.

If you take 1 or more sips, your beerglass should not contain anymore foam, but should show the top of your glass. Drinking the foam counts as one sip.

If you take 6 or more sips, you should output an empty beer glass, followed by a new line and the string `Burp`.

For each sip you take, your beer glass should become emptier. How full your beerglass is depends on the amount of bubbles `°` (`°`) in your beer. For each sip you take after the foam, a line of bubbles should be removed. Each line of beer can contain a minimum of `1` and a maximum of `5` bubbles. The position of these bubbles should be 100% random.

### Examples

**input**

`empty input string, or no input at all`

**output**

```
  oo  o oo
 oooooooooooo
o|  °     ° |\
 |     °    | \
 | °°    °  |} |
 |  °    °  | /
 |     °   °|/
 \__________/

```

**input**

`sip sip sip`

**output**

```
 ____________
 |          |\
 |          | \
 |     °    |} |
 |° °     ° | /
 | °    °   |/
 \__________/

```

**input**

`sip sip sip sip sip sip sip sip sip sip`

**output**

```
 ____________
 |          |\
 |          | \
 |          |} |
 |          | /
 |          |/
 \__________/
Burp

```

This pastebin contains a list of inputs and outputs. Remember that the bubbles in the beerglass should be random!

### Scoring

This is , shortest code in bytes wins!

Happy ~~drinking~~ golfing!

# Answer
# Japt, 189 bytes

I almost went insane while trying to get this to work properly...

```
U?S+'_pC +R:"  oo  o oo\n "+'opC +"\no")+"\\, \\,} |, /,/"q', £(V=(!Y«U?"|: |" +SpA +'|+X,(1+5*Mr)o mZ=>Ul <Y*4+4©(V=Vh2+A*Mr ,'° ),V)qR +"\n \\"+'_pA +'/+R+(Ul ¥3?"Yuck, foam.":Ug22 ?`B¨p:

```

### Try it online!

<sub>(Note: This program was made for an older version of Japt, and doesn't currently work in the latest version. To get around this, the older version is specified in the URL. Unfortunately, this also means the top-right code box doesn't work.)</sub>

This is *by far* the longest program I have ever written in Japt. Here's a breakdown:

**Step 1:** Create the top of the beer mug.

```
U?S+'_pC +R:"  oo  o oo\n "+'opC +"\no")

           // Implicit: U = input string
           // Begin the ASCII art with:
U?S+       //  If U is not an empty string, a space +
'_pC +R:   //   "_".repeat(12) + a newline.
:"..."+    //  Otherwise, this string +
'opC +     //   "o".repeat(12) +
"\no")     //   a newline and an "o".

```

If U is an empty string, this makes:

```
  oo  o oo
 oooooooooooo
o

```

Otherwise, this makes:

```
 ____________

```

**Step 2:** Create the middle rows of the mug.

```
+"\\, \\,} |, /,/"q', £(V=(!Y«U?"|: |" +SpA +'|+X,

+"..."    // Add to the previous string: this string,
q', £(    // split at commas, with each item X and its index Y mapped to:
V=(       //  Set variable V to the result of concatenating:
!Y«U?     //   If Y is 0 and U is an empty string,
"|: |"    //    "|"; otherwise, " |";
+SpA      //   10 spaces,
'|+X,     //   "|", and X.

```

This results in the previous string plus:

```
 |          |\
 |          | \
 |          |} |
 |          | /
 |          |/

```

**Step 3:** Add the bubbles.

```
(1+5*Mr)o mZ=>Ul <Y*4+4©(V=Vh2+A*Mr ,'° ),V)

            // Note: We're still looping through the five rows at this point.
(1+5*Mr)    // Generate a random integer between 1 and 5.
o           // Create an array of this many integers, starting at 0.
mZ=>        // Map each item Z in this range to:
Ul <Y*4+4©  //  If the length of U is less than Y*4+4,
            //  (in other words, if there's less than Y+1 "sip"s)
(V=Vh   '°  //   Insert "°" at position
2+A*Mr      //    2 + random number between 0 and 9.
),V)qR      // Finally, return V, and join the five rows with newlines.

```

At this point, the mug looks something like this:

```
 ____________
 |          |\
 |          | \
 |     °    |} |
 |° °     ° | /
 | °    °   |/

```

**Step 4:** Add the final row and optional text.

```
+"\n \\"+'_pA +'/+R+(Ul ¥3?"Yuck, foam.":Ug22 ?`B¨p:

+"\n \\"    // Add a newline and " \".
+'_pA       // Add 10 "_"s.
+'/+R       // Add a slash and a newline.
+(Ul ¥3?    // If the length of U is 3 (i.e. 1 "sip"),
"..."       //  add the string "Yuck, foam.".
:Ug22 ?     // Otherwise, if U has a character at position 22 (six or more "sip"s),
`B¨p        //  decompress this string ("Burp") and add it.
:           // Otherwise, add nothing.

```

Now everything is ready to be sent to output, which is done automatically. If you have any questions, feel free to ask!
> 10 votes

# Answer
# JavaScript (ES6), ~~283~~ 281 bytes

```
s=>` `+(u=`_________`,(s=s&&s.split` `.length)?u+`___
 `:` oo  o oo
 oooooooooooo
o`)+(i=0,l=q=>`|`+[...u].map(_=>Math.random()>.8&i>=s&&b++<5?`°`:` `,b=0,i++).join``+(b|i<s?` `:`°`)+`|`+q+`
 `)`\\`+l` \\`+l`} |`+l` /`+l`/`+`\\`+u+`_/
`+(s&&s<2?`Yuck, foam.`:s>5?`Burp`:``)

```

## Explanation

```
s=>
  ` `+(u=`_________`,        // u = 9 underscores
  (s=s&&s.split` `.length)   // s = number of sips
    ?u+`_
 `:` oo  o oo
 oooooooooooo
o`)                          // print glass top or foam

  // Print glass lines
  +(i=0,                     // i = line number
    l=q=>                    // l = print glass line
      `|`+[...u].map(_=>     // iterate 9 times
        Math.random()>.8     // should we put a bubble here?
        &i>=s                // has this line already been sipped?
        &&b++<5              // have we already placed 5 bubbles?
          ?`°`:` `,          // if not, place the bubble!
        b=0,                 // reset the number of placed bubbles
        i++                  // increment the line counter
      ).join``               // put the 9 spaces and bubbles together
      +(b|i<s?` `:`°`)       // place a bubble at 10 if none were placed
      +`|`+q+`
 `                           // print the suffix of this glass line
  )`\\`
  +l` \\`
  +l`} |`
  +l` /`
  +l`/`

  +`\\`+u+`_/
`                            // print the bottom of the glass
  +(s&&s<2?`Yuck, foam.`
    :s>5?`Burp`:``)          // print the message

```

## Test

```
Input: <input type="text" id="sips" /><button onclick="result.innerHTML=(

s=>` `+(u=`_________`,(s=s&&s.split` `.length)?u+`___
 `:` oo  o oo
 oooooooooooo
o`)+(i=0,l=q=>`|`+[...u].map(_=>Math.random()>.8&i>=s&&b++<5?`°`:` `,b=0,i++).join``+(b|i<s?` `:`°`)+`|`+q+`
 `)`\\`+l` \\`+l`} |`+l` /`+l`/`+`\\`+u+`_/
`+(s&&s<2?`Yuck, foam.`:s>5?`Burp`:``)

)(sips.value)">Go</button><pre id="result"></pre>
```
> 4 votes

# Answer
# PHP, ~~277~~ ~~265~~ 263 bytes

Assuming 1-byte-linebreak. Add one to `14` and `17` on Windows.

```
$r=str_pad(($i=$argc-1)?"":"  oo  o oo",16).str_pad("
 ",14,_o[!$i])."   ".($s="
 |          |")."\\  $s \\ $s} |$s / $s/
 \__________/
 ".($i<6?$i-1?"":"Yuck, foam.":burp)if(!$i){$r[34]=o;$i=1;}for(;$i++<6;)for($n=rand(1,5);$n--;)$r[17*$i+rand(2,11)]="°";echo$r;

```

Run with `-r`. line breaks may need escaping.

**breakdown**

```
// draw beer glass
$r=
    // first line: empty or foam
    str_pad(($i=$argc-1)?"":"  oo  o oo",16)
    // second line: top or foam
    .str_pad("\n ",14,_o[!$i])
    // other lines: empty glass+bottom
    ."   ".($s="\n |          |")."\\  $s \\ $s} |$s / $s/\n \__________/\n"
    // lyrics
    .($i<6?$i-1?"":"Yuck, foam.":burp)
;

// add foam left to the glass
if(!$i){$r[34]=o;$i=1;}

// add bubbles
for(;$i++<6;)
    for($n=rand(1,5);$n--;)
        $r[17*$i+rand(2,11)]="°";

// output
echo$r;

```
> 1 votes

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


# Question
Title: A regex to satisfy the grammar police (there vs. their vs they're)
We've all been burned by the grammar police on the internet. What we need is a regex that can be used in place of "there", "their", and "they're". This would shift burden of grammar parsing from the writer to the reader (a sort of "client-side" grammar, if we you will). So, here's what I have to start with:

`the([re]|[ir]|[y're]).`

...but I'm positive there's room for optimization.

What's the shortest regex that could be used in place of any variation or the aforementioned homohpones?

# Answer
There isn't a lot of room for optimisation here. This seems to be optimal:

```
the(y're|re|ir)

```

The only alternative I can think of avoids the duplication of `re` but ends up at the same byte count (and it's potentially worse in flavours where meta characters need to be escaped to work):

```
the((y')?re|ir)

```
> 17 votes

---
Tags: code-golf, regular-expression
---


# Question
Title: Shortest possible JS (ES5) code to get ids of all elements of a given tag
Using the shortest JS (ES5) code possible, as measured in number of characters, gather all the ids on a page for `foobar` elements into a comma-delimited string. For example:

```
<div>
  <foobar id="456"></foobar>
  <foobar id="aaa"></foobar>
  <foobar id="987"></foobar>
<div>

```

Should give `"456,aaa,987"`

You cannot use ES6 or any libraries. The `foobar` elements will not ever be nested.

My current shortest solution is

```
[].map.call(document.querySelectorAll("foobar"),function(a){return a.id}).join()

```

Can anyone beat it?

# Answer
I don't *think* it's going to get shorter than this:

```
[].map.call(document.querySelectorAll("foobar"),function(a){return a.id})+""

```

Hopefully someone can prove me wrong!
> 2 votes

---
Tags: code-golf, javascript
---


# Question
Title: Compute the histogram entropy estimation of a string
Write a program or function that estimates the Shannon entropy of a given string.

If a string has *n* characters, *d* **distinct** characters, *xi* is the *i* th distinct character, and *P(xi)* is the probability of that character occuring in the string, then our Shannon entropy estimate for that string is given by:

For the estimation in this challenge we assume that the probability of a character occurring in a string is simply the number of times it occurs divided by the total number of characters.

Your answer must be accurate to at least 3 digits after the period.

---

Test cases:

```
"This is a test.", 45.094
"00001111", 8.000
"cwmfjordbankglyphsvextquiz", 122.211
"             ", 0.0

```

# Answer
# Jelly, ~~11~~ 8 bytes

```
ċÐ€÷Ll.S

```

Try it online!
> 2 votes

# Answer
## Python 3.3+, 64 bytes

```
import math
lambda s:sum(math.log2(len(s)/s.count(c))for c in s)

```

Got `math.log2` from mbomb007's solution.
> 11 votes

# Answer
# APL, ~~18~~ 14 bytes

```
+/2⍟≢÷(+/∘.=⍨)

```

This is an unnamed, monadic function train that accepts a string on the right and returns a real.

Like all good things in life, this uses xnor's formula. We get a matrix of booleans corresponding to the occurrences of each character in the string using `∘.=⍨`, sum this along the first axis (`+/`) to get the number of occurrences of each character, divide the length of the string by each, then take log base 2 (`2⍟`) and sum.

Try it here

Saved 4 bytes thanks to Dennis!
> 2 votes

# Answer
# Perl 5, 58 bytes

A subroutine:

```
{for$a(@a=split'',pop){$t+=(log@a/grep/\Q$a/,@a)/log 2}$t}

```

A tip of my hat to xnor for the formula.
> 1 votes

# Answer
# MATL, 17 bytes

```
S4#Y'ts/tZl*sGn_*

```

Try it online!
> 1 votes

# Answer
# J - ~~18~~ ~~16~~ 14 bytes

```
1#.2^.#%1#.=/~

```

Shortened using the idea in Dennis' method.

## Usage

```
   f =: 1#.2^.#%1#.=/~
   f 'This is a test.'
45.0936
   f '00001111'
8
   f 'cwmfjordbankglyphsvextquiz'
122.211
   f '             '
0

```

## Explanation

```
1#.2^.#%1#.=/~  Input: string S
           =/~  Create a table testing for equality
        1#.     Convert each row from a list of base 1 digits to decimal
                This is equivalent to taking the sum and forms a list of tallies
      #         Get the length of S
       %        Divide the length by each tally
   2^.          Log base 2 of each
1#.             "Sum" those values and return

```
> 1 votes

# Answer
## JavaScript (ES6), 67 bytes

```
s=>[...s].map(c=>t+=Math.log2(s.length/~-s.split(c).length),t=0)&&t

```

I need to use `~-s.split` because that accepts strings rather than regexps. As usual, `map` beats `reduce` by a byte.

```
s=>[...s].reduce((t,c)=>t+Math.log2(s.length/~-s.split(c).length),0)

```
> 1 votes

# Answer
# MATL, 14 bytes

```
!Gu=stGn/Zl*s|

```

**Try it online!**

```
!      % transpose implicit input into column vector
Gu     % row vector with unique elements of input
=      % test for equality, element-wise with broadcast
s      % sum of each column
tGn/   % duplicate. Divide by number of input characters
Zl     % binary logarithm
*      % element-wise multiplication
s      % sum of array
|      % absolute value. Display implicitly

```
> 1 votes

# Answer
# Julia, 37 bytes

```
x->sum(log2(endof(x)./sum(x.==x',1)))

```

Takes a character array as input. Try it online!
> 1 votes

# Answer
# Pyth - 17 bytes

```
*_lQsm*FlBc/QdlQ{

```

Try it online here.
> 0 votes

# Answer
# Jolf, 26 bytes

```
_*liuΜGμiEd*γ/l miLeHlimzγ

```

Try it here! (Note that the test suite function is borked.)

## Explanation

```
_*liuΜGμiEd*γ/l miLeHlimzγ
       μi                   unique members of i
      G  E                  split on ""
     Μ    d                 map over function
               _miLeH       match i with regex escaped member
             /l      li     divide length of (^) by length of i
            γ               γ = (^)
           *           mzγ  (^) * log_2(γ)
 *li                        (^) * length of i
_                           negate

```
> 0 votes

# Answer
# Python 3.3+, ~~95~~ ~~91~~ ~~89~~ 85 bytes

Simple solution. Version 3.3 is required to use `math.log2`.

```
import math
def f(s):C=s.count;return-sum(C(x)*math.log2(C(x)/len(s))for x in set(s))

```

**Try it online**
> 0 votes

# Answer
# Java 7, 207 bytes

```
double C(String x,Map<Character,Integer>f){double H=0,g;for(char c:x.toCharArray())f.put(c,f.containsKey(c)?f.get(c)+1:1);for(char c:f.keySet()){g=f.get(c);H+=g*Math.log(g/x.length())/Math.log(2);}return-H;}

```

**Detailed** try online

```
double log2(double d) { return Math.log(d) / Math.log(2); }

double C(String x, Map<Character,Integer>f)
{
    double H=0,g;

    // frequency
    for(char c : x.toCharArray())
    {
        f.put(c, f.containsKey(c) ? f.get(c)+1 : 1);
    }

    // calculate entropy
    for(char c : f.keySet())
    {
        g = f.get(c);
        H += g * log2(g / x.length());
    }

    return -H;
}

```
> 0 votes

# Answer
# Factor, 98 bytes

```
[ [ length ] [ dup [ [ = ] curry dupd count ] { } map-as nip ] bi [ / log 2 log / ] with map sum ]

```

This is a direct translation of this Python answer. I'll add an explanation over dinner.
> 0 votes

# Answer
# Racket, 130 bytes

:c

```
#lang racket
(require math)(λ(S)(let([s(string->list S)])(sum(map(λ(c)(/(log(/(length s)(count(λ(x)(char=? c x))s)))(log 2)))s))))

```

Translation of my Factor answer, so it's an indirect translation of Kenny Lau's Python answer.
> 0 votes

# Answer
# k (32 bytes)

```
{-+/c*(log c%n:+/c:#:'=x)%log 2}

```

Or in `q`, the translation is not all that short but clearer:

```
{neg sum c*2 xlog c%n:sum c:count each group x}

```
> 0 votes

# Answer
# Mathematica, 45 bytes

```
Tr[Log[2,Tr@#/#]#]&@Values@CharacterCounts@#&

```

## Usage

This returns exact results so we approximate them with `N`.

```
  f = Tr[Log[2,Tr@#/#]#]&@Values@CharacterCounts@#&
  f["This is a test."]//N
45.0936
  f["00001111"]//N
8.
  f["cwmfjordbankglyphsvextquiz"]//N
122.211
  f["             "]//N
0.

```
> 0 votes

# Answer
# R, 67 bytes

```
l=length(i<-strsplit(readline(),"")[[1]]);-sum(log2(l/table(i)[i]))

```

### Explanation

Take input from stdin and split it into a list of characters. (This clunky syntax is why string golf challenges are so tough in R...)

```
         i<-strsplit(readline(),"")[[1]])

```

This assignment is hidden inside of a `length` command, so we get two assignments for the price of one. We have `i`, the list of characters, and `l`, its length.

```
l=length(i<-strsplit(readline(),"")[[1]]);

```

Now we calculate the entropy. R has a nice function `table` which returns the counts of all unique values. For input `This is a test`, `table(i)` returns

```
> table(i)
i
  . a e h i s t T
3 1 1 1 1 2 3 2 1

```

This is indexed by characters, which is nice, as we can then use `i` as an index to get the count of each character, like so:

```
> table(i)[i]
i
T h i s   i s   a   t e s t .
1 1 2 3 3 2 3 3 1 3 2 1 3 2 1

```

The rest of the code is then a simple implementation of the entropy formula, flipped around a little.

```
                                           -sum(log2(l/table(i)[i]))

```
> 0 votes

# Answer
# C#, 159 bytes

Golfed:

```
string f(string s){var l=s.Length;double sum=0;foreach(var item in s.GroupBy(o=>o)){double p=(double)item.Count()/l;sum+=p*Math.Log(p,2);}return(sum*=-l)+"";}}

```

Ungolfed:

```
string f(string s)
{
  var l = s.Length;
  double sum = 0;
  foreach (var item in s.GroupBy(o => o))
  {
    double p = (double)item.Count() / l;
    sum += p * Math.Log(p, 2);
  }
  return (sum *= -l) + "";
}

```

Test:

```
var codeGolf = new StringHistogramEntropyEstimation();
    Console.WriteLine(codeGolf.f("This is a test.")); //45.0935839298008
    Console.WriteLine(codeGolf.f("00001111")); //8
    Console.WriteLine(codeGolf.f("cwmfjordbankglyphsvextquiz")); //122.211432671668
    Console.WriteLine(codeGolf.f("             ")); //0

```
> 0 votes

# Answer
# Groovy, 100 Bytes

```
{a->n=a.size();a.toList().unique().collect{p=a.count(it)/n;p*(Math.log(p)/Math.log(2.0f))}.sum()*-n}

```

## Tests:

```
This is a test. = 45.09358393449714
00001111 = 8.0
cwmfjordbankglyphsvextquiz = 122.21143275636976
aaaaaaaa = -0.0

```
> 0 votes

---
Tags: code-golf, string, probability-theory
---


title: Sieve of Eratosthenes, Step by Step

text:
# Question
Title: Sieve of Eratosthenes, Step by Step
Given a number *N*, draw a left aligned *N*x*N* board of numbers, leaving 1 blank (as a space) (I will show diagrams with *N*=5)

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

```

Your job is to construct the Sieve of Eratosthenes, step by step. First, start with 2. It's prime, so leave it there, and replace all other numbers divisible by 2 with the proper number of spaces.

```
   2  3     5
   7     9
11    13    15
   17    19
21    23    25

```

Next, go to the next unprinted number (`3` in this case) and do the same.

```
   2  3     5
   7
11    13
   17    19
      23    25

```

And so on, until you reach *N*.

You need to first print the complete grid, and every time you go to a new number, print the board with the multiples removed. Make sure you print a blank line in between!

## Examples

Text in parenthesis `()` are just for reference, you don't need to print it

*N* = 2:

```
  2 (complete grid)
3 4

  2 (remove multiples of 2)
3

```

*N* = 3:

```
  2 3 (complete grid)
4 5 6
7 8 9

  2 3 (remove multiples of 2)
  5
7   9

  2 3 (remove multiples of 3)
  5
7

```

Remember, this is , so the code with the smallest number of bytes wins.

# Answer
# Jelly, 34 bytes

```
Ṿ€“1“ ”ys³G
>®i©1ḍoṛ®¦
²R;1©ÇÐĿÑ€Y

```

Try it online!

### How it works

```
²R;1©ÇÐĿÑ€Y  Main link. Argument: n (integer)

²            Yield n².
 R           Range; yield [1, ..., n²].
   1©        Yield 1 and copy it to the register.
  ;          Append 1 to the range.
             This is the initial state. Let's call it S.
     ÇÐĿ     Call the second helper link until the results are no longer unique.
             This returns all unique results as an array.
        Ṅ€   Call the first helper link on each result.
          Y  Join, separating by linefeeds.

>®i©1ḍoṛ®¦   Second helper link. Argument: S (state)

>®           Compare all integers in S with the value in the register.
  i 1        Find the first index of 1 (i.e., the first number that is greater
             than the register.
   ©         Copy the index to the register. Let's call the index p.
     ḍ       Test all numbers in S for divisibility by p. This yield 1 for
             multiples of p, 0 otherwise.
      o      Logical OR; replace 0's with the corresponding values of S.
       ṛ®¦   Replace the 0 at index p with the corresponding element of S (p).
             For the purposes of the explanation, S is now the updated state.

Ṿ€“1“ ”ys³G  First helper link. Argument: A (array)

Ṿ€           Uneval each; convert all integers in A into strings.
  “1“ ”y     Replace each string "1" with the string " ".
        s³   Split into chunks of length n (command-line argument).
          G  Grid; separate row items by spaces (left-padding since the row items
             are strings), the rows themselves by linefeeds.

```
> 7 votes

# Answer
# Perl, ~~250~~ ~~243~~ ~~231~~ ~~202~~ 157 bytes

```
$n=<>;@a=0..($e=$n*$n);$a[1]=$";for$p(1..$n){next if!$a[$p];for(1..$e){$a[$_]=""if!($p~~[(1,$_)]||$_%$p);printf"%-*s",1+length$e,$a[$_];say""if!($_%$n)}say}

```

Test the current golf online! (be sure to run as `perl -M5.010 main.pl`)

The two literal newlines each save 1 byte in place of \n.

Sample output (input of 7):

```
   2  3  4  5  6  7
8  9  10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35
36 37 38 39 40 41 42
43 44 45 46 47 48 49

   2  3     5     7
   9     11    13
15    17    19    21
   23    25    27
29    31    33    35
   37    39    41
43    45    47    49

   2  3     5     7
         11    13
      17    19
   23    25
29    31          35
   37          41
43          47    49

   2  3     5     7
         11    13
      17    19
   23
29    31
   37          41
43          47    49

   2  3     5     7
         11    13
      17    19
   23
29    31
   37          41
43          47

```

I'm positive I didn't golf it very well, so when I get home I'll take another look at it to see just how much I can shave off.

Edit 1: -7 bytes (changing "print sprintf" to the obvious "printf")

Edit 2: Saved 12 bytes by using $d explicitly in the one place it was called instead of creating a separate variable, by combining some declarations, and by eliminating one of my conditions for the `next` statement inside the first `foreach` loop by adding a space somewhere else. An additional 29 bytes were golfed out by reworking two for loops into a single loop, eliminating two variable declarations, and turning `unless` statements into if-not statements. Declaring `my$e=$n*$n;` then replacing the three instances of $n\*$n with $e (allowing me to drop a paren for one of them) turned out to yield ±0 bytes, but I kept it in anyway.

Edit 3: Thanks to @Dada, another 40 bytes were golfed out (variable declarations, 'foreach' becoming 'for', implicit $\_ in several locations, and cutting down on the printf statement size). An additional 1 byte was shaved off by turning `if!($c%$p||$c==$p||$p==1)` into `if!($p~~[(1,$_)]||$_%$p)`. Unfortunately, the \[\] around the array is necessary, because the smartmatch operator ~~ is still experimental and doesn't seem to work properly on actual arrays, but does work on references to them instead. 4 more bytes were removed by removing two semicolons and an empty set of quotation marks after the last `say`.
> 5 votes

# Answer
# PHP, 155 Bytes

```
for(;$d++<$n=$argv[1];$x&$a[$d]<1?:print"\n".chunk_split(join($a),$n*$l))for($i=$d*$x=$d>1;$n**2>=$i+=$d;)$a[$i]=str_pad($x|$i<2?"":$i,$l=strlen($n**2)+1);

```

@Crypto -3 Bytes Thank You @Titus -6 Bytes Thank You

Try it

First time that I use print in a after loop condition

Breakdown

```
for(;$d++<$n=$argv[1];
$x&$a[$d]<1?:print"\n".chunk_split(join($a),$n*$l))
#after loop print the grid if $d = 1 or is prime
for($i=$d*$x=$d>1;$n**2>=$i+=$d;)
$a[$i]=str_pad($x|$i<2?"":$i,$l=strlen($n**2)+1);
#fills the array at first run and replace positions with space in the next runs

```

Previous Version 174 Bytes

```
for(;$d++<=$n=$argv[1];!($d<2||$a[$d]>0)?:print chunk_split(join($a),$n*$l)."\n")for($i=$d<2?1:2*$d;$i<=$m=$n**2;$i+=$d)$a[$i]=str_pad($d<2?($i<2?"":$i):" ",$l=strlen($m)+1);

```
> 5 votes

# Answer
# R, ~~195~~ ~~191~~ ~~185~~ 204 bytes

```
f=function(N){a=b=1:N^2;i=1;a[1]="";S=sprintf;while(i<=N){for(j in b)cat(a[j]<-S(S("%%-%is",nchar(N^2)),if(j==i|j%%i|i<2)a[j]else ""),if(j%%N)"" else"\n");cat("\n");i=(grep("\\d",a[-(1:i)],v=T)[1]:1)[1]}}

```

Thanks to @Billywob for 6 extra bytes saved!

Indented, with newlines:

```
f=function(N){
   a=b=1:N^2 #Initial array
   i=1 #Turn counter
   a[1]="" #1 never shown
   S=sprintf
   while(i<=N){
      for(j in b)
         cat(a[j]<-S(S("%%-%is",nchar(N^2)),if(j==i|j%%i|i<2)a[j]else ""),
             if(j%%N)"" else"\n") #Newline at end of row
      cat("\n") #Newline between turns
      i=(grep("\\d",a[-(1:i)],v=T)[1]:1)[1] #Select next prime as next i
   }
}

```

Usage:

```
> f(2)
  2
3 4

  2
3

> f(3)
  2 3
4 5 6
7 8 9

  2 3
  5
7   9

  2 3
  5
7

> f(9)
   2  3  4  5  6  7  8  9
10 11 12 13 14 15 16 17 18
19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54
55 56 57 58 59 60 61 62 63
64 65 66 67 68 69 70 71 72
73 74 75 76 77 78 79 80 81

   2  3     5     7     9
   11    13    15    17
19    21    23    25    27
   29    31    33    35
37    39    41    43    45
   47    49    51    53
55    57    59    61    63
   65    67    69    71
73    75    77    79    81

   2  3     5     7
   11    13          17
19          23    25
   29    31          35
37          41    43
   47    49          53
55          59    61
   65    67          71
73          77    79

   2  3     5     7
   11    13          17
19          23
   29    31
37          41    43
   47    49          53
            59    61
         67          71
73          77    79

   2  3     5     7
   11    13          17
19          23
   29    31
37          41    43
   47                53
            59    61
         67          71
73                79

> f(12)
    2   3   4   5   6   7   8   9   10  11  12
13  14  15  16  17  18  19  20  21  22  23  24
25  26  27  28  29  30  31  32  33  34  35  36
37  38  39  40  41  42  43  44  45  46  47  48
49  50  51  52  53  54  55  56  57  58  59  60
61  62  63  64  65  66  67  68  69  70  71  72
73  74  75  76  77  78  79  80  81  82  83  84
85  86  87  88  89  90  91  92  93  94  95  96
97  98  99  100 101 102 103 104 105 106 107 108
109 110 111 112 113 114 115 116 117 118 119 120
121 122 123 124 125 126 127 128 129 130 131 132
133 134 135 136 137 138 139 140 141 142 143 144

    2   3       5       7       9       11
13      15      17      19      21      23
25      27      29      31      33      35
37      39      41      43      45      47
49      51      53      55      57      59
61      63      65      67      69      71
73      75      77      79      81      83
85      87      89      91      93      95
97      99      101     103     105     107
109     111     113     115     117     119
121     123     125     127     129     131
133     135     137     139     141     143

    2   3       5       7               11
13              17      19              23
25              29      31              35
37              41      43              47
49              53      55              59
61              65      67              71
73              77      79              83
85              89      91              95
97              101     103             107
109             113     115             119
121             125     127             131
133             137     139             143

    2   3       5       7               11
13              17      19              23
                29      31
37              41      43              47
49              53                      59
61                      67              71
73              77      79              83
                89      91
97              101     103             107
109             113                     119
121                     127             131
133             137     139             143

    2   3       5       7               11
13              17      19              23
                29      31
37              41      43              47
                53                      59
61                      67              71
73                      79              83
                89
97              101     103             107
109             113
121                     127             131
                137     139             143

    2   3       5       7               11
13              17      19              23
                29      31
37              41      43              47
                53                      59
61                      67              71
73                      79              83
                89
97              101     103             107
109             113
                        127             131
                137     139

```
> 4 votes

# Answer
# Groovy, ~~201~~ ~~195~~ 191 Bytes

```
{n->a=(1..n*n).toArray();y={a.collect{(it?"$it":"").padRight((""+n*n).size())}.collate(n).each{println it.join(" ")}};a[0]=0;y(a);(2..n).each{b->(b+1..n*n).each{if(it%b==0){a[it-1]=0}};y(a)}}

```

This is an absolute cluster... The left-align murdered my byte count. But hey, it works. Here's the output for 4:

```
   2  3  4
5  6  7  8
9  10 11 12
13 14 15 16

   2  3
5     7
9     11
13    15

   2  3
5     7
      11
13

   2  3
5     7
      11
13

```

# Ungolfed:

```
{
    n->
    a = (1..n*n).toArray();                           // Create initial array.
    y = {                                             // Createa  printing utility closure.
        a.collect {                                   // Create an array collection of...
            (it ? "$it":"").padRight((""+n*n).size()) // If 0, store "", else store number & right pad it.
        }.collate(n).each{                            // Collate by n (break into nxn grid).
            println it.join(" ")                      // print each separated by spaces.
        }
    };
    a[0]=0;                                           // Remove first element.
    y(a);                                             // Print initial status.
    (2..n).each{                                      // From 2 to n...
        b->
        (b+1..n*n).each{                              // From current number + 1 to end of grid...
            if(it%b==0){                              // If current grid position is divisible...
                a[it-1]=0                             // Replace with 0.
            }
        }
        y(a)                                          // Print it.
    }
}

```
> 3 votes

# Answer
# Python 2, ~~199 202~~ 201 bytes

+3 bytes (I wasn't stopping early)
-1 byte thanks to @Oliver (missed a space)

```
def f(n,p={()}):
 m=n*n;g=['']+[[i,''][any(i>n and i%n<1for n in p)]for i in range(2,m+1)];x=min(set(g)-p);i=0
 while i<m+n:print' '.join('%%%ds'%-len(`m`)%v for v in g[i:i+n]);i+=n
 if x<=n:f(n,p|{x})

```

**repl.it**
> 3 votes

# Answer
# Perl, ~~115~~ ~~114~~ ~~113~~ 112 bytes

Includes +1 for `-a`

Run with input number on STDIN:

```
perl -M5.010 sieving.pl <<< 7

```

`sieving.pl`:

```
#!/usr/bin/perl -a
$_*=$_;$a.="$_"x$|++|$"x"@+".($_%"@F"?$":$/)for/\d+/..$_;*_=a;s^^$$_++||say;$.++;s//$&%$.|$&==$.?$&:$&&$_/eg^eg

```

Needs a recent enough perl so that `-a` implies `-n`. If your perl is too old add a `-n` option.

Prints a trailing newline which is allowed.
> 3 votes

# Answer
## JavaScript (ES6), ~~190~~ 189 bytes

Directly prints to the console.

```
f=(w,k=1,a=[...Array(w*w)].map((_,n)=>n&&n+1))=>k++<=w&&(k==2|a[k-2]&&console.log(a.map((n,x)=>`${n||''}    `.slice(0,`_${w*w}`.length)+(++x%w?'':`
`)).join``),f(w,k,a.map(n=>n==k|n%k&&n)))

```

### Demo

```
f=(w,k=1,a=[...Array(w*w)].map((_,n)=>n&&n+1))=>k++<=w&&(k==2|a[k-2]&&console.log(a.map((n,x)=>`${n||''}    `.slice(0,`_${w*w}`.length)+(++x%w?'':`
`)).join``),f(w,k,a.map(n=>n==k|n%k&&n)))

f(5)
```
> 2 votes

# Answer
## Batch, 464 bytes

```
@echo off
set/an=%1,s=n*n,t=s,c=1
set p=
:l
set/ac+=1,t/=10
set p= %p%
if %t% gtr 0 goto l
for /l %%i in (1,1,%1)do call:i %%i
exit/b
:i
set l=
set/af=0
call:f %1 %1
if %f%==0 for /l %%j in (1,1,%s%)do call:j %1 %%j
exit/b
:j
set/am=%2,f=!(m-1),g=%2%%n
call:f %1 %2
if %f% gtr 0 set m=
set m=%m% %p%
call set l=%%l%%%%m:~0,%c%%%
if %g%==0 echo(%l%&set l=
if %2==%s% echo(
exit/b
:f
for /l %%l in (2,1,%1)do if %%l neq %2 set/af+=!(%2%%%%l)

```

This was somewhat laborious. Explanation: Starts by squaring `n` so that it can calculate the desired column width `c`, and the appropriate amount of padding `p`, using the loop `:l`. The outer loop from `1` to `n` then runs once for each grid, calling the subroutine `:i`. First the value is checked to see whether it is 1 or prime; if not then that grid is skipped. The inner loop from `1` to `n*n` then handles the rows and columns of the grid, calling the subroutine `:j`. Each value is checked to see whether it is one of the prime numbers found so far, or if none of the prime numbers found so far divide it. If so then the value is concatenated to the output buffer, which is then padded to the desired column width. The buffer is printed and cleared every `n` lines, and an extra blank line is added at the end of the grid. The `:f` label denotes the factor-checking subroutine; f(x,y) adds 1 to `f` for each integer between 2 and `x` that divides `y`, excluding `y` itself.
> 2 votes

# Answer
# J, 125 bytes

```
p=:3 :'}."1,./('' '',.>)"1|:(-%:#y)]\((a:"_)`(<@":)@.*)"+y'
3 :'p@>~.|.(]*](*@|~+.=)({[:I.*){])&.>/\.(<"+i.-y),<]`>:@.*i.*:y'

```

This is explicit, not tacit J, but there should be a way to golf it tacitly.

## Usage

```
   p =: 3 :'}."1,./('' '',.>)"1|:(-%:#y)]\((a:"_)`(<@":)@.*)"+y'
   f =: 3 :'p@>~.|.(]*](*@|~+.=)({[:I.*){])&.>/\.(<"+i.-y),<]`>:@.*i.*:y'
   f 2
  2
3 4

  2
3
   f 3
  2 3
4 5 6
7 8 9

  2 3
  5
7   9

  2 3
  5
7
   f 4
   2  3  4
5  6  7  8
9  10 11 12
13 14 15 16

   2  3
5     7
9     11
13    15

   2  3
5     7
      11
13
   f 5
   2  3  4  5
6  7  8  9  10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25

   2  3     5
   7     9
11    13    15
   17    19
21    23    25

   2  3     5
   7
11    13
   17    19
      23    25

   2  3     5
   7
11    13
   17    19
      23

```
> 1 votes

# Answer
# Mathematica, 133 bytes

```
Grid[#,Alignment->Left]~Print~"
"&/@FoldList[#/.(##|1&@@(2~r~i#2)->Null)&,(r=Range)[i=#^2]~Partition~#/.Rule[1,],Prime@r@PrimePi@#];&

```
> 1 votes

# Answer
# PHP, ~~155~~ ~~150~~ ~~147~~ ~~145~~ ~~142~~ 140 bytes

```
for(;$k++<$n=$argv[1];)if($k<2||$a[$k]){for($i=0;$i++<$n*$n;)echo$a[$i]=$k>1?$i>$k&$i%$k<1?"":$a[$i]:($i<2?"":$i),"\t\n"[$i%$n<1];echo"\n";}

```

**breakdown**

```
for(;$k++<$n=$argv[1];)
    if($k<2||$a[$k])    // if first iteration or number unprinted ...
{
    for($i=0;$i++<$n*$n;)
        echo
            $a[$i]=$k>1
                ?$i>$k&$i%$k<1
                    ?""         // sieve
                    :$a[$i]     // or copy value
                :($i<2?"":$i)   // first iteration: init grid
            ,
            // append tab, linebreak every $n columns
            "\t\n"[$i%$n<1]
        ;
    // blank line after each iteration
    echo"\n";
}

```
> 1 votes

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