title: Evolution of OEIS

text:
# Question
Title: Evolution of OEIS
In this challenge, the goal is to recreate the On-Line Encyclopedia of Integer Sequences one sequence at a time. Similar to the Evolution of Hello World, each answer depends on a previous answer.

Over time, this challenge will create a "family tree" of the OEIS sequences. It is simple to add on to this tree.

1. Find a previous answer, which can be at any depth N of the tree.
2. Determine the first N numbers generated by that answer's sequence.
3. Find a sequence in OEIS which starts with those same numbers and which hasn't been used before.
4. Write a program to generate this new sequence you just found.
5. Submit your answer as depth N+1

Since the level of your answer influences scoring, you should always add your answer onto the tree at the deepest level possible. If you cannot fit your answer anywhere on the tree, you can start a new branch of the tree and put your answer as depth 1.

## Answer Requirements

There are a few ways to output a sequence.

The first option is to write a program or function that inputs a number (from STDIN or as an argument) and returns the Nth number in your chosen sequence. You can assume that the sequence will be defined for N and that N and S\_N are "reasonably sized" (so it won't cause overflows). You can also use any reasonable indexing, such as 0 indexing, 1 indexing, or the indexing listed under "offset" on the sequence's OEIS page, that doesn't matter. The term produced by the first index must match the first term of the OEIS entry.

The second option is to write a program or function that inputs a number and returns the first N terms of the sequence. The first terms of the output must be the first terms of the OEIS entry (you can't leave off the first few terms). Consecutive terms must be delimited by arbitrary strings of non-digit characters, so `0,1 1.2/3,5;8,11` works but `011235811` does not count.

The third option is to create a program that outputs a continuous stream of numbers. Similarly to the second option, there must be delimiters between consecutive terms.

Your answer **should contain a header** like this to aid Stack Snippet parsing:

```
 # [language], [number] bytes, depth [number], A[new sequence] from A[old sequence]

```

Your answer should contain the code to generate the sequence, along with the first few terms that any descendants will need to contain. These few terms should be **preceded by the exact word `terms:`** so that the controller can use them as part of the tree diagram. It is also recommended to write a description of the sequence you chose.

If your post is a depth 1 answer and thus has no ancestor, you should simply omit the `from A[number]` in your header.

Here is an example answer:

```
# Perl, 26 bytes, depth 3, A026305 from A084912

    various code here
    and here

The next answer should match the following terms:

    1, 4, 20

This sequence is .... and does ....

```

## Chaining Requirements

In order to make this challenge more fair, there are restrictions on which answers you can chain yours to. These rules are mostly to prevent a single person from creating a whole branch of the tree by themselves or owning a lot of "root" nodes.

* You cannot chain to yourself.
* You cannot directly chain two of your answers to the same ancestor.
* You cannot make more than one "Level 1" answer.

Also, if the ancestor was of depth N, your post must have depth N+1, even if more than the required number of terms agree.

## Scoring

Your score as a user is the **sum** of the scores of all of your answers. The score of a single answer is determined by the following formula:

```
Answer Score = Sqrt(Depth) * 1024 / (Length + 256)

```

This scoring system should encourage users to submit a large number of deeper answers. Shorter answers are preferred over longer answers, but depth has a much larger influence.

**Below is a stack snippet that generates a leaderboard as well as a tree diagram of all of the answers.** I would like to thank Martin Büttner and d3noob as the sources for a lot of this code. You should click "Full screen" to see the complete results.

```
function answersUrl(t){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+t+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(t){answers.push.apply(answers,t.items),t.has_more?getAnswers():process()}})}function shouldHaveHeading(t){var e=!1,r=t.body_markdown.split("\n");try{e|=/^#/.test(t.body_markdown),e|=["-","="].indexOf(r[1][0])>-1,e&=LANGUAGE_REG.test(t.body_markdown)}catch(a){}return e}function shouldHaveScore(t){var e=!1;try{e|=SIZE_REG.test(t.body_markdown.split("\n")[0])}catch(r){}return e}function getAuthorName(t){return t.owner.display_name}function decodeEntities(t){return $("<textarea>").html(t).text()}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.reverse();var t={},e=[],r=1,a=null,n=1,s=[];answers.forEach(function(t){var r=t.body_markdown.split("\n")[0],a=getAuthorName(t),n=r.match(SEQUENCE_REG)[0];n=n.trim();var o="from A000000";PARENT_REG.test(r)&&(o=r.match(PARENT_REG)[0]),o=o.substring(5).trim(),"A000000"==o&&(o="OEIS");var i="";SEQDATA_REG.test(t.body_markdown)&&(i=t.body_markdown.match(SEQDATA_REG)[1]);for(var u=!0,c=0;c<e.length;++c)u=u&&!(e[c]===n);for(var l=!0,c=0;c<e.length;++c)l=!(!l||e[c]===n||e[c]===n+a||e[c]===o+a);e.push(n),e.push(n+a),e.push(o+a),u&&data.push({name:n,parent:o,term:i+" : ",author:decodeEntities(a),URL:t.share_link}),l&&s.push(t)}),answers.sort(function(t,e){var r=t.body_markdown.split("\n")[0].match(SEQUENCE_REG),a=e.body_markdown.split("\n")[0].match(SEQUENCE_REG);return a>r?-1:r>a?1:void 0}),answers.forEach(function(e){var o=e.body_markdown.split("\n")[0],i=(o.match(NUMBER_REG)[0],(o.match(SIZE_REG)||[0])[0]),u=parseInt((o.match(DEPTH_REG)||[0])[0]).toString(),c=o.match(SEQUENCE_REG)[0],l="from A000000";PARENT_REG.test(o)&&(l=o.match(PARENT_REG)[0]),l=l.substring(5);var d=o.match(LANGUAGE_REG)[1];d.indexOf("]")>0&&(d=d.substring(1,d.indexOf("]")));for(var p=getAuthorName(e),E=!1,h=0;h<s.length;++h)E=E||s[h]===e;if(E){var f=jQuery("#answer-template").html();i!=a&&(n=r),a=i,++r;var m=1024*Math.pow(parseInt(u),.5)/(parseInt(i)+256);f=f.replace("{{SEQUENCE}}",c).replace("{{SEQUENCE}}",c).replace("{{NAME}}",p).replace("{{LANGUAGE}}",d).replace("{{SIZE}}",i).replace("{{DEPTH}}",u).replace("{{LINK}}",e.share_link),f=jQuery(f),jQuery("#answers").append(f),t[p]=t[p]||{lang:d,user:p,size:"0",numanswers:"0",link:e.share_link},t[p].size=(parseFloat(t[p].size)+m).toString(),t[p].numanswers=(parseInt(t[p].numanswers)+1).toString()}});var o=[];for(var i in t)t.hasOwnProperty(i)&&o.push(t[i]);o.sort(function(t,e){return parseFloat(t.size)>parseFloat(e.size)?-1:parseFloat(t.size)<parseFloat(e.size)?1:0});for(var u=0;u<o.length;++u){var c=jQuery("#language-template").html(),i=o[u];c=c.replace("{{RANK}}",u+1+".").replace("{{NAME}}",i.user).replace("{{NUMANSWERS}}",i.numanswers).replace("{{SIZE}}",i.size),c=jQuery(c),jQuery("#languages").append(c)}createTree()}function createTree(){function t(){var t=i.nodes(root).reverse(),e=i.links(t);t.forEach(function(t){t.y=180*t.depth});var r=c.selectAll("g.node").data(t,function(t){return t.id||(t.id=++o)}),a=r.enter().append("g").attr("class","node").attr("transform",function(t){return"translate("+t.y+","+t.x+")"});a.append("a").attr("xlink:href",function(t){return t.URL}).append("circle").attr("r",10).style("fill","#fff"),a.append("text").attr("x",function(){return 0}).attr("y",function(){return 20}).attr("dy",".35em").attr("text-anchor",function(){return"middle"}).text(function(t){return t.term+t.name}).style("fill-opacity",1),a.append("text").attr("x",function(){return 0}).attr("y",function(){return 35}).attr("dy",".35em").attr("text-anchor",function(){return"middle"}).text(function(t){return t.author}).style("fill-opacity",1);var n=c.selectAll("path.link").data(e,function(t){return t.target.id});n.enter().insert("path","g").attr("class","link").attr("d",u)}var e=data.reduce(function(t,e){return t[e.name]=e,t},{}),r=[];data.forEach(function(t){var a=e[t.parent];a?(a.children||(a.children=[])).push(t):r.push(t)});var a={top:20,right:120,bottom:20,left:120},n=3203-a.right-a.left,s=4003-a.top-a.bottom,o=0,i=d3.layout.tree().size([s,n]),u=d3.svg.diagonal().projection(function(t){return[t.y,t.x]}),c=d3.select("body").append("svg").attr("width",n+a.right+a.left).attr("height",s+a.top+a.bottom).append("g").attr("transform","translate("+a.left+","+a.top+")");root=r[0],t(root)}var QUESTION_ID=49223,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",data=[{name:"OEIS",parent:"null",term:"",author:"",URL:"https://oeis.org/"}],answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*,)/,DEPTH_REG=/\d+, A/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/,SEQUENCE_REG=/A\d+/,PARENT_REG=/from\s*A\d+/,SEQDATA_REG=/terms:\s*(?:(?:-)?\d+,\s*)*((?:-)?\d+)/;
```

```
body{text-align: left !important}#answer-list{padding: 10px; width: 550px; float: left;}#language-list{padding: 10px; width: 290px; float: left;}table thead{font-weight: bold;}table td{padding: 5px;}.node circle{fill: #fff; stroke: steelblue; stroke-width: 3px;}.node text{font: 12px sans-serif;}.link{fill: none; stroke: #ccc; stroke-width: 2px;}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="http://d3js.org/d3.v3.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answer-list"> <h2>Sequence List</h2> <table class="answer-list"> <thead> <tr> <td>Sequence</td><td>Author</td><td>Language</td><td>Size</td><td>Depth</td></tr></thead> <tbody id="answers"></tbody> </table></div><div id="language-list"> <h2>Leaderboard</h2> <table class="language-list"> <thead> <tr> <td>Rank</td><td>User</td><td>Answers</td><td>Score</td></tr></thead> <tbody id="languages"></tbody> </table></div><table style="display: none"> <tbody id="answer-template"> <tr> <td><a href="https://oeis.org/{{SEQUENCE}}">{{SEQUENCE}}</a></td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td>{{DEPTH}}</td><td><a href="{{LINK}}">Link</a> </td></tr></tbody></table><table style="display: none"> <tbody id="language-template"> <tr> <td>{{RANK}}</td><td>{{NAME}}</td><td>{{NUMANSWERS}}</td><td>{{SIZE}}</td></tr></tbody></table>
```

# Answer
> 22 votes
# Parenthetic, 150 bytes, depth 4, A000292 from A000290

```
((()()())(()()()())((()())((()(()())))((()(())())((()()(()))(()(()()))((()(()))(()(()()))((())()))((()(()))(()(()()))((())()())))((())()()()()()()))))

```

The next answer should match the following terms:

```
0, 1, 4, 10

```

This is the sequence of tetrahedral numbers, the 3D generalisation of triangular numbers. The formula for this is

```
T(n) = n*(n+1)*(n+2)/6

```

Parenthetic is a Lisp-like language which uses parentheses to define everything. The above is a function `()()()` which takes in `n` and outputs `T(n)`. Call like:

```
((()()()())((())()()()()()()()))

```

## Annotated

```
(
  define
  (() ()())

  f [][][]
  (() ()()())

  (
    lambda
    (() ())

    (
      n [[][]]
      (() (()()))
    )

    (
      div
      (() (())())

      (
        *
        (() ()(()))

        n
        (() (()()))

        (
          +
          (() (()))

          n
          (() (()()))

          1
          ((()) ())
        )

        (
          +
          (() (()))

          n
          (() (()()))

          2
          ((()) ()())
        )
      )

      6
      ((()) ()()()()()())
    )
  )
)

Test call:

(
  f
  (() ()()())

  6
  ((()) ()()()()()())
)

```

# Answer
> 21 votes
# Pancake Stack, 118 bytes, depth 1, A000012

```
Put this kindercarnavalsoptochtvoorbereidingswerkzaamheden pancake on top!
Show me a pancake!
Eat all of the pancakes!

```

The next answer should match the following terms:

```
1

```

This prints the smallest divisor of `n`. Tested with the Python interpreter on the esolang wiki page. The interpreter expects a `~` on the line after to denote end of program, after which comes STDIN input (which will be ignored anyway).

Relevant instructions:

```
Put this <blah> pancake on top!                # Push length of <blah>
Show me a pancake!                             # Output top of stack as char
Eat all of the pancakes!                       # Terminate the program

```

## Previous answer

```
Put this  pancake on top!
[]
Put this kindercarnavalsoptochtvoorbereidingswerkzaamheden pancake on top!
Show me a pancake!
Put this delectable pancake on top!
Show me a pancake!
If the pancake is tasty, go over to "".

```

This one prints in an infinite loop. Additional instructions:

```
[<blah>]                                       # Define the label <blah>
If the pancake is tasty, go over to "<blah>".  # If top of stack nonzero, go to label

```

There are other instructions, but even so Pancake Stack is *very* cumbersome to use normally, thanks to a lack of numeric output and access to only the top two elements of the stack.

Unfortunately, the first line of this program seems necessary to prevent a bug concerning labels in the Python interpreter.

# Answer
> 17 votes
# Python, 31 bytes, depth 4, A010060 from A000045

```
lambda n:sum(map(ord,bin(n)))%2

```

The next answer should match the following terms:

```
0, 1, 1, 0

```

This one's a favourite of mine, and it's the Thue-Morse sequence. There are at least two definitions of it:

* The parity of ones in the binary expansion of `n` (used above), and
* The sequence obtained by starting with 0, then repeatedly appending the bitwise complement of the sequence so far (i.e. `0 -> 01 -> 0110 -> 01101001 -> ...`)

One of many cool things about this sequence is if we grab a turtle and do:

```
import turtle

turtle.speed(0)
n = 12

# Calculate first 2^n of Thue-Morse
tm = map(lambda n:sum(map(ord,bin(n)))%2, range(2**n))

# Move to top left
turtle.penup()
turtle.setx(-300)
turtle.sety(300)
turtle.pendown()

# For each num, go forward a unit if 0, or turn left 120 degrees if 1
for m in tm:
    if m == 0:
        turtle.forward(1)

    elif m == 1:
        turtle.left(120)

turtle.hideturtle()
turtle.mainloop()

```

we get this:

Look familiar?

# Answer
> 15 votes
# MarioLANG, 265 bytes, depth 3, A016957 from A006370

```
                           <
         =================="
               (((+)< ))+(<
              ======" ===="
               >-))+!  >-(!
               "====#  "==#
          >-(>[!))   >[!(  !
          "====#=======#===#
;)++++++>[!))++++:
==========#=======

```

The next answer should match the following terms:

```
4, 10, 16

```

The sequence is merely the arithmetic progression `6n + 4`.

MarioLANG is an esoteric programming language based on, well, Super Mario. Calculations are done in a Brainfuck-like way — there is a tape of cells which you can increment/decrement.

The relevant BF-like commands here are:

```
+      Increment current memory cell
-      Decrement current memory cell
(      Move memory pointer left
)      Move memory pointer right
;      Numeric input
:      Numeric output
[      Skip next instruction is current cell is zero

```

So where's the Mario? Well Mario is your instruction pointer, and he starts on the left (where `;` is). Mario keeps executing instructions as long as he's on the ground `=`, and when he falls the program terminates.

The relevant instructions for this are:

```
=      Ground for Mario to stand on
<      Make Mario move leftward
>      Make Mario move rightward
!      Make Mario stop moving
#      Elevator start
"      Elevator end

```

All in all, the program does this:

```
Put input (n) in cell 0
Increment cell 1 to 6
While cell 1 is not zero...
    Decrement cell 1
    Move n from cell 0 to cells 2, 3
    Move n from cell 2 to cell 0
Increment cell 3 by 4
Output as num

```

Tested with the Ruby interpreter. Note that the language has a lot of undefined behaviour, such as what happens to instructions Mario meets as he falls, so I tried to avoid any of that.

# Answer
> 14 votes
# Brainfuck, 2 bytes, depth 2, A000030 from A001477

```
,.

```

A000030 is the sequence of the initial digits of the non-negative integers, so this simply reads the first digit character and writes it back. The next sequence should start with the terms:

```
0, 1

```

# Answer
> 9 votes
# Piet, 16 bytes, depth 3, A000035 from A000030

The next answer should match the following terms:

```
0, 1, 0

```

This is Piet, so the "bytes" are really codels. Here it is at a larger codel size:

The program simply reads in `n` and outputs `n` modulo 2.

# Answer
> 9 votes
# Marbelous, 7 bytes, depth 3, A011760 from A000027

It's been a while since this site has seen a Marbelous answer!

```
}0
<D++

```

The next answer should start with the terms:

```
1, 2, 3

```

You can try the code in es1024's Stack Snippet interpreter. In put is given via command-line argument, and you should choose "Display output as decimal numbers". Otherwise, the result will be output as a byte value, which is technically also fine.

The sequence is the sequence of "elevator buttons in U.S.A.", i.e. all positive integers except 13. Note that Marbelous is limited to 8-bit numbers, but as far as I'm aware there are no buildings with anywhere near 256 floors. :)

Marbelous is a 2D language where data flows through the code in the form of marbles (byte values) falling down the grid. `}0` gets replace with the first command-line argument. `<D` is a switch which acts as an empty cell to marbles less than 13 (the `D` is in base 36), so that inputs 1 to 12 pass through unaffected. If the marble is equal to or greater than 13, the marble is deflected to the right and passes through the `++` which increments the value by 1. In either case the marble then falls off the board, which prints its value.

# Answer
> 8 votes
# Starry, 22 bytes, depth 4, A008619 from A000142

```
      + + +*,  +   **.

```

The next answer should match the following terms:

```
1, 1, 2, 2

```

The sequence consists of the positive integers repeated twice. The program reads in a number from STDIN and calculates `1 + floor(n/2)`.

Starry is an esoteric language implemented in Ruby which was part of a book on... making esoteric languages in Ruby. Each instruction is determined by the number of spaces before one of `+*.,`'`. All other characters are ignored, so the above is equivalent to

```
      +
 + +*,
  +   *
*.

```

which looks a lot more starry! (note the trailing spaces)

The relevant commands are:

```
Spaces     Final      Instruction
------     -----      -----------
n >= 5     +          Push n-5 to stack
1          +          Duplicate top of stack
0 mod 5    *          Add
0 mod 2    ,          Input num
2          +          Swap top 2
3 mod 5    *          Divide
0 mod 2    .          Output num

```

## Previous answer, 53 bytes

```
      +` +.               + + .  + +.  + .      +* +'

```

This generates the sequence ad infinitum instead. Some additional commands are:

```
Spaces     Final      Instruction
------     -----      -----------
1 mod 2    .          Output as ASCII char
n          `          Mark a label n
n          '          Pop and if nonzero, jump back to label n

```

# Answer
> 8 votes
# Rail, 56 bytes, depth 4, A033547 from A002378

```
$'main'
 0/aima19-@
@------e<
  /()(!!)-@
@-()m5a()m3do#

```

The next answer should match the following terms:

```
0, 2, 6, 14

```

The program reads in `n` from STDIN and outputs `n*(n^2+5)/3`, which was a guess at the magic numbers for the nuclear shell model from the 1940s.

Rail is a 2D language which is themed around train tracks. The above code is golfed using `@` reflectors which reverse the direction of the train, in order to reduce the number of newlines. Here it is ungolfed:

```
$ 'main'
 \
  0
   \ /--aima19--\
    |           |
    \--e-------<
                \
                 \-(!n!)-(n)-(n)-m-5-a-(n)-m-3-d-o-#

```

Note how Rail starts at the top left and begins moving vertically down-right.

The stack manipulation commands used are:

```
0-9       Push 0-9 respectively
e         Push t (true) if EOF, else f (false)
i         Input char
o         Output
a         Add
m         Multiply
(!n!)     Store top of stack as variable n
(n)       Push variable n to stack
#         Halt program

```

The train branches at junctions `>v<^`, turning right if the top of the stack is true, otherwise left if false.

# Answer
> 7 votes
# Golfscript, 3 bytes, depth 3, A000290 from A000030

```
~2?

```

The next answer should match the following terms:

```
0, 1, 4

```

This sequence is simply the square numbers, so the program takes a number and outputs its square.

# Answer
> 7 votes
# Mathematica, 20 bytes, depth 6, A037965 from A104631

```
Binomial[2#-2,#-1]#&

```

This is an unnamed function which simply computes the definition of the sequence. The next sequence should start with the terms:

```
0, 1, 4, 18, 80, 350

```

# Answer
> 7 votes
# CJam, 34 bytes, depth 14, A157271 from A238263

```
qi_,_m*{~2@#3@#*}$<::+1f&_:+\1-,e>

```

The next answer should start with the terms:

```
1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7

```

but there aren't any left which haven't been done already.

Let `D(n)` be the set of the first `n` 3-smooth numbers: that is, integers whose prime factors are a subset of `{2, 3}`. Let `S(n)` be the largest subset of `D(n)` which doesn't itself contain any subset of the form `{x, 2x}` or `{y, 3y}`. Then A157271 is the size of `S(n)`.

# Answer
> 6 votes
# Prelude, 16 bytes, depth 1, A000211

```
3(v!  v)
4 ^+2-^

```

I thought I'd start a tree with a less obvious initial number. This is a generalised Fibonacci sequence with definition `a(0) = 4`, `a(1) = 3`, `a(n) = a(n-1) + a(n-2) - 2`. Consequently, this is mostly a simple adaptation of my Prelude Fibonacci solution. The above is a program which prints an infinity stream of the numbers. It assumes the Python interpreter which outputs numbers instead of individual characters.

The next answer should start with the terms:

```
4

```

# Answer
> 6 votes
# Clip, 0 bytes, depth 2, A000027 from A000012

Given a number `n`, prints the `nth` number in the sequence `1, 2, 3, 4...`

The next answer should start with the terms:

```
1, 2

```

# Answer
> 5 votes
# Perl, 10 bytes, depth 1, A001477

To kick things off, here is a simple sequence.

```
print$_=<>

```

This represents the non-negative numbers 0, 1, 2, 3, etc. by printing the input number. The next sequence should start with the terms:

```
0

```

# Answer
> 5 votes
# J, 4 bytes, depth 4, A001563 from A000290

```
(*!)

```

The next answer should match the following terms:

```
0, 1, 4, 18

```

This sequence is the number multiplied by its factorial. In J `(fg)x` is `f(x,g(x))` here `x*factorial(x)`.

# Answer
> 5 votes
# Mathematica, 48 bytes, depth 5, A104631 from A001563

```
SeriesCoefficient[((x^5-1)/(x-1))^#,{x,0,2#+1}]&

```

The next answer should match the following terms:

```
0, 1, 4, 18, 80

```

Barring the long function names, Mathematica absolutely rocks at this challenge. This one is simply the coefficient of `x^(2n+1)` in the expansion of

```
(1 + x + x^2 + x^3 + x^4)^n

```

# Answer
> 5 votes
# Element, 13 bytes, depth 3, A000045 from A000030

```
1_'0[3:~2@+]`

```

A000045 represents the Fibonacci numbers. Each term in the sequence is the sum of the previous two terms. It is notable because the ratio between consecutive terms approaches the golden ratio, also known as phi. Somewhat interestingly, the OEIS entry starts with `0, 1` instead of the common `1, 1`. The next answer should match the terms:

```
0, 1, 1

```

# Answer
> 5 votes
# Prelude, 1 byte, depth 2, A000004 from A001477

```
!

```

The next answer should match the following terms:

```
0, 0

```

This program takes in `n` as input, completely ignores it, and outputs the zero constant. It requires `NUMERIC_OUTPUT = True` in the Python interpreter.

The nice thing about Prelude is that it has an infinite supply of zeroes at the bottom of the stack, so all that was needed was a single output command.

# Answer
> 4 votes
# GolfScript, 9 bytes, depth 4, A051682 from A002275

```
~.9*7-*2/

```

The next answer should match the following terms:

```
0, 1, 11, 30

```

This simply uses the formula for hendecagonal numbers found on the OEIS page.

# Answer
> 4 votes
# Deadfish, 4 bytes, depth 2, A005563 from A001477

```
isdo

```

This sequence is defined as `(n+1)^2-1`, which is exactly what this program does. Since Deadfish has no input, it assumes the accumulator is at the desired input number. The next answer should start with the terms:

```
0, 3

```

# Answer
> 4 votes
# APL, 13 bytes, depth 4, A000108 from A000142

```
{(⍵!2×⍵)÷⍵+1}

```

Catalan numbers! Indexing starts at zero for these. The next answer should start with the terms:

```
1, 1, 2, 5

```

# Answer
> 4 votes
# GolfScript, 31 bytes, depth 11, A029030 from A242681

```
~][11.(2]{:C;{{.C-.)0>}do;}%}/,

```

The next answer should match the following terms:

```
1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 7

```

but it won't be able to: this is a leaf of the tree. This sequence is the number of ways of giving change with coins of value 1, 2, 10, and 11.

# Answer
> 4 votes
# Retina, 1 byte, depth 3, A055642 from A001333

```
.

```

The next answer should start with the terms:

```
1, 1, 1

```

I think this is the first time I used Retina in something else than Replace mode. If only a single file is given without any options, Retina assumes Match mode, which by default counts the number of matches of the given regex in the input. This regex is `.` and matches any character. Therefore, this program returns the number of digits of the input which is A055642.

# Answer
> 3 votes
# TI-BASIC, 10 bytes, depth 5, A181857 from A001563

```
Input X
lcm(X²,X!

```

A181857 represents the least common multiple of the squares and factorials. The code length for TI-BASIC is always confusing, because it uses tokens, so most tokens are fewer bytes than their Unicode byte count. The next sequence should start with the terms:

```
0, 1, 4, 18, 48

```

# Answer
> 3 votes
# Clip, 24 bytes, depth 4, A049666 from A002275

```
/F*5nx5[Fx?<x3O]+F(xF((x

```

The next answer should match the following terms:

```
0, 1, 11, 122

```

The sequence is just `Fibonacci(5n)/5`. See the examples page for an explanation.

# Answer
> 3 votes
# Clip, 37 bytes, depth 5, A227327 from A000292

```
[t/m++#t4*2#t3*8#t2?%t2+*2t9]*8t]48]n

```

Possible ways to choose two points on a triangular grid of side n, excluding rotations and reflections. The example given is: for n = 3, there are 4 ways:

```
  X        X        X        .
 X .      . .      . .      X X
. . .    X . .    . X .    . . .

```

The next sequence must start with the following terms:

```
0, 1, 4, 10, 22

```

# Answer
> 3 votes
# APL, 24 bytes, depth 6, A025581 from A182712

```
{¯1-⍵-2!1+⌊.5+.5*⍨2×1+⍵}

```

The sequence A025581 is the sequence of... Im not quite sure to be honest. It scares me.

Indexing starts at 0 and the function just calculates the sequence by definition.

The next sequence should start with the terms:

```
0, 1, 0, 2, 1, 0

```

# Answer
> 3 votes
# \>\<\>, 25 bytes, depth 2, A001333 from A002522

```
301-v >rn;
*2@:<r^!?:-1r+

```

These are the numerators of the continued fraction convergents to sqrt(2). The code needs the user to prepopulate the stack with the index of the convergent that should be returned. Indexing starts at 1. The next answer should start with the terms:

```
1, 1

```

# Answer
> 3 votes
# J, 44 bytes, depth 10, A242681 from A026233

```
f=.(,(<:*+)"0/~~.50,25,(,+:,3*])1+i.20)+/@:=]

```

The next answer should start with the terms:

```
1, 1, 2, 2, 3, 3, 4, 4, 5, 5

```

Something closer to everyday life: "the number of ways that a score of `n` can be obtained using two darts on a standard dartboard". Only the unordered score-pair matters. Starting offset is two as in the OEIS page. Usage:

```
f 2 => 1
f 72 => 12

```

# Answer
> 3 votes
# R, 20 bytes, depth 11, A194964 from A242681

```
1+floor(scan()/5^.5)

```

The next answer should match the following terms:

```
1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 5

```

The sequence A194964 gives for each n the result of `1+[n/sqrt(5)]` where `[` means "floor". The R function takes input as stdin.

# Answer
> 3 votes
# 3var, 15 bytes, depth 5, A004523 from A002620

```
aaama{pOpOipOi}

```

The next answer should match the following terms:

```
0, 0, 1, 2, 2

```

This simply prints a stream of two even numbers followed by an odd, i.e. `0, 0, 1, 2, 2, 3, 4, 4, 5, ...`

3var is essentially a much better version of Deadfish that has three variables `A`, `B`, `R`. Here we only use the first two.

```
i        Increment A
p        Print A as num
a        Increment B
m        Square B
O        Print B as ASCII
{}       Infinite loop

```

If it wasn't for the fact that we had to separate the numbers in the output, `{ppipi}` would have been a lot shorter.

# Answer
> 3 votes
# Piet, 56 bytes, depth 4, A000124 from A000079

with size 10 codels for legibility. The next sequence should start with the terms:

```
1, 2, 4, 7

```

This sequence is the "maximal number of pieces formed when slicing a pancake with n cuts" (i. e. sum(1:n) + 1 ). The sequence was so simple so i thought i could increase the difficulty a little by doing it in Piet. I tested it on PietDev.

It pushes 1 on the stack `1`, then the number provided with stdin `1 n`, duplicate the latter `1 n n` \[here the loop begins = bright green codel\], pushes 1 `1 n n 1`, substracts it `1 n n-1`, duplicates the result twice `1 n n-1 n-1 n-1` (the deeper one will be then one we ll add to `n`, the second one the one we ll compare to zero and the third one the loop counter), pushes 4 and then 1 `1 n n-1 n-1 n-1 4 1` uses the last two to roll the "loop counter" to the bottom `1 n-1 n n-1 n-1`, check if `n-1` is equal to 0: if no the stack becomes `1 n-1 n n-1 0`, which we negates `1 n-1 n n-1 1` and uses the `1` to change the pointer direction `1 n-1 n n-1`, adds n-1 to n `1 n-1 (n+n-1)` which we roll to the bottom with a 2 and 1 that we just pushed on the stack thus leaving the stack in this state `1 (n+n-1) n-1` when it starts the loop over. When the counter indeed reaches 0, it exits the loop with a stack looking like this `1 0 Sum(1:n) 0`, it then pops the first number, adds the rest and outputs as a numeric.

# Answer
> 3 votes
# Python, 87 bytes, depth 1, A000040

```
def b(n):
 p,t=[],2
 while n>0:
  if all(t%a for a in p):
   p+=[t];n-=1;yield t
  t+=1

```

The prime numbers. The next answer should match the following terms:

```
2

```

# Answer
> 2 votes
# Pyth, 6 bytes, depth 3, A002275 from A000030

```
&Q*Q\1

```

The next answer should match the following terms:

```
0, 1, 11

```

A002275 is the sequence of repunits. The `n`-th sequence number is `(10^n - 1)/9`, which consists of `n` 1s.

# Answer
> 2 votes
# Python, 41 bytes, depth 6, A090017 from A104631

```
a=lambda n:n if n<2else 4*a(n-1)+2*a(n-2)

```

This is the lucas sequence U(-4, 2) The next sequence should start with the terms:

```
0, 1, 4, 18, 80, 356

```

# Answer
> 2 votes
# Mathematica, 25 bytes, depth 6, A181860 from A181857

```
LCM[#^2,#!/⌊#/2⌋!^2]&

```

This is an unnamed function which simply computes the definition of the sequence. The next sequence should start with the terms:

```
0, 1, 4, 18, 48, 150

```

# Answer
> 2 votes
# Clip, 14 bytes, depth 4, A007814 from A000035

```
([tmlt)%t1]bWn

```

The count of the terminal zeroes in the binary from of a number. The next answer should start with the terms:

```
0, 1, 0, 2

```

# Answer
> 2 votes
# Mathematica, 29 bytes, depth 5, A129953 from A000292

```
a@0=0;a@1=1;a@n_=2^(n-2)(n+2)

```

The next sequence must start with the following terms:

```
0, 1, 4, 10, 24

```

# Answer
> 2 votes
# CJam, 20 bytes, depth 7, A218254 from A025581

```
0p1{_{_p_2b:+-}hp)}h

```

The next answer should start with the terms:

```
0, 1, 0, 2, 1, 0, 3

```

My first CJam program! This is such a far superior language to GolfScript. It is like somebody re-did Golfscript, but properly.

A218254 itself is a cute sequence where you iterate the non-negative integers, and for each one, you print it out, then subtract the popcount (number of 1s in the binary expansion) of it, and iterate 'till you reach zero.

The program loops forever so you will have to run it locally.

# Answer
> 2 votes
# CJam, 27 bytes, depth 8, A022336 from A218254

```
ri_),_ff{5\#Z2$#*[\]}:+$=W=

```

The next answer should start with the terms:

```
0, 1, 0, 2, 1, 0, 3, 2

```

Exponent of 3 of every integer in the form of 3<sup>j</sup>5<sup>k</sup>.

# Answer
> 2 votes
# Nagato Yuki, 225 bytes, depth 4, A063524 from A000035

```
…………………「・………。………………… …………。」………。・………………。・………………。…… ………………。・「・………………。… ………………。」

```

The next answer should start with the terms:

```
0, 1, 0, 0

```

Characteristic function of n=1, separated by slashes.

I don't know who invented the Nagato Yuki programming language. But I found an interpreter. I don't know Scala and don't know what's the correct way to run the interpreter. So I just replaced the sample Hello World program with my code, and ran `sbt` at the root directory, `run` and selected `NagatoApp`.

The interpreter seemed to only read one character per line. So I chose the format without input.

Brainfuck translation:

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

```

# Answer
> 2 votes
# Pyth, 4 bytes, depth 5, A070939 from A008619

```
l.BQ

```

A070939 is the length of `n` in binary. The approximation Python translation is

```
print(len(bin(eval(input()))-2))

```

Try it online here. The next answer should start with the terms:

```
1,1,2,2,3

```

# Answer
> 2 votes
# J, 4 bytes, depth 2, A033999 from A000012

```
_1&^

```

The next answer should start with the terms:

```
1, -1

```

No negative numbers yet?

It is a function that may *return* the number -1, which is displayed as \_1.

# Answer
> 2 votes
# Racket, 86 bytes, depth 8, A084054 from A000006

```
#lang racket
(lambda(n)(modulo(string->number(substring(number->string(* 5 n))0 1))5))

```

The next answer should match the following terms:

```
1, 1, 2, 2, 3, 3, 4, 4

```

The sequence is "5n digit-reversed mod 5", which is another way of saying "first digit of 5n, mod 5".

I'm no expert at Racket/Scheme but it appears that `first` only works on lists, hence the use of `substring`.

Test like:

```
#lang racket
(map
    (lambda(n)(modulo(string->number(substring(number->string(* 5 n))0 1))5))
    (range 0 100)
)

```

# Answer
> 2 votes
# CJam, 14 bytes, depth 9, A026233 from A084054

```
ri,:):mp)f=:+)

```

The next answer should start with the terms:

```
1, 1, 2, 2, 3, 3, 4, 4, 5

```

Return k where the input (\>=1) is the kth prime or non-prime.

# Answer
> 2 votes
# CJam, 14 bytes, depth 11, A025766 from A242681

```
ri),A~%2f/:):+

```

The next answer should start with the terms:

```
1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6

```

The sequence which has the generating function 1/((1-x)(1-x^2)(1-x^11)).

I'm not sure why it is useful.

# Answer
> 2 votes
# GolfScript, 12 bytes, depth 12, A135020 from A025766

```
~).2/`-1@?%~

```

The next answer should start with the terms:

```
1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6

```

Each natural number is followed by its reversal. Indexed from 1. Gets interesting at A(20) = 1.

# Answer
> 2 votes
# CJam, 17 bytes, depth 5, A000010 from A008619

```
ri:N,{mfNmf&!},,(

```

Euler's totient function - count of numbers \<= N and relatively prime to N.

The next sequence must start with the terms:

```
1, 1, 2, 2, 4

```

# Answer
> 2 votes
# CJam, 70 bytes, depth 6, A134452 from A179081

```
{_3%2<{_{_3%\3/T+}{;L}?}{)3/T-1\+}?}:T;{_{_1>{:+TR}{0=}?}{;0}?}:R;riTR

```

The next answer should start with the terms:

```
0, 1, 0, 1, 0, -1

```

This is the digital root of `n` in balanced ternary.

Balanced ternary is a ternary base system where the digits can be `-1`, `0`, or `1`. E.g. 4 is `++ = 3 + 1`, 5 is `+-- = 9 - 3 - 1`, 6 is `+-0 = 9 - 3 + 0`.

The digital root is the digit you get when you keep adding the digits together. e.g. in base 10:

```
9685 --> 9 + 6 + 8 + 5 = 28
28   --> 2 + 8 = 10
10   --> 1 + 0 = 1
1

```

Thus the digital root in base 10 for `9685` is `1`.

`T` recursively converts a number to balanced ternary. `R` recursively computes the digital root.

See history for the original Python version. This is a straightforward translation of that. CJam golf tips are welcome! This one has that look like it could be golfed but I am not sure..

# Answer
> 2 votes
# Befunge, 7 bytes, depth 4, A002620 from A172275

```
&:*4/.@

```

The next answer should match the following terms:

```
0, 0, 1, 2

```

# Answer
> 2 votes
# A:;, 63 bytes, depth 3, A010052 from A001333

```
n:j;l:0;b:l;?:j:=:l:2;p:1;k;?:j:<:l:2;p:0;k;a:b:1;l:b;m:l:l;g:3

```

The next sequence should match the terms:

```
1, 1, 0

```

The sequence generated here returns 1 if the input is a square and 0 if not. I wanted to try this language out of curiosity. The algorithm is dead simple so I don't think I made a mistake but if anyone sees one, please tell me!

# Answer
> 2 votes
# Python, 173 bytes, depth 5, A090245 from A014137

```
from itertools import*
C=combinations
f=lambda n:max(i for i in range(3**n+1)if any(all(any(sum(x)%3for x in zip(*s))for s in C(b,3))for b in C(product(*tee([0,1,2],n)),i)))

```

Call like `f(2)`. The next answer should match the following terms:

```
1, 2, 4, 9, 20

```

This is the maximum number of cards you can have in `n`-attribute Set such that there is no set amongst the cards you chose.

For those who are unfamiliar with Set, a "set" in the game is a collection of three cards such that, for each attribute (e.g. colour, number, shape, shading) the cards are either all different or all the same. You can check out this paper which gives a very good explanation of the rules in the first two pages, as well as an example of 20 cards for the case `n = 4` (i.e. regular Set) on the third page. Then proceed to buy the cards as an excellent timekiller with your nerdy friends.

Since the algorithm is brute force, it only solves up to `n = 2` in a reasonable amount of time. Here's an ungolfed version with early exiting which manages to complete `n = 3` within a few minutes, and outputs the boards it finds as it goes:

```
from itertools import *

def f(n):
    cards = list(product([0,1,2], repeat=n))

    for board_size in range(3**n+1):
        for board in combinations(cards, board_size):
            for three_cards in combinations(board, 3):
                if any(sum(attr)%3 != 0 for attr in zip(*three_cards)):
                    continue

                else:
                    break

            else:
                print("Board size {}: {}".format(board_size, board))
                break

        else:
            return

```

For `n = 3` the final output is

```
Board size 9: ((0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 2), (1, 2, 2), (2, 1, 2))

```

which can be visualised as

The program makes use of the fact that, when representing an attribute by `0, 1, 2`, "all the same or all different" is equivalent to the sum of the three cards' attributes being divisible by 3 (`0+0+0 = 1+1+1 = 2+2+2 = 0+1+2 = 0 mod 3`).

# Answer
> 2 votes
# Mathematica, 11 bytes, depth 15, A086388 from A157271

```
Round[#/2]&

```

A086388 is just a duplicate of A008619. However, the question didn't disallow `dead` sequences, so I assume that this is valid. The next answer should start with the terms:

```
1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8

```

# Answer
> 1 votes
# Mathematica, 53 bytes, depth 5, A182712 from A007814

```
Count[Select[IntegerPartitions@#,!#~MemberQ~1&],2,2]&

```

A182712 is the set of the total number of 2's in the last section of the partitions of `n` (the ones that don't contain 1.) The next answer should start with the terms:

```
0, 1, 0, 2, 1

```

# Answer
> 1 votes
# Mathematica, 58 bytes, depth 6, A106391 from A104631

```
a=Binomial;Sum[a[#,2k]a[2(#-2k),#-2k+1],{k,0,Floor[#/2]}]&

```

Will add explanation later. The next answer should start with the terms:

```
0, 1, 4, 18, 80, 365

```

# Answer
> 1 votes
# Mathematica, 30 bytes, depth 7, A051122 from A025581

```
a=Fibonacci;a@#~BitAnd~a[#+1]&

```

A051122(n) = Fib(n) AND Fib(n + 1). The next answer should start with the terms:

```
0, 1, 0, 2, 1, 0, 8

```

# Answer
> 1 votes
# Mathematica, 8 bytes, depth 4, A003462 from A000290

```
3^#/2-2&

```

The next answer should start with the terms:

```
0, 1, 4, 13

```

# Answer
> 1 votes
# Mathematica, 4 bytes, depth 3, A000079 from A000027

```
2^#&

```

The next answer should start with the terms:

```
1, 2, 4

```

# Answer
> 1 votes
# Mathematica, 20 bytes, depth 2, A006370 from A000211

```
If[OddQ@#,3#+1,#/2]&

```

The mapping of `n` to the next term in its Collatz sequence. The next answer should start with the terms:

```
4, 1, 10

```

# Answer
> 1 votes
# J, 27 bytes, depth 4, A014137 from A000079

```
[:+/\[:(([:!2*])%!*[:!>:)i.

```

Interesting idea! These are the partial sums of the Catalan numbers:

```
   f=.[:+/\[:(([:!2*])%!*[:!>:)i.
   f 4
1 2 4 9

```

The next answer should start with the terms:

```
1, 2, 4, 9

```

# Answer
> 1 votes
# Mathematica, 15 bytes, depth 5, A018001 from A014137

```
Round[9^(#/3)]&

```

These are the powers of the cube root of 9 rounded to the nearest integer. The next answer should start with the terms:

```
1, 2, 4, 9, 19

```

# Answer
> 1 votes
# J, 13 bytes, depth 6, A018099 from A018001

Powers of the fourth root of 19 rounded down

```
[:<.(19^%4)^]

```

(OP: I'm not clear if we should provide the full series with our functions up to term N or just term N for any input N)

```
   f=.[:<.(19^%4)^]
   f i. 6
1 2 4 9 19 39

```

The next answer should start with the terms:

```
1, 2, 4, 9, 19, 39

```

# Answer
> 1 votes
# Mathematica, 16 bytes, depth 3, A065134 from A000030

```
#~Mod~PrimePi@#&

```

The remainder of `n` over the number of primes \<= `n`. The next answer should start with the terms:

```
0, 1, 0

```

# Answer
> 1 votes
# Mathematica, 46 bytes, depth 4, A001590 from A000035

```
Switch[#,0|2,0,1,1,_,#0[#-1]+#0[#-2]+#0[#-3]]&

```

"Tribonacci" numbers. The next answer should start with the terms:

```
0, 1, 0, 1

```

# Answer
> 1 votes
# J, 3 bytes, depth 3, A002378 from A005843

```
*>:

```

The next answer should start with the terms:

```
0, 2, 6

```

# Answer
> 1 votes
# CJam, 4 bytes, depth 3, A000142 from A001333

```
rim!

```

The next answer should start with the terms:

```
1, 1, 2

```

Factorial.

# Answer
> 1 votes
# CJam, 61 bytes, depth 6, A182094 from A129953

```
{[_{_),(;{1$1$-P{\_@+@@}/;}/;}{;Q}?]:$_&}:P;riP{_,\0+:e>*}%:+

```

The next sequence must start with the following terms:

```
0, 1, 4, 10, 24, 47

```

This is the sum of the area of the "bounding boxes" for all integer partitions for `n`. For example, the partitions of `4` are:

```
[1,1,1,1] = 4 * 1
[1,1,2]   = 3 * 2
[2,2]     = 2 * 2
[1,3]     = 2 * 3
[4]       = 1 * 4

```

Eventually I figured out by "bounding box", the author meant the length of the list times the max of the list.

I'm quite proud of this Python -\> CJam conversion, mostly because it works at all. It's my first fairly intricate recursive function implementation, either in CJam or Golfscript. These are the only languages where I actually have to think in terms of invariants, namely, what I expect the stack to look like at the start of each loop and function call.

Basically I define a recursive function `P(N)` which returns a list of all the unique partitions of `N`. I then sum the length times the max of each partition.

I saved 7 bytes by not appending to an array, instead setting an array marker and collecting the intermediate results all together. Here's the old version along with ungolfed explanation:

```
{_!{;[[]]}{_),(;[]\{2$1$-P{\_a@+a@+\}/;}/\;}?:$_&}:P;riP{_,\0+:e>*}%:+

```

Here is the ungolfed version with an explanation:

```
                     # pseudocode             |  stack view
                     # -----------------------+------------------------
{                    # def P(N):              |  N                   (at func start)
  _!                 #  if N==0:              |    N
  {;[[]]}            #   X = [[]]             |    X                 (return value)
  {                  #  else:                 |  N
    _),(;            #   G = range(1, N+1)    |    N (1..N)
    []\              #   X = []               |    N X (1..N)        (X is return value)
    {                #   for i in G:          |      N X i           (at loop start)
     2$1$-P          #    R = P(N-i)          |      N X i P(N-i)
     {               #    for r in R:         |        N X i r       (at loop start)
       \_a@+a        #     p = [[i]+r]        |        N X i [[i]+r]
       @+\           #     X += p             |        N X i         (X updated)
     }/;             #    endfor              |      N X
    }/\;             #   endfor               |    X
  }?                 #  endif                 |    X
  :$                 #  map(sort, X)          |    X
  _&                 #  X = X & X             |    X                 (remove duplicates)
}:P;                 # enddef                 |
                     #
riP                  # Y = P(input())
{                    # Y = [
 _,\0+:e>*           #   len(r)*max(r)
}%                   #   for r in Y]
:+                   # print sum(Y)

```

Some questions: before I had `ri<define P>;P`. Is there any way to execute a block in CJam without having to pop it and push it back? I could do `1*` but that's the same number of characters as `;P`.

# Answer
> 1 votes
# CJam, 8 bytes, depth 6, A017980 from A070939

```
2rd3/#mo

```

The next answer should start with the terms:

```
1, 1, 2, 2, 3, 3

```

2^(n/3) rounded.

# Answer
> 1 votes
# PARI/GP, 20 bytes, depth 7, A000006 from A017980

```
n->sqrtint(prime(n))

```

The integer part of the square root of the n-th prime.

The next answer should match the following terms:

```
1, 1, 2, 2, 3, 3, 4

```

# Answer
> 1 votes
# Pyth, 16 bytes, depth 7, A056186 from A018099

```
thf>smc1^hd.9TQ0

```

Takes input via STDIN and outputs the Nth number.

### Explanation

```
t                   decrement 1 from
 h                   the first item of
  f            0      filter integers T by
   >          Q        N is less than
    s                   sum of
     m       T           map d over 0..T-1
      c1^hd.9             1 / d^(9/10)

```

The next answer should start with the terms:

```
1, 2, 4, 9, 19, 39, 77

```

# Answer
> 1 votes
# Mathematica, 22 bytes, depth 6, A090091 from A000110

```
FiniteGroupCount[3^#]&

```

The next answer should match the following terms:

```
1, 1, 2, 5, 15, 67

```

Number of groups of order `3^n`.

I think this is the first answer with keyword "hard" on its OEIS page. It's not easy to calculate the number of finite groups of a given order. In fact, Mathematica can only calculate the first eight terms in this sequence.

# Answer
> 1 votes
# CJam, 17 bytes, depth 5, A136859 from A000292

```
qi_1&4\#10@2/(#*i

```

The next answer should match the following terms:

```
0, 1, 4, 10, 40

```

Integers `n` such that `n` and the square of `n` use only the digits 0, 1, 4 and 6, indexed from 1.

The final `i` is needed to avoid outputting `0.4` for input `1`.

# Answer
> 1 votes
# Mathematica, 13 bytes, depth 4, A110654 from A000045

```
Ceiling[#/2]&

```

The OP said that it could be 0- or 1-indexed. The next answer should start with the terms:

```
0, 1, 1, 2

```

# Answer
> 1 votes
# GolfScript, 11 bytes, depth 8, A103181 from A037888

```
{49&}%.1`?>

```

The next answer should match the following terms:

```
0, 1, 0, 1, 0, 1, 0, 1

```

"Replace all even digits by 0 and all odd digits by 1." Then the `.1`?>` removes leading zeroes.

# Answer
> 1 votes
# PARI/GP, 25 bytes, depth 3, A027641 from A033999

```
n->numerator(bernfrac(n))

```

The next answer should start with the terms:

```
1, -1, 1

```

Numerator of Bernoulli number B<sub>n</sub>.

# Answer
> 1 votes
# Java, 30 bytes, depth 6, A016116 from A000010

```
int f(int n){return 1<<(n/2);}

```

This sequence is the powers of two, twice. This is a zero-indexed function. The next answer should match the following terms:

```
1, 1, 2, 2, 4, 4

```

# Answer
> 1 votes
# CJam, 5 bytes, depth 3, A005408 from A000244

```
ri2*)

```

The odd numbers. The next answer should start with the terms:

```
1, 3, 5

```

# Answer
> 1 votes
# Java, 29 bytes, depth 5, A000325 from A000108

```
int f(int n){return(1<<n)-n;}

```

This sequence is 2<sup>n</sup>-n for all n \>= 0. This is a zero-indexed function. The next answer should start with the following terms:

```
1, 1, 2, 5, 12

```

# Answer
> 1 votes
# Pyth, 18 bytes, depth 10, A083889 from A083912

```
lf&!%QTq\2eS`TtUhQ

```

The next sequence should match the following terms:

```
0, 1, 0, 1, 0, 1, 0, 1, 0, 1

```

Number of divisors of n with largest digit = 2 (base 10)

# Answer
> 1 votes
# Mathematica, 92 bytes, depth 11, A116372 from A083889

```
Length@Select[IntegerPartitions@#,And@@(NestWhile[Plus@@IntegerDigits@#&,#,#<9&]==2&)/@#&]&

```

The number of partitions of `n` composed of numbers with a digital root of 2. The next answer should start with the terms:

```
0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1

```

# Answer
> 1 votes
# CJam, 19 bytes, depth 12, A113217 from A116372

```
0p{"10"4*" "*p1p1}h

```

The next answer should start with the terms:

```
0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0

```

This is the parity of the decimal digital root of n. The sequence is periodic so I took the shortcut way of producing it. Output looks like:

```
0
"1 0 1 0 1 0 1 0"
1
"1 0 1 0 1 0 1 0"
1

```

etc... which from the rules I understand is ok.

# Answer
> 1 votes
# CJam, 26 bytes, depth 10, A096972 from A083912

```
ri_,(;f{_`{i48-}%0-:*+=}:+

```

The next answer should start with the terms:

```
0, 1, 0, 1, 0, 1, 0, 1, 0, 1

```

This is a cute one. You have a hash function, `h(i) = i + product of non-zero digits of i`. The `n`th number is the number of inputs into `h` which result in `n`.

Python seemed especially ill-suited for this one: having to do `lambda x,y:x*y` instead of just `x`, and a very lengthy `filter(None,map(int,``k``))` to get the non-zero digits as ints. I was right - changing the answer to CJam got it down to 26 bytes. I was a little sad I had to do `'{i48-}%` to convert a number to a list of its digits as integers, instead of just `':i`.

# Answer
> 1 votes
# Java, 41 bytes, depth 6, A028391 from A004523

```
int f(int n){return n-(int)Math.sqrt(n);}

```

This sequence is `n` minus the square root of `n` rounded to the lower integer for all n \>= 0. This is a zero-index function. The next answer should start with the following terms:

```
0, 0, 1, 2, 2, 3

```

# Answer
> 1 votes
# CJam, 21 bytes, depth 11, A216188 from A083889

```
ri_2/),f{_`$@@-`$=}:+

```

The next answer should start with the following terms:

```
0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0

```

This is a cute one. They define an "anagrammatic pair of integers" as two integers which have the same number of each of the digits, e.g. `123` is anagrammatic to `132` and `321`. `A(n)` is the number of unordered anagrammatic pairs that add up to `n`. Takes a bit to get more interesting. It's easily checked by `sorted(repr(i))==sorted(repr(n-i))` in Python or

```
`$\`$=

```

in CJam. Got it down from 76 bytes in Python to 21 bytes in CJam. CJam version takes `n` as input.

# Answer
> 1 votes
# R, 34 bytes, depth 12, A125122 from A216188

```
n=scan();diff(nchar(3^(0:n+1)))[n]

```

The following sequence should start with the terms:

```
0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1

```

It is the sequence of first differences between the number of digits of 3<sup>n</sup>.
`0:n+1` is equivalent to `1:(n+1)` because `:` has precedence over `+`. The rest is relatively self-explanatory.

# Answer
> 1 votes
# Pyth, 12 bytes, depth 2, A001358 from A000211

```
#IqlPZ2Z)~Z1

```

The next answer should match the following terms:

```
4, 6

```

This is the sequence of semiprimes, i.e. product of two (not necessarily distinct) prime factors.

```
                     Z = 0
#                    while True:
 IqlPZ2                if len(prime_factorisation(Z)) == 2:
       Z)                print(Z)
 ~Z1                   Z += 1

```

Note that this prints an infinite stream of numbers, so it's best to try this locally.

# Answer
> 1 votes
# R, 59 bytes, depth 3, A058199 from A001358

```
which(diff(rowSums(!outer(1:1e4,1:1e4,`%%`)))>=scan())[1]+1

```

The following sequence should start with the terms:

```
4, 6, 12

```

It is the sequence of integers whose number of divisors is larger than the number of divisors of the next integer by at least `n`.
The `outer(1:1e4,1:1e4,`%%`)` construct is such that the resulting matrix contains for `i` in 1 to 1e4 and `j` in 1 to 1e4 the results of `i%%j`. The sum of all zeroes in each row `i` thus gives the number of divisor for `i`. I limited to 1e4 so that it could be computed this way without overflow and fairly quickly and still work for all the values given on the A058199 page.

# Answer
> 1 votes
# Java, 27 bytes, depth 8, A057359 from A049472

```
int f(int n){return 5*n/7;}

```

This sequence is 5 times `n` divided by 7, rounded to the lower integer. This is a zero-indexed function. The next answer should start with the following terms:

```
0, 0, 1, 2, 2, 3, 4, 5

```

# Answer
> 1 votes
# CJam, 30 bytes, depth 10, A226190 from A026233

```
ri_ml\,(;f{),(;{1.\/}%:+>!}1#)

```

The next sequence should start with the terms:

```
1, 1, 2, 2, 3, 3, 4, 4, 5, 6

```

`A(n)` is the least positive integer `k` such that `1 + 1/2 + ... + 1/k >= log(n)`. My answer uses the fact that `n >= k`. This is because:

So, `k` will never have to be greater than `n`.

I think this also sheds light on what the significance of this sequence is: it's a relation between the discrete sum of `1/m` and the integral of `1/m`.

# Answer
> 1 votes
# Python, 241 bytes, depth 13, A249699 from A125122

```
from fractions import*
F=lambda n:n<2and 1or n*F(n-1)
R=range
def B(n):
 A={}
 for m in R(n):
  A[m]=Fraction(1,m+1)
  for j in R(m,0,-1):A[j-1]=j*(A[j-1]-A[j])
 return A[0]/((n-1)*F(n))
print 0,1,0
n=3
while n:print abs(B(n).numerator);n+=1

```

The next sequence should start with the terms:

```
0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0

```

Sadly this isn't on depth 14 because the next number in the sequence is 691! It quickly grows wild from there:

```
0
1
0
3617
0
43867
0
174611
0
77683
0
236364091

```

I could have gotten more points on a lower depth with fewer bytes, but this one was very weird and I wanted to try it out. The description is:

> Numerators of coefficients in series expansion of Cl\_2(x)+x\*log(x), where Cl\_2 is the Clausen function of order 2.

But I used the formula:

> Numerators of BernoulliB(n - 1)/((n - 1)\*n!), except the first 3 terms.

It actually ended up being the absolute value of the numerators.

I used the Akiyama–Tanigawa algorithm from the linked Wikipedia page to generate the Bernoulli numbers.

# Answer
> 1 votes
## CJam, 3 bytes, depth 2, A000007 from A002522

```
ri!

```

The next answer should start with the terms:

```
1, 0

```

The sequence consists of 1 followed by only 0's.

There are a lot of interpretations (see the website's page), such as the decimal expansion of 1.

# Answer
> 1 votes
# Java, 186 bytes, depth 10, A073719 from A072490

```
int f(int n){return g(1<<n,0)/g(1<<n,1);}int g(int n,int o){int k=2,c=1;while(c<n)if(h(++k)>0&&o<1||h(k)<1&&o>0)c++;return k;}int h(int n){for(int k=2;k<n;)if(n%k++<1)return 0;return 1;}

```

Long version:

```
int f(int n) {
    return g(1<<n,0) / g(1<<n,1);
}

int g(int n, int o) {
    int k=2, c=1;
    while(c<n)
        if (h(++k)>0 && o<1 || h(k)<1 && o>0)
            c++;
    return k;
}

int h(int n) {
    for (int k=2; k<n;)
        if (n % k++ < 1)
            return 0;
    return 1;
}

```

This is the sequence of the 2<sup>*n*</sup>th prime numbers divided by the 2<sup>*n*</sup>th composite numbers for all natural numbers greater than 1, rounded down. Method g finds the 2<sup>*n*</sup>th prime or composite number while method h checks if numbers are prime or composite. Due to the inefficiency of the algorithm, lag becomes apparent at *n* = 12.

This is a one-indexed function (*n* starts at 1). The next answer should start with the following terms:

```
0, 0, 1, 2, 2, 3, 4, 5, 5, 6

```

# Answer
> 1 votes
# Haskell, 32 bytes, depth 4, A015919 from A011760

```
filter(\n->mod(2^n-2)n==0)[1..]

```

The next sequence should start with the following terms:

```
1, 2, 3, 5

```

It outputs an infinite list:

```
[1,2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,...

```

It looks like it's just the sequence of 1 together with the prime numbers. In fact, the first composite number in the sequence is 341, and the first composite even number is 161038.

# Answer
> 1 votes
# Piet, 96 bytes, depth 5, A209229 from A010060

with size 10 codels for legibility. Tested on PietDev. The next sequence should start with the terms:

```
0, 1, 1, 0, 1

```

This is the characteristic function of powers of 2 (i. e. it outputs 1 if `n` is a power of 2 and 0 if not). It starts on the red codel in the first row: it takes input as stdin and pushes it to the stack `n`, it then duplicates it twice `n n n`and pushes 1 to the stack `n n n 1` \[the loop starts on the red codel at the end of the second row\] that it also duplicates twice `n n n 1 1 1` it then rolls the first one near the bottom `n 1 n n 1 1` and again `n 1 1 n n 1` then check if the first two are equal (if yes than it is a power of 2 so it change direction and outputs 1), then check if the first number of the stack (on first iteration, 1) is smaller than the second. If yes it stops and output 0 and if no it continues on the loop (at that point the stack only contains `n 1` as the first two pairs of `n 1` were used for the comparisons). It pushes 2 on the stack and multiply `n 1 2`-\>`n 2` then rolls it at the bottom, `2 n`, duplicates twice `2 n n n` rolls the bottom number on top of the stack `n n n 2` and reaches back the beginning of the loop.

# Answer
> 1 votes
# R, 79 bytes, depth 3, A000945 from A000043

```
f=function(n)if(n-1){m=prod(sapply(1:(n-1),f))+1;p=2;while(m%%p)p=p+1;p}else{2}

```

The next sequence should contain the following terms:

```
2, 3, 7

```

The sequence is such that a(n+1) is the smallest prime factor of prod(a(k) for k in 1:n)+1. `f=function(n)if(n-1){m=prod(sapply(1:(n-1),f))+1;p=(2:m)[!m%%2:m];p[1]}else{2}` would be one character shorter but can't perform `f(9)` because it can't create of vector of length 38 709 183 810 570.

# Answer
> 1 votes
# Ruby, 75 bytes, depth 2, A125710 from A000211

```
def r n;n==2??0:n%2==0??0+r(n/2):?1+r(n*3+1);end;p (r 2*gets.to_i+1).to_i 2

```

The next sequence should contain the following terms:

```
4, 80

```

This is a complicated sequence so I will just quote OEIS:

> In the "3x+1" problem, let 0 denote a halving step and 1 denote an x-\>3x+1 step. Then a(n) is obtained by writing the sequence of steps needed to reach 1 from 2n+1 and reading it as a decimal number.

My code is not short; but It was fun to make.

# Answer
> 1 votes
# Ruby, 35 bytes, depth 6, A008998 from A014137

```
a=->n{n<0?0:n>0?2*a(n-1)+a(n-3):1}

```

The next sequence should contain the following terms:

```
1, 2, 4, 9, 20, 44

```

Defined recursively as:`a(n) = 2*a(n-1) + a(n-3)`.

# Answer
> 1 votes
# Ruby, 26 bytes, depth 4, A006882 from A000142

```
a=->n{n>1?n*a.call(n-2):1}

```

The next answer should start with the terms:

```
1,1,2,3

```

The Double factorial sequence.

# Answer
> 1 votes
# Ruby, 30 bytes, depth 6, A010051 from A209229

```
->n{(2..n).one?{|x|n%x<1}?1:0}

```

The next answer should start with the terms:

```
0,1,1,0,1,0

```

# Answer
> 1 votes
# Mathematica, 51 bytes, depth 11, A025765 from A226190

```
SeriesCoefficient[1/((1-x)(1-x^2)(1-x^9)),{x,0,#}]&

```

Just another infinite series. The next answer should start with the terms:

```
1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 7

```

# Answer
> 1 votes
# Python, 14 bytes, depth 3, A010872 from A000030

```
x=lambda x:x%3

```

The next sequence should start with the following terms:

```
0, 1, 2

```

# Answer
> 1 votes
# Haskell, 32 bytes, depth 7, A018819 from A016116

```
l=1:zipWith(+)l(tail$l>>=(:[0]))

```

This defines an infinite list containing all the values.

As more easily readable function that (could be golfed some more and) is much less efficient the sequence can be defined by

```
a 0=1; a m|odd m=a(m-1); a m=a(m-1)+a(m`div`2)

```

So it starts with 1, and then we always take the previous value and, in the even case, add the value from `m/2`. The list definition uses `l>>=(:[0])` to create a list that alternates between values from `l` and zeroes (`[l0,0,l1,0,l2,0,...]`) to achieve the same effect.

The sequence is the binary partition function, giving the number of partitions of a number into powers of 2, for example for 5 it is 4, because 5 can be written in four ways: as 1+1+1+1+1, 1+1+1+2, 1+2+2 and 1+4.

The next sequence should match the following terms:

```
1, 1, 2, 2, 4, 4, 6

```

# Answer
> 1 votes
# Vyxal, 5 bytes, depth 5, A000041 from A006882

```
[ṄL|1

```

Try it Online!

Calculates A000041(n). Could have been 2 bytes, but it wouldn't have worked correctly for an input of 0. The sequence is the number of integer partitions of `n`.

```
[ṄL|1 # Takes an integer input
[     # If input is not 0...
 Ṅ    # Integer partitions of n
  L   # And take the length
   |  # Otherwise...
    1 # Push 1
      # After which the top of the stack is printed

```

The next answer should match the following terms:

```
1, 1, 2, 3, 5

```

# Answer
> 1 votes
# Vyxal, 6 bytes, depth 6, A002379 from A000041

```
3$e$Eḭ

```

Try it Online!

The next answer should match the following terms:

```
1, 1, 2, 3, 5, 7

```

# Answer
> 1 votes
# Vyxal, 9 bytes, depth 5, A027383 from A000123

```
→ʀƛ←ε∵E;∑

```

Try it Online!

The next answer should match the following terms:

```
1, 2, 4, 6, 10

```

# Answer
> 1 votes
# Vyxal, 4 bytes, depth 8, A079584 from A01881

```
¡b1O

```

Try it Online!

The next sequence should match the following terms:

```
1, 1, 2, 2, 4, 4, 6, 6

```

# Answer
> 0 votes
# Mathematica, 6 bytes, depth 1, A002522

```
#^2+1&

```

The next answer should start with the terms:

```
1

```

# Answer
> 0 votes
# Mathematica, 4 bytes, depth 2, A000244 from A000012

```
3^#&

```

Powers of 3. The next answer should start with the terms:

```
1, 3

```

# Answer
> 0 votes
# Mathematica, 3 bytes, depth 2, A005843 from A001477

```
2#&

```

Even numbers. The next answer should start with the terms:

```
0, 2

```

# Answer
> 0 votes
# CJam, 21 bytes, depth 7, A095884 from A025581

```
1{_),(;{_@_@-@#p}/)}h

```

The next answer should start with the terms:

```
0, 1, 0, 2, 1, 0, 3

```

My second CJam program! I wonder if there's a better way to get `n (n-k)^k` from `n k` than `_@_@-@#` \- any tips?

This sequence is simply "Triangle read by rows: T(n,k) = (n-k)^k, n\>=1, 1\<=k\<=n.".

# Answer
> 0 votes
# CJam, 5 bytes, depth 5, A179081 from A001590

```
r1b2%

```

The next answer should start with the terms:

```
0, 1, 0, 1, 0

```

Parity of decimal digit sum.

# Answer
> 0 votes
# CJam, 9 bytes, depth 3, A025192 from A000027

```
3ri(#2*m]

```

The next answer should start with the terms:

```
1, 2, 6

```

2\*3^(n-1) with a special case.

For that sequence.

# Answer
> 0 votes
# PARI/GP, 19 bytes, depth 4, A056486 from A016957

```
n->(9*2^n+(-2)^n)/4

```

It's just `(9*2^n+(-2)^n)/4`. The old name was "Number of periodic palindromes using a maximum of four different symbols", but I don't know what it means.

The next answer should match the following terms:

```
4, 10, 16, 40

```

# Answer
> 0 votes
# Octave, 28 bytes, depth 6, A196564 from A179081

```
@(n)sum(mod(int2str(n)+0,2))

```

Number of odd digits in decimal representation of n.

The next answer should start with the terms:

```
0, 1, 0, 1, 0, 1

```

# Answer
> 0 votes
# CJam, 13 bytes, depth 7, A037888 from A196564

```
ri2b_W%.^:+2/

```

The next answer should start with the terms:

```
0, 1, 0, 1, 0, 1, 0

```

How many bits to change to make a palindrome binary number.

# Answer
> 0 votes
# R, 100 bytes, depth 5, A000110 from A000108

```
n=scan();a=0;for(k in 1:n){K=0:k;J=factorial(K);a=a+sum(rep(c(1,-1)*(-1)^k,l=k+1)*K^n/(J*rev(J)))};a

```

The next sequence should match the following terms:

```
1, 1, 2, 5, 15

```

This sequence is the Bell numbers, i. e. the number of ways to partition a set of n labeled elements. My code, with indents and newlines:

```
n=scan()
a=0
for(k in 1:n){
    K=0:k
    J=factorial(K)
    a=a+sum(rep(c(1,-1)*(-1)^k,l=k+1)*K^n/(J*rev(J)))
    }
a

```

What's inside the loop is an implementation of the "Stirling numbers of second kind", which happens to have been implemented also in R in package `gmp`, so the code could be golfed to 68 chars:

```
n=scan();sum(sapply(1:n,function(k)as.integer(gmp::Stirling2(n,k))))

```

# Answer
> 0 votes
# Pyth, 16 bytes, depth 3, A006521 from A000244

```
@f!%+^2T1Tr1^3QQ

```

Takes input via STDIN and outputs the Nth number.

### Explanation

```
@              Q   Nth item of
 f                  filter by
  !%+^2T1T           (2^Z + 1) mod Z is 0
          r1^3Q      integers 1..3^(N-1)

```

The next answer should match the following terms:

```
1, 3, 9

```

# Answer
> 0 votes
# CJam, 25 bytes, depth 13, A238263 from A135020

```
ri,(;{2*mF,3<}%_W%.&1b)2/

```

The next answer should start with the terms:

```
1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7

```

Number of ways of n=2^k1\*p1^k2+2^k3\*p2^k4, starting from n=2.

# Answer
> 0 votes
# R, 36 bytes, depth 9, A083912 from A103181

```
f=function(n)sum(!n%%1:n&1:n%%10==2)

```

The next sequence should match the following terms:

```
0, 1, 0, 1, 0, 1, 0, 1, 0

```

It is the sequence containing the number of divisors of n that are congruent to 2 modulo 10.

Usage:

```
> f(1)
[1] 0
> f(9)
[1] 0
> sapply(1:40, f)
[1] 0 1 0 1 0 1 0 1 0 1 0 2 0 1 0 1 0 1 0 1 0 2 0 2 0 1 0 1 0 1 0 2 0 1 0 2 0 1 0 1

```

# Answer
> 0 votes
# Pyth, 34 bytes, depth 13, A075355 from A135020

```
L?*bytbb1VQ~Z1J]ZW<.xJyhN~Z1aJZ;lJ

```

### Explanation

```
L                  define function y(b): return
  *bytb              b * y(b - 1)
 ?     b            if b is not 0, else
        1            1
VQ                 iterate N over 0..input-1
  ~Z1              increment Z (initialized to 0)
  J]Z               set J to array of Z
  W                 while
    .xJ               product of J
   <                 is less than
       yhN            factorial of N+1
          ~Z1          increment Z
          aJZ          add Z to J
;
lJ                 print length of J

```

The next answer should match the following terms:

```
1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 6

```

# Answer
> 0 votes
# Julia, 20 bytes, depth 6, A017910 from A000010

```
f(n)=ifloor(2^(n/2))

```

Note the use of `ifloor` instead of `floor` to force the conversion to integer. The next answer should start with the terms:

```
1, 1, 2, 2, 4, 5

```

# Answer
> 0 votes
# Pyth, 23 bytes, depth 6, A136855 from A136859

```
#Ig{`10456{+`Z`^Z2Z)~Z1

```

The next answer should match the following terms:

```
0, 1, 4, 10, 40, 100

```

My program prints an infinite stream of numbers, which where `n` and `n^2` only use the digits `01456`.

# Answer
> 0 votes
# Mathematica, 57 bytes, depth 5, A145132 from A000292

```
Series[n/((1-n-n^4)(1-n)^3),{n,0,#}]~SeriesCoefficient~#&

```

The `n`th coefficient of the expansion of `x/((1-x-x^4)(1-x)^3)`. The next answer should start with the terms:

```
0, 1, 4, 10, 20

```

# Answer
> 0 votes
# Mathematica, 25 bytes, depth 3, A172275 from A000004

```
Floor[#(Sqrt@13-Sqrt@7)]&

```

Simply `{0, 0, 1, 2, 3, ...}`. The next answer should start with the terms:

```
0, 0, 1

```

# Answer
> 0 votes
# Pyth, 7 bytes, depth 4, A001317 from A005408

```
uxGyGQ1

```

### Explanation

```
u    Q     reduce to do N times
      1     start with 1
 x          xor
  G          previous value
   yG        double previous value

```

The next answer should match the following terms:

```
1, 3, 5, 15

```

# Answer
> 0 votes
# Pyth, 26 bytes, depth 7, A136860 from A136855

```
L{jbT@f<+yTy*TTy10467U^5QQ

```

### Explanation

```
L                         define function y(b): returns
 {                         set of
  jbT                       base-10 digits of b
@                   Q     take Nth item
 f                         filter
                U^5Q        integers T in 0..(5^N)-1
   +                         union of
    yT                        digits of T
      y*TT                    digits of T^2
  <                         is subset of
          y10467             digits of 10467

```

The `N`th value will always be less than `5^N`, since:

1. All powers of 10 are in the sequence, as numbers of form `10^k` and `(10^k)^2 = 10^2k` will always contain only digits `1` and `0`.
2. All powers of 10 multiplied by 4 are in the sequence, as numbers of form `4*10^k` and `(4*10^k)^2 = 16*10^2k` will always contain only digits `4`, `1`, `6` and `0`.
3. Therefore there are at least two values in the sequence for each power of 10. For each value, we do the next power of 5, which means the next power of 25 for each value. This will always contain at least two values per power, since `25^m >= 10^m` whenever `m >= 0`.

The next answer should match the following terms:

```
0, 1, 4, 10, 40, 100, 400

```

# Answer
> 0 votes
# PARI/GP, 22 bytes, depth 4, A004601 from A010052

```
n->floor(Pi*2^(n-1))%2

```

Binary expansion of π.

The next sequence should start with the terms:

```
1, 1, 0, 0

```

# Answer
> 0 votes
# Julia, 27 bytes, depth 5, A010057 from A004601

```
f(n)=floor(n^(1/3))^3<n?0:1

```

Next sequence should start with the terms:

```
1, 1, 0, 0, 0

```

This sequence gives 1 if n is a cube and 0 if not.

# Answer
> 0 votes
# Python, 21 bytes, depth 7, A049472 from A028391

```
lambda n:int(n/2**.5)

```

Next sequence on that branch should start with the terms:

```
0, 0, 1, 2, 2, 3, 4

```

# Answer
> 0 votes
# R, 26 bytes, depth 4, A014684 from A000142

```
n=scan();n-(sum(n%%2:n)<2)

```

List of natural integers minus one if the integer is a prime. The next sequence should start with the terms:

```
1, 1, 2, 4

```

# Answer
> 0 votes
# CJam, 64 bytes, depth 9, A072490 from A057359

```
ri,(;{0:M;X\{\)0:A;{1$1$%0{_@@/\A):A}?}gAMe>:M;\_1>}g;;M1=}%0+:+

```

The next sequence should start with the terms:

```
0, 0, 1, 2, 2, 3, 4, 5, 5

```

Here's an easy-to-understand sequence: the number of squarefree numbers less than n. A squarefree number is one whose prime decomposition contains no repeated factors.

I am betting this can be golfed more. I figure out whether a number `k` is squarefree by iterating `j` from 2 to `k` and dividing the number by `j` as many times as it fits, then storing this in `A`. Then I keep track of the max `A`s in `M`, so `M` is the max number of repeated prime factors. If `M==1`, the number if squarefree. Then I apply this to all the numbers in the range and sum. But there must be a cleaner way. On the other hand I like that `gAMe` accidentally appears in the code.

# Answer
> 0 votes
# Mathematica, 66 bytes, depth 3, A000002 from A000027

```
Nest[Mod[Flatten@MapIndexed[Table[#2,{#}]&,#],2,1]&,{1,2},#][[#]]&

```

The next answer should start with the terms:

```
1, 2, 2

```

The Kolakoski Sequence.

A longer, but more interesting solution:

```
k[n_] := StringTake[
  NestWhile[
   StringReplace[#, {"1 1" -> "2 1", "1 2" -> "2 1 1",
      "2 1" -> "2 2 1", "2 2" -> "2 2 1 1"}] &, "1,2 2",
   StringLength@# < 2 n &], 2 n]

```

Related question: Generate a Kolakoski sequence

# Answer
> 0 votes
# CJam 0.6.5, 52 bytes, depth 9, A045841 from A103181

```
]:Rri`{i48-}%e!{_,),(;{\_@<_)2%{;aR+:R}{}?}/}/];RR&,

```

The next sequence should start with the following terms:

```
0, 1, 0, 1, 0, 1, 0, 1, 0

```

This is the "number of distinct odd numbers formed from the digits of n". e.g `A(37)` is `4` because you have `3`, `7`, `37`, and `73`, while `A(33)` is `2` because you have `3` and `33`.

`e!` gets permutations, but without choosing a subset. So for all permutations I take the first 1 through `d` digits in turn, see if they are odd, and if so add it to `R`. `RR&` at the end removes duplicates and then I output the length. I saved a bunch of bytes by leaving the stack littered with garbage and wiping it all out at the end with `];`.

# Answer
> 0 votes
# CJam, 28 bytes, depth 9, A098388 from A084054

```
ri:N1U{\)_mp@+_N=!}g;2mLm[p;

```

The next sequence should start with the following terms:

```
1, 1, 2, 2, 3, 3, 4, 4, 4

```

This is the floor of the binary logarithm of the nth prime. `1U{\)_mp@+_N=!}g;` computes the `N`th prime, and `2mLm[p` prints the floor of the binary logarithm.

This uses built-in primality testing `mp`, so if that is considered cheating let me know and I will use a non-built-in primality tester.

I wonder if this could be golfed a bit more.

# Answer
> 0 votes
# CJam, 17 bytes, depth 8, A194175 from A049472

```
ri,{)7mq*1%}%:+m[

```

The next sequence should start with the following terms:

```
0, 0, 1, 2, 2, 3, 4, 4

```

This one seemed like a nice and short one. It's simply:

where `frac` is the fractional part. Very well-suited to CJam.

# Answer
> 0 votes
# Python 3, 66 bytes, depth 2, A000043 from A000040

```
n=2
while n:k=2**n-1;any(k%d<1for d in range(2,k))or print(n);n+=1

```

The next answer should match the following terms:

```
2, 3

```

These are the positive integers `n` such that `2^n - 1` is prime, i.e. `n` is the exponent of a Mersenne prime. It's easy to see that `n` itself must be prime, since if `d` divides `n` then `2^d - 1` is a divisor of `2^n - 1`.

Equivalently, by the Euclid-Euler theorem, these are also the integers `n` such that `2^(n-1) (2^n - 1)` is an even perfect number (sum of divisors equals itself).

This Python program uses trial division, so it only manages to get up to 19 before it starts taking a while. For comparison, simply replacing the primality check with the probabilistic Miller-Rabin manages up to 607 in a reasonable amount of time.

# Answer
> 0 votes
## Seriously, 14 bytes, depth 3, A000125 from A000027

```
,;3@^@5*+6+6@\

```

Try it online!

The next answer should match the following terms:

```
1, 2, 4

```

# Answer
> 0 votes
# , noncompeting, depth 4, A001614 from A000125

17 chars / 25 bytes:

```
2*ï-⌊ ½+½*√ 8*ï-7

```

`Try it here (Firefox only).`

The next answer should match:

```
1, 2, 4, 5

```

# Answer
> 0 votes
# Mathematica, 14 bytes, depth 5, A129323 from A001563

```
BellB[#-1,2]#&

```

Derived from the Mathematica program given with the sequence. Ignore any messages. The next answer should start with the terms:

```
0, 1, 4, 18, 88

```

# Answer
> 0 votes
## Python 2, 59 bytes, depth 4, A000123 from A000125

```
i=0;j=1;s=1,
while 1:print s[-1];s+=(s[-1]+s[i],);i+=j;j^=1

```

**Try it online**. Uses a modified version so you can actually read the output, since infinite output is hard to read.

The next answer should match the following terms:

```
1, 2, 4, 6

```

# Answer
> 0 votes
# Mathematica, 11 bytes, depth 4, A004188 from A002275

```
(3#^3-#)/2&

```

The next answer should start with the terms:

```
0, 1, 11, 39

```

# Answer
> 0 votes
# Mathematica, 58 bytes, depth 12, A029031 from A025766

```
SeriesCoefficient[1/Times@@(1-x^#&)/@{1,2,11,12},{x,0,#}]&

```

Just uses the definition of the series. The next answer should start with the terms:

```
1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7

```

# Answer
> 0 votes
# Mathematica, 68 bytes, depth 11, A096088 from A096972

```
For[a=1,1>0,Print/@Union@Flatten[PowerModList[#,4,a]&/@0~Range~a++]]

```

Outputs terms, followed by newlines. The sequence definition is pretty complicated, so I won't go into it here. The next answer should start with the terms:

```
0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 3

```

# Answer
> 0 votes
# Mathematica, 40 bytes, depth 10, A096125 from A026233

```
NestWhile[#+1&,a=#;1,!((a-#)!^2∣a!)&]&

```

Just increments *k* until the condition is met. See the sequence definition for more information. The next answer should start with the terms:

```
1, 1, 2, 2, 3, 3, 4, 4, 5, 4

```

# Answer
> 0 votes
# Mathematica, 34 bytes, depth 10, A173923 from A045841

```
Floor[#~IntegerReverse~2/8]~Mod~2&

```

Uses a definition given with the sequence. Requires Mathematica 10.3 or higher to run. Starts at index 8. The next answer should start with the terms:

```
0, 1, 0, 1, 0, 1, 0, 1, 0, 0

```

# Answer
> 0 votes
# Mathematica, 98 bytes, depth 10, A175835 from A083912

```
Count[Normal@SeriesData[x,0,Reverse@RealDigits[EulerGamma,10,#][[1]],0,#,1]~NRoots~x,_Real,{1,2}]&

```

Pretty random sequence definition. Makes more sense if you read the sequence page. The next answer should start with the terms:

```
0, 1, 0, 1, 0, 1, 0, 1, 0, 1

```

# Answer
> 0 votes
# Mathematica, 20 bytes, depth 10, A225545 from A098388

```
Floor@*Exp@*LambertW

```

Does what it says on the tin (takes ⌊*e*<sup>*W*(*n*)</sup>⌋). `LambertW` appears to be an alias for `ProductLog`. The next answer should start with the terms:

```
1, 1, 2, 2, 3, 3, 4, 4, 4, 5

```

# Answer
> 0 votes
# Mathematica, 48 bytes, depth 9, A025640 from A022336

```
SortBy[0~Range~#~Tuples~2,3^# 4^#2&@@#&][[#,1]]&

```

Exponent of 3 (value of *i*) in *n*th number of form 3<sup>*i*</sup>∙4<sup>*j*</sup>. The next answer should start with the terms:

```
0, 1, 0, 2, 1, 0, 3, 2, 1

```

# Answer
> 0 votes
# Mathematica, 30 bytes, depth 9, A038668 from A057359

```
Floor[#/LucasL@a]~Sum~{a,#}-#&

```

*A<sub>n</sub>* = ⌊*n*/*L*(2)⌋ + ⌊*n*/*L*(3)⌋ + ⌊*n*/*L*(4)⌋ + ⌊*n*/*L*(5)⌋ + ⋯, where *L*(*n*) denotes the *n*th term in the Lucas sequence. The next answer should start with the terms:

```
0, 0, 1, 2, 2, 3, 4, 5, 6

```

---
Tags: code-challenge, number, sequence, answer-chaining
---


title: Optimally break a string into words

text:
# Question
Title: Optimally break a string into words
Given a string, like `potatocarrot`, break it into the smallest number of substrings possible. These substrings can consist either be a single character, or one of a list of words passed as input. For example, if `[carrot, potato]` was the input, the optimal way to break the string up would be `[potato][carrot]`. If the list was `[potat, tatocarr, rot]`, the optimal way would be `[p][o][tatocarr][o][t]`.

You can take the string in any reasonable format, and the list of substrings in any reasonable format. As for output, any of the following would be examples of allowed output formats:

* Inserting characters into the string to delimit substrings (e.g., `"potato,carrot"` or `"[potato][carrot]"`)
* Delimiting words, but not individual characters (e.g., `"po[tatocarr]ot"`, but not `"po,tatocarr,ot"`)
* Returning an array of substrings (e.g., `["potato", "carrot"]`)

You can assume the input strings consist of lowercase letters, and that there won't be duplicates or strings with a length of 0 or 1 in the list of substrings.

This is , so shortest answer (in bytes) per language wins.

**Test cases:**

```
STRING          WORDS                   OPTIMAL SOLUTION
potatocarrot    potato, carrot          [potato][carrot]
potatocarrot    pot, tatocarr, rot      [p][o][tatocarr][o][t]
potatocarrot    atocarr, ot             [p][ot][atocarr][ot]
potatocarrot    tatocarr, potato, carr  [potato][carr][o][t]
purpur                                  [p][u][r][p][u][r]
purpur          carrot                  [p][u][r][p][u][r]
purpur          pur                     [pur][pur]
purpur          pu, rp                  [pu][r][pu][r] OR [pu][rp][u][r]
purpur          pu, rp, urp             [pu][r][pu][r] OR [pu][rp][u][r] OR [p][urp][u][r]
todoornottodo   to, do, or, not         [to][do][or][not][to][do]
todoornottodo   tod, nott, door         [t][o][door][nott][o][d][o]

```

# Answer
> 5 votes
# Python, 82 bytes

```
f=lambda s,d:s and min([[w,*f(s[len(w):],d)]for w in[*d,*s]if w+"~">s>=w],key=len)
```

Attempt This Online!

Depth-first search over solution space.

-6 bytes thanks to loopy walt

# Answer
> 4 votes
# APL(Dyalog Unicode), 42 bytes SBCS

Assumes index origin 0. Takes the string as right argument ⍵ and the word list as left argument ⍺.

```
{e⊃⍨⊃⍋≢¨e←d/⍨(1∧.=≢¨∨∊∘⍺)¨d←⊂∘⍵¨~,⍳1+×⍳≢⍵}

```

Try it on APLgolf!

`⍳≢⍵` Indices of the string: `0 1 ... (length-1)`
`1+×` Sign of that incremented: `1 2 2 ... 2 2`
`,⍳` Indices of an array of that shape, flattened. All these indices have a 0 in the first position and some combination of 1's and 0's after that.
`~` Boolean inverse.
`d←⊂∘⍵¨` Partition the string according to each of these sequences. This yields a list of all partitions. (Call this `d`)
`≢¨∨∊∘⍺ ¨` For each substring in each partition, take the gcd of its length and the boolean indicating whether it is in the word list. This is only 1 if at least one of the values is 1.
`1∧.=` For each partition, are all values 1?
`e←d/⍨` Only keep partitions where this is the case and call these `e`.
`e⊃⍨⊃⍋≢¨` Pick the partition with minimal length.

# Answer
> 4 votes
# Ruby, ~~60~~ 53 bytes

```
->s,l,r=""{s=~/^#{r+="(.|"+l*?|+?)}$/?$~[1..-1]:redo}

```

Try it online!

# Answer
> 3 votes
# Retina, ~~81~~ 65 bytes

```
/,;/^+%L$w`\b(\w(\w+)?)(\w*;(?(2).*\b\1\b))
$`$1,$3$'
0G`,;
,;.*

```

Try it online! Link includes test cases. Explanation:

```
/,;/^+

```

Repeat until a complete substring list has been found...

```
%L$w`\b(\w(\w+)?)(\w*;(?(2).*\b\1\b))

```

... find all of the leading substrings of the rest of the input that are either a single character or are present in the list of words, ...

```
$`$1,$3$'

```

... and create new substring lists containing each of those substrings.

```
0G`,;
,;.*

```

Output just the first complete list of substrings.

# Answer
> 2 votes
# Python, ~~353~~ ~~348~~ ~~342~~ 309 bytes

```
import re,itertools as I
def f(s,a):
 u=[]
 for e in I.permutations(a):
  *r,=s
  for x in e:
   if x in s:
    p=0
    for _ in"_"*s.count(x):
     b=s.index(x,p);p=b+len(x);j=''.join(r[b:p])
     if j.isalpha():r[b]='<'+r[b];r[p-1]+='>'
  u+=''.join(r),
 return min(u,key=lambda x:len(re.sub('<.+?>','',x)))
```

Attempt This Online!

*-5 bytes thanks to ophact*

*-33 bytes thanks to pxeger*

# Answer
> 2 votes
# JavaScript (ES6),  ~~104 102 97~~  96 bytes

Expects `(word_list)(string)`. Returns a list of substrings.

```
a=>g=(s,O=o='',...b)=>[s[O.length],...a].every(e=>e&&g(s,O+e,...b,e))|O!=s||b[o&&o.length]?o:o=b

```

Try it online!

# Answer
> 1 votes
# Python3, 145 bytes:

```
lambda s,w:min(f(s,w),key=len)
f=lambda s,w,c=[]:[c]if''==s else[x for y in w for x in f(s[len(y):],w,c+[y])if s[:len(y)]==y]+f(s[1:],w,c+[s[0]])

```

Try it online!

# Answer
> 1 votes
# Charcoal, ~~73~~ 67 bytes

```
≔⟦⟦Ｓ⟧⟧θ≔⟦⟧ηＷＳ⊞ηιＦθ«≔⊟ιζ¿ζＦ⁺η⟦§ζ⁰⟧Ｆ⁼κ✂ζ⁰Ｌκ⊞θ⁺ι⟦κ✂ζＬκ⟧⊞υι»⊟Φυ⁼Ｌι⌊ＥυＬλ

```

Try it online! Link is to verbose version of code. Takes input as a newline-terminated list of words and outputs each substring on its own line (default output for an array of substrings). Explanation:

```
≔⟦⟦Ｓ⟧⟧θ

```

Start a breadth-first search with an empty substring list that still has the initial input to processes.

```
≔⟦⟧ηＷＳ⊞ηι

```

Input the list of words.

```
Ｆθ«

```

Loop over the list of substring lists.

```
≔⊟ιζ

```

Remove the remainder of the input from this substring list.

```
¿ζ

```

If there is still any input left:

```
Ｆ⁺η⟦§ζ⁰⟧

```

For each of the input words, plus the first letter of the remainder of the input, ...

```
Ｆ⁼κ✂ζ⁰Ｌκ

```

... if the remainder of the input begins with this string, ...

```
⊞θ⁺ι⟦κ✂ζＬκ⟧

```

... then push a new substring list obtained by splitting the input after that string.

```
⊞υι

```

Otherwise, save this substring list.

```
»⊟Φυ⁼Ｌι⌊ＥυＬλ

```

Output any one shortest substring list.

---
Tags: code-golf, string, optimization, subsequence
---