# Question
Title: Inverse quine: print everything except your program
Write a program which will eventually, given enough time, print all possible permutations of ASCII characters (both printable *and* non-printable) less than or equal to its length, **except** itself. The text of the program must not appear anywhere in its output.

For example, if your program is `abc`, then part of your output could look like:

```
(many lines omitted)
ab0
ab1
ab2
...
abb
abd
(many lines omitted)

```

or

```
...[some character other than a]bcabacba5804g715^^*#0...

```

If your language requires characters that are not printable ASCII (e.g. Jelly or APL), print all combinations of characters in its code page.

The strings need not be separate from each other; a single character can be counted as part of multiple strings. You could try to create a superpermutation, which would be at least \\$95! + 94! + 93! + 95 − 3 = 1.04 × 10^{148}\\$ characters long.

Standard quine rules apply (no reading the program's source code) but this is also code golf.

# Answer
# Ruby, <sup>~~92~~ ~~91~~</sup> 86 bytes

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

```
eval s="a=*?\0..?\x7f;90.times{|i|puts a.product(*[a]*i).map(&:join)-['eval s=%p'%s]}"

```

Try it online!

Forms arrays containing all permutations of ASCII characters (codepoints `00` to `127`) of length 1 to 91, then subtracts from each the string `eval$s=%q(#$s)`, which is equivalent to the full program (because of the interpolated string `$s`).

```
eval s="                               # evaluate s, a double-quoted string that contains most of the program
  a=*?\0..?\x7f;                       # create array of ASCII characters 00 to 127
  90.times{|i|                         # for permutations of length i = 1 to 91:
    puts a.product(*[a]*i).map(&:join)   # print all strings of length i...
    -['eval$s=%p'%s]                     # not equal to the full program
  }
"

```
> 2 votes

# Answer
# Perl 5, ~~119~~, ~~110~~, 108 bytes

-9 bytes hardcoding code length thanks to @Dingus.

```
$C=q(while(y///c<109){s/^\xff*(.?)/"\0"x$-[1].chr(''ne$1?1+ord$1:0)/es;"\$C=q($C);eval\$C"ne$_&&say});eval$C

```

Try it online!

or to check the case when output is just before the source
> 1 votes

---
Tags: code-golf, kolmogorov-complexity, quine
---


title: Fissile Numbers

text:
# Question
Title: Fissile Numbers
*I found this sequence while working on Evolution of OEIS, but never got around to posting it as an answer. After writing a reference implementation in Mathematica, I thought this is a fun exercise to do as a separate challenge though, so here we go.*

Let's build a numeric fission reactor! Consider a positive integer `N`. As an example, we'll look at `24`. To fission this number, we have to find the largest number of *consecutive* positive integers that sum to `N`. In this case, that's `7 + 8 + 9 = 24`. So we've split `24` into three new numbers. But this wouldn't be much of a fission reactor without chain reactions. So let's recursively repeat the process for these components:

```
       24
       /|\
      / | \
     /  |  \
    7   8   9
   / \     /|\
  3   4   / | \
 / \     /  |  \
1   2   2   3   4
           / \
          1   2

```

Notice that we stop the process whenever the number cannot be decomposed into smaller consecutive integers. Also note that we could have written `9` as `4 + 5`, but `2 + 3 + 4` has more components. The **Fission number** of `N` is now defined as the number of integers obtained in this process, including `N` itself. The above tree has 13 nodes, so `F(24) = 13`.

This sequence is OEIS entry A256504.

The first 40 terms, starting from `N = 1`, are

```
1, 1, 3, 1, 5, 6, 5, 1, 6, 7, 12, 10, 12, 11, 12, 1, 8, 16, 14, 17, 18, 18,
23, 13, 21, 18, 22, 23, 24, 19, 14, 1, 22, 20, 23, 24, 31, 27, 25, 26

```

The first 1000 terms can be found in this pastebin.

## The Challenge

Given a positive integer `N`, determine its Fission number `F(N)`. (So you don't need to cover the leading `0` listed on OEIS.)

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.

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

**Bonus question:** Can you find any interesting properties of this sequence?

# Answer
> 53 votes
# Fission, ~~1328~~ ~~989~~ ~~887~~ 797 bytes

*This answer is a bit unreasonably long (I wish we had collapsible regions)... please don't forget to scroll past this and show the other answers some love!*

Working on this code was what inspired this challenge. I wanted to add an answer in Fission to EOEIS, which led me to this sequence. However, actually learning Fission and implementing this took a few weeks working on it on and off. In the meantime, the sequence had really grown on me so I decided to post a separate challenge for it (plus, this wouldn't have been particularly far down the tree on EOEIS anyway).

So I present to you, the Monstrosity:

```
 R'0@+\
/  Y@</ /[@ Y]_L
[? % \  / \ J
   \$@  [Z/;[{+++++++++L
UR+++++++++>/;
9\   ;    7A9
SQS  {+L  /$     \/\/\/\/\/   5/ @  [~ &@[S\/ \  D /8/
~4X /A@[  %5                   /; &    K  } [S//~KSA /
  3    \  A$@S  S\/  \/\/\/   \/>\ /S]@A  /  \ { +X
W7           X  X    /> \      +\ A\ /   \ /6~@/ \/
        /   ~A\;     +;\      /@
    ZX [K    / {/  / @  @ }  \ X @
       \AS   </      \V /    }SZS S/
         X   ;;@\   /;X  /> \ ; X X
 ;       \@+  >/ }$S SZS\+;    //\V
           / \\  /\; X X @  @  \~K{
           \0X /     /~/V\V /   0W//
    \        Z      [K \  //\
W       /MJ $$\\ /\7\A  /;7/\/ /
       4}K~@\ &]    @\  3/\
 /     \{   }$A/1 2  }Y~K <\
[{/\  ;@\@  /   \@<+@^   1;}++@S68
@\ <\    2        ;   \    /
$  ;}++ +++++++L
%@A{/
M  \@+>/
~     @
SNR'0YK
  \  A!/

```

It expects that there is no trailing newline on the input, so you might want to call it like `echo -n 120 | ./Fission oeis256504.fis`.

The layout could probably still be more efficient, so I think there's still a lot of room for improvement here (for instance, this contains ~~911~~ ~~581~~ ~~461~~ 374 spaces).

Before we get to the explanation, a note on testing this: the official interpreter doesn't entirely work as is. a) `Mirror.cpp` doesn't compile on many systems. If you run into that problem, just comment out the offending line - the affected component (a random mirror) is not used in this code. b) There are a couple of bugs that can lead to undefined behaviour (and likely will for a program this complex). You can apply this patch to fix them. Once you've done that, you should be able to compile the interpreter with

```
g++ -g --std=c++11 *.cpp -o Fission

```

Fun fact: This program uses almost every component Fission has to offer, except for `#` (random mirror), `:` (half mirror), `-` or `|` (plain mirror), and `"` (print mode).

## What on Earth?

**Warning:** This will be quite long... I'm assuming you're genuinely interested in how Fission works and how one could program in it. Because if you're not, I'm not sure how I could possibly summarise this. (The next paragraph gives a general description of the language though.)

Fission is a two-dimensional programming language, where both data and control flow are represented by *atoms* moving through a grid. If you've seen or used Marbelous before, the concept should be vaguely familiar. Each atom has two integer properties: a non-negative mass and an arbitrary energy. If the mass ever becomes negative the atom is removed from the grid. In most cases you can treat the mass as the "value" of the atom and the energy as some sort of meta-property that is used by several components to determine the flow of the atoms (i.e. most sorts of switches depend on the sign of the energy). I will denoted atoms by `(m,E)`, when necessary. At the beginning of the program, the grid starts with a bunch of `(1,0)` atoms from wherever you place on of the four components `UDLR` (where the letter indicates the direction the atom is moving in initially). The board is then populated with a whole bunch of *components* which change the mass and energy of atoms, change their directions or do other more sophisticated things. For a complete list see the esolangs page, but I'll introduce most of them in this explanation. Another important point (which the program makes use of several times) is that the grid is toroidal: an atom that hits any of the sides reappears on the opposite side, moving in the same direction.

I wrote the program in several smaller parts and assembled them at the end, so that's how I'll go through the explanation.

### `atoi`

This component may seem rather uninteresting, but it's nice and simple and allows me to introduce a lot of the important concepts of Fission's arithmetic and control flow. Therefore, I will go through this part in quite meticulous detail, so I can reduce the other parts to introducing new Fission mechanics and pointing out higher-level components whose detailed control flow you should be able to follow yourself.

Fission can only read byte values from individual characters, not entire numbers. While that's acceptable practice around here, I figured while I was at it, I could do it right and parse actual integers on STDIN. Here is the `atoi` code:

```
     ;
 R'0@+\
/  Y@</ /[@ Y]_L
[? % \  / \ J
   \$@  [Z/;[{+++++++++L
UR+++++++++>/;
           O

```

Two of the most important components in Fission are fission and fusion reactors. Fission reactors are any of `V^<>` (the above code uses `<` and `>`). A fission reactor can store an atom (by sending it into the character's wedge), the default being `(2,0)`. If an atom hits the character's apex, two new atoms will be sent off to the sides. Their mass is determined by dividing the incoming mass by the stored mass (i.e. halving by default) - the left-going atom gets this value, and the right-going atom gets the remainder of the mass (i.e. mass is conserved in the fission). Both outgoing atoms will have the incoming energy *minus* the stored energy. This means we can use fission reactors for arithmetic - both for subtraction and division. If a fission reactor is hit from the site, the atom is simply reflected diagonally and will then move in the direction of the character's apex.

Fusion reactors are any of `YA{}` (the above code uses `Y` and `{`). Their function is similar: they can store an atom (default `(1,0)`) and when hit from the apex two new atoms will be sent off to the sides. However, in this case the two atoms will be identical, always retaining the incoming energy, and multiplying the incoming mass by the stored mass. That is, by default, the fusion reactor simply duplicates any atom hitting its apex. When hit from the sides, fusion reactors are a bit more complicated: the atom is *also* stored (independently of the other memory) until an atom hits the opposite side. When that happens a new atom is released in the direction of the apex whose mass and energy are the sum of the two old atoms. If a new atom hits the same side before a matching atom reaches the opposite side, the old atom will simply be overwritten. Fusion reactors can be used to implement addition and multiplication.

Another simple component I want to get out of the way is `[` and `]` which simply set the atom's direction to right and left, respectively (regardless of incoming direction). The vertical equivalents are `M` (down) and `W` (up) but they're not used for the `atoi` code. `UDLR` also act as `WM][` after releasing their initial atoms.

Anyway, let's look at the code up there. The program starts out with 5 atoms:

* The `R` and `L` at the bottom simply get their mass increment (with `+`) to become `(10,0)` and then stored in a fission and a fusion reactor, respectively. We will use these reactors to parse the base-10 input.
* The `L` in the top right corner gets its mass decremented (with `_`) to become `(0,0)` and is stored in the side of a fusion reactor `Y`. This is to keep track of the number we're reading - we'll gradually increase and multiply this as we read numbers.
* The `R` in the top left corner gets its mass set to the character code of `0` (48) with `'0`, then mass and energy are swapped with `@` and finally mass incremented once with `+` to give `(1,48)`. It is then redirected with diagonal mirrors `\` and `/` to be stored in a fission reactor. We'll use the `48` for subtraction to turn the ASCII input into the actual values of the digits. We also had to increase the mass to `1` to avoid division by `0`.
* Finally, the `U` in the bottom left corner is what actually sets everything in motion and is initially used only for control flow.

After being redirected to the right, the control atom hits `?`. This is the input component. It reads a character and sets the atom's mass to the read ASCII value and the energy to `0`. If we hit EOF instead, the energy will be set to `1`.

The atom continues and then hits `%`. This is a mirror switch. For non-positive energy, this acts like a `/` mirror. But for positive energy it acts like a `\` (and also decrements the energy by 1). So while we're reading the characters, the atom will be reflected upwards and we can process the character. But when we're done with the input, the atom will be reflected downwards and we can apply different logic to retrieve the result. FYI, the opposite component is `&`.

So we've got an atom moving up for now. What we want to do for each character is to read its digit value, add that to our running total and then multiply that running total by 10 to prepare for the next digit.

The character atom first hits a (default) fusion reactor `Y`. This splits the atom and we use the left-going copy as a control atom to loop back into the input component and read the next character. The right-going copy will be processed. Consider the case where we've read the character `3`. Our atom will be `(51,0)`. We swap mass and energy with `@`, such that we can make use of the subtraction of the next fission reactor. The reactor subtracts `48` off the energy (without changing the mass), so the it sends off two copies of `(0,3)` \- the energy now corresponds to the digit we've read. The upgoing copy is simply discarded with `;` (a component that just destroys all incoming atoms). We'll keep working with the downgoing copy. You'll need to follow its path through the `/` and `\` mirrors a bit.

The `@` just before the fusion reactor swaps mass and energy again, such that we'll add `(3,0)` to our running total in the `Y`. Note that the running total itself will therefore always have `0` energy.

Now `J` is a jump. What it does is jump any incoming atom forward by its energy. If it's `0`, the atom just keeps moving straight on. If it's `1` it will skip one cell, if it's `2` it'll skip two cells and so on. The energy is spent in the jump, so the atom always ends up with energy `0`. Since the running total does have zero energy, the jump is ignored for now and the atom is redirected into the fusion reactor `{` which multiplies its mass by `10`. The downgoing copy is discarded with `;` while the upgoing copy is fed back into the `Y` reactor as the new running total.

The above keeps repeating (in a funny pipelined way where new digits are being processed before the previous ones are done) until we hit EOF. Now the `%` will send the atom downwards. The idea is to turn this atom into `(0,1)` now before hitting the running total reactor so that a) the total is not affected (zero mass) and b) we get an energy of `1` to jump over the `[`. We can easily take care of the energy with `$`, which increments the energy.

The issue is that `?` does not reset the mass when you're hitting EOF so the mass will still be that of the last character read, and the energy will be `0` (because `%` decremented the `1` back to `0`). So we want to get rid of that mass. To do that we swap mass and energy with `@` again.

I need to introduce one more component before finishing up this section: `Z`. This is essentially the same as `%` or `&`. The difference is that it lets positive-energy atoms pass straight through (while decrementing the energy) and deflects non-positive-energy atoms 90 degrees to the left. We can use this to eliminate an atom's energy by looping it through the `Z` over and over - as soon as the energy is gone, the atom will be deflected and leave the loop. That is this pattern:

```
/ \
[Z/

```

where the atom will move upwards once the energy is zero. I will use this pattern in one form or another several times in the other parts of the program.

So when the atom leaves this little loop, it will be `(1,0)` and swapped to `(0,1)` by the `@` before hitting the fusion reactor to release the final result of the input. However, the running total will be off by a factor of 10, because we've tentatively multiplied it for another digit already.

So now with energy `1`, this atom will skip the `[` and jump into the `/`. This deflects it into a fission reactor which we've prepared to divide by 10 and fix our extraneous multiplication. Again, we discard one half with `;` and keep the other as output (here represented with `O` which would simply print the corresponding character and destroy the atom - in the full program we keep using the atom instead).

### `itoa`

```
           /     \
input ->  [{/\  ;@
          @\ <\
          $  ;}++ +++++++L
          %@A{/
          M  \@+>/
          ~     @
          SNR'0YK
            \  A!/

```

Of course, we also need to convert the result back to a string and print it. That's what this part is for. This assumes that the input doesn't arrive before tick 10 or so, but in the full program that's easily given. This bit can be found at the bottom of the full program.

This code introduce a new very powerful Fission component: the stack `K`. The stack is initially empty. When an atom with non-negative energy hits the stack, the atom is simply pushed onto the stack. When an atom with negative energy hits the stack, its mass and energy will be replaced by the atom on the top of the stack (which is thereby popped). If the stack is empty though, the direction of the atom is reversed and its energy becomes positive (i.e. is multiplied by `-1`).

Okay, back to the actual code. The idea of the `itoa` snippet is to repeatedly take the input modulo 10 to find the next digit while integer-dividing the input by 10 for next iteration. This will yield all the digits in reverse order (from least significant to most significant). To fix the order we push all the digits onto a stack and at the end pop them off one by one to print them.

The upper half of the code does the digit computation: the `L` with the pluses gives a 10 which we clone and feed into a fission and a fusion reactor so we can divide and multiply by 10. The loop essentially starts after the `[` in the top left corner. The current value is split: one copy is divided by 10, then multiplied by 10 and stored in a fission reactor, which is then hit by the other copy at the apex. This computes `i % 10` as `i - ((i/10) * 10)`. Note also that the `A` splits the intermediate result after the division and before the multiplication, such that we can feed `i / 10` into the next iteration.

The `%` aborts the loop once the iteration variable hits 0. Since this is more or less a do-while loop, this code would even work for printing `0` (without creating leading zeroes otherwise). Once we leave the loop we want to empty the stack and print the digits. `S` is the opposite of `Z`, so it's a switch which will deflect an incoming atom with non-positive energy 90 degrees to the right. So the atom actually moves over the edge from the `S` straight to the `K` to pop off a digit (note the `~` which ensures that the incoming atom has energy `-1`). That digit is incremented by `48` to get the ASCII code of the corresponding digit character. The `A` splits the digit to print one copy with `!` and feed the other copy back into the `Y` reactor for the next digit. The copy that's printed is used as the next trigger for the stack (note that the mirrors also send it around the edge to hit the `M` from the left).

When the stack is empty, the `K` will reflect the atom and turn its energy into `+1`, such that it passes straight through the `S`. `N` prints a newline (just because it's neat :)). And then the atom goes thorugh the `R'0` again to end up in the side of the `Y`. Since there are no further atoms around, this will never be released and the program terminates.

### Computing the Fission Number: The Framework

Let's get to the actual meat of the program. The code is basically a port of my Mathematica reference implementation:

```
fission[n_] := If[
  (div =
    SelectFirst[
      Reverse@Divisors[2 n],
      (OddQ@# == IntegerQ[n/#]
       && n/# > (# - 1)/2) &
    ]
  ) == 1,
  1,
  1 + Total[fission /@ (Range@div + n/div - (div + 1)/2)]
]

```

where `div` is the number of integers in the maximal partition.

The main differences are that we can't deal with half-integer values in Fission so I'm doing a lot of things multiplied by two, and that there is no recursion in Fission. To work around this, I'm pushing all the integers in a partition in a queue to be processed later. For each number we process, we'll increment a counter by one and once the queue is empty, we'll release the counter and send it off to be printed. (A queue, `Q`, works exactly like `K`, just in FIFO order.)

Here is a framework for this concept:

```
                      +--- input goes in here
                      v

                     SQS ---> compute div from n          D /8/
                     ~4X               |                /~KSA /
                       3               +----------->    { +X
initial trigger ---> W                               6~@/ \/
                              4
                     W        ^                     /
                              |              3
                     ^     generate range    |
                     |     from n and div  <-+----- S6
                     |         -then-
                     +---- release new trigger

```

The most important new components are the digits. These are teleporters. All teleporters with the same digit belong together. When an atom hits any teleporter it will be immediately move the next teleporter in the same group, where *next* is determined in the usual left-to-right, top-to-bottom order. These are not necessary, but help with the layouting (and hence golfing a bit). There is also `X` which simply duplicates an atom, sending one copy straight ahead and the other backwards.

By now you might be able to sort out most of the framework yourself. The top left corner has the queue of values still to be processed and releases one `n` at a time. One copy of `n` is teleported to the bottom because we need it when computing the range, the other copy goes into the block at the top which computes `div` (this is by far the single largest section of the code). Once `div` has been computed, it is duplicated - one copy increments a counter in the top right corner, which is stored in `K`. The other copy is teleported to the bottom. If `div` was `1`, we deflect it upwards immediately and use it as a trigger for the next iteration, without enqueuing any new values. Otherwise we use `div` and `n` in the section at the bottom to generate the new range (i.e. a stream of atoms with the corresponding masses which are subsequently put in the queue), and then release a new trigger after the range has been completed.

Once the queue is empty, the trigger will be reflected, passing straight through the `S` and reappearing in the top right corner, where it releases the counter (the final result) from `A`, which is then teleported to `itoa` via `8`.

### Computing the Fission Number: The Loop Body

So all that's left is the two sections to compute `div` and generate the range. Computing `div` is this part:

```
 ;
 {+L  /$     \/\/\/\/\/   5/ @  [~ &@[S\/ \
/A@[  %5                   /; &    K  } [S/
   \  A$@S  S\/  \/\/\/   \/>\ /S]@A  /  \
         X  X    /> \      +\ A\ /   \ /
    /   ~A\;     +;\      /@
ZX [K    / {/  / @  @ }  \ X @
   \AS   </      \V /    }SZS S/
     X   ;;@\   /;X  /> \ ; X X
     \@+  >/ }$S SZS\+;    //\V
       / \\  /\; X X @  @  \~K{
       \0X /     /~/V\V /   0W//
\        Z      [K \  //\
           \ /\7\A  /;7/\/

```

You've probably seen enough now to puzzle this out for yourself with some patience. The high-level breakdown is this: The first 12 columns or so generate a stream of divisors of `2n`. The next 10 columns filter out those that don't satisfy `OddQ@# == IntegerQ[n/#]`. The next 8 columns filter out those that don't satisfy `n/# > (# - 1)/2)`. Finally we push all valid divisors on a stack, and once we're done we empty the entire stack into a fusion reactor (overwriting all but the last/largest divisor) and then release the result, followed by eliminating its energy (which was non-zero from checking the inequality).

There are a lot of crazy paths in there that don't really do anything. Predominantly, the `\/\/\/\/` madness at the top (the `5`s are also part of it) and one path around the bottom (that goes through the `7`s). I had to add these to deal with some nasty race conditions. Fission could use a delay component...

The code that generates the new range from `n` and `div` is this:

```
 /MJ $$\
4}K~@\ &]    @\  3/\
\{   }$A/1 2  }Y~K <\
 \@  /   \@<+@^   1;}++@
  2        ;   \    /

```

We first compute `n/div - (div + 1)/2` (both terms floored, which yields the same result) and store for later. Then we generate a range from `div` down to `1` and add the stored value to each of them.

There are two new common patterns in both of these, that I should mention: One is `SX` or `ZX` hit from below (or rotated versions). This is a nice way to duplicate an atom if you want one copy to go straight ahead (since redirecting the outputs of a fusion reactor can sometimes be cumbersome). The `S` or `Z` rotates the atom into the `X` and then rotates the mirrored copy back into the original direction of propagation.

The other pattern is

```
[K
\A --> output

```

If we store any value in `K` we can repeatedly retrieve it by hitting `K` with negative energy from the top. The `A` duplicates the value we're interested in and sends what copy right back onto the stack for the next time we need it.

Well, that was quite a tome... but if you actually got through this, I hope you got the idea that Fission i͝s̢̘̗̗ ͢i̟nç̮̩r̸̭̬̱͔e̟̹̟̜͟d̙i̠͙͎̖͓̯b̘̠͎̭̰̼l̶̪̙̮̥̮y̠̠͎̺͜ ͚̬̮f̟͞u̱̦̰͍n͍ ̜̠̙t̸̳̩̝o ̫͉̙͠p̯̱̭͙̜͙͞ŕ̮͓̜o̢̙̣̭g̩̼̣̝r̤͍͔̘̟ͅa̪̜͇m̳̭͔̤̞ͅ ͕̺͉̫̀ͅi͜n̳̯̗̳͇̹.̫̞̲̞̜̳

# Answer
> 16 votes
# Pyth, ~~23~~ ~~22~~ 21 bytes

```
Lh&lJfqbsT.:tUb)syMeJ

```

This defines a recursive function `y`. Try it online: Demonstration

### Explanation:

```
L                      define a function y(b): return ...
            tUb          the list [1, 2, ..., b-1]
          .:   )         generate all consecutive sub-sequences
     f                   filter for sub-sequences T, which satisfy:
      qbsT                   b == sum(T)
    J                    and store them in J

                         return
   lJ                        len(J)
  &                        and (if len(J) == 0 then 0 else ...)
                    eJ       last element of J (=longest sub-sequence)
                  yM         recursive calls for all these numbers
                 s           sum
 h                         incremented by one (counting the current node)

```

# Answer
> 11 votes
# CJam, ~~42~~ 41 bytes

```
ri]{_{:X,:)_few:+W%{1bX=}=}%{,(},e_}h]e_,

```

A simple Breadth first traversal and a stopping condition of empty next level.

**How it works**:

```
ri]                                       e# This represents the root of the fissile tree
   {                               }h     e# Now we run a do-while loop
    _{                    }%              e# Copy the nodes at the current level and map them
                                          e# via this code block to get next level nodes
      :X,:)                               e# Store the node value in X and get array [1..X]
           _few                           e# Copy the array and get continuous slices of
                                          e# length 1 through X from the array [1..X]
               :+W%                       e# Right now, we have an array of array with each
                                          e# array containing slice of same length. We join
                                          e# those arrays and reverse them to get slices of
                                          e# higher length in front of lower lengths
                   {1bX=}=                e# Choose the first slice whose sum is same as X
                                          e# The reversal above makes sure that we give
                                          e# preference to slice of higher length in case of
                                          e# multiple slices add up to X
                            {,(},         e# Filter out slices of length 1 which basically
                                          e# mean that the current node cannot be split up
                                 e_       e# Join all slices in a single array. This is our
                                          e# next level in the Fissile tree. If this is empty
                                          e# it means that all no further node can be
                                          e# decomposed. In an {}h do-while loop, this fact
                                          e# itself becomes the stopping condition for the
                                          e# loop
                                     ]e_, e# Wrap all levels in an array. Flatten the array
                                          e# and take its length

```

Try it online here

# Answer
> 10 votes
# Python 3, 112 bytes

```
def f(n,c=0):
 d=n-c;s=(n-d*~-d/2)/d
 return(s%1or s<1)and f(n,c+1)or+(d<2)or-~sum(f(int(s)+i)for i in range(d))

```

4 bytes saved thanks to @FryAmTheEggman.

Explanation coming later...

**Bonus fact:** Every power of 2 has a Fission number of 1. This is because the sum of an even length sequence is always the sum of the two middle numbers, which is odd, multiplied by half the length of the sequence, which is integer. The sum of an odd length sequence is the middle number multiplied by the sequence length, which is odd. So because a power of 2 doesn't have an odd divisor it can be only expressed as the sum of itself.

# Answer
> 8 votes
# Python 2, ~~111~~ ~~102~~ 97 bytes

**Somewhat readable:**

```
def f(n,c=0):a=n-c;b=n-a*~-a/2;return 1/a or-~sum(map(f,range(b/a,b/a+a)))if b>b%a<1else f(n,c+1)

```

**Not-so-readable:**

```
def f(n,a=0):b=n-a*~-a/2;return b>0and(f(n,a+1)or b%a<1and(1/a or-~sum(map(f,range(b/a,b/a+a)))))

```

Both 97 bytes.

`b` is the `n` minus the `(a-1)th` triangular number. If `b % a == 0`, then `n` is the sum of `a` consecutive numbers starting from `b`.

# Answer
> 7 votes
# Python 2, 86

```
f=lambda n,R={1}:n-sum(R)and f(n,R^{[min(R),max(R)+1][n>sum(R)]})or-~sum(map(f,R-{n}))

```

Less golfed:

```
def f(n,R={1}):
    d=sum(R)-n
    if d==0:return (sum(map(f,R-{n}))
    if d<0:return f(n,R|{max(R)+1})
    if d>0:return f(n,R-{min(R)})

```

The idea is to test potential runs of consecutive integers that sum to `n`. The run is stored directly directly as a set `R` rather than via its endpoints.

We check how the sum of the current run compares to the desired sum `n` via their difference.

* If the sum is too large, we cut the smallest element in the run.
* If the sum is too small, we extend the run by making its max bigger by 1.
* If the sum is correct, we recurse, mapping `f` onto the run, summing, and adding 1 for the current node. If the run is `{n}`, we've tried all non-trivial possible sums, stop the recursion by removing `n` first.

Thanks to Sp3000 for saving 3 chars.

# Answer
> 7 votes
# Python 2, 85

I am very proud of this answer because it already takes tens of seconds for n=9, and 5-10 minutes for n=10. In code golf this is considered a desirable attribute of a program.

```
f=lambda n,a=1,d=1:a/n or[f(a)+f(n-a,1+1%d*a)+1/d,f(n,a+d/n,d%n+1)][2*n!=-~d*(2*a+d)]

```

There is also a short-circuiting version that does not take so long and uses the same amount of bytes:

```
f=lambda n,a=1,d=1:a/n or~d*(2*a+d)+n*2and f(n,a+d/n,d%n+1)or f(a)+f(n-a,1+1%d*a)+1/d

```

It may be faster, but at least it exceeds the default recursion limit once n goes a little above 40.

The idea is to do a brute force search for numbers `a` and `d` such that `a + a+1 + ... + a+d == n`, on values between 1 and `n`. The `f(n,a+d/n,d%n+1)` branch of the recursion loops through the `(a, d)` pairs. In the case that the equality is satisfied, I manage to avoid an expensive `map(range(...))` call by splitting into just two branches regardless of how long the sequence is. The numbers `a+1` through `d` are lumped into one call of `f` by setting the `a` parameter so that a different way to split up the sequence can't be used.

# Answer
> 6 votes
# Haskell, ~~76~~ 69 bytes

```
f x=head$[1+sum(map f[y..z])|y<-[1..x-1],z<-[y..x],sum[y..z]==x]++[1]

```

Usage:

```
*Main> map f [1..40]
[1,1,3,1,5,6,5,1,6,7,12,10,12,11,12,1,8,16,14,17,18,18,23,13,21,18,22,23,24,19,14,1,22,20,23,24,31,27,25,26]

```

How it works:

```
[  [y..z] |y<-[1..x-1],z<-[y..x],sum[y..z]==x]

           make a list of lists with all consecutive integers (at least 2 elements)
           that sum up to x, sorted by lowest number, e.g. 9 -> [[2,3,4],[4,5]].

1+sum(map f[...])

           recursively calculate the Fission Number for each list

[...]++[1]

           always append the 1 to the list of Fission Numbers.

head

           take the first element, which is either the Fission Number of the
           longest list or if there's no list, the 1 appended in the step before.

```

# Answer
> 3 votes
# Retina, 66 bytes

```
^|$
,
(`,(1+?)(?=(?<1>1\1)+\D)
$0;
+)`,(1*);1\1
,$1,1$1;
^,|1

.
1

```

Takes input and prints output in unary.

You can put each line in a single file or run the code as is with the `-s` flag. E.g.:

```
> echo -n 1111111|retina -s fission
11111

```

Explanation:

* We keep a comma-delimited list of the numbers to be splitted.
* For every number we take the smallest starting value which can crate a valid splitup and delimit it from the rest with a semicolon.
* If there is a semicolon inside a number we change it to a comma and delimit the next properly sized (length of previous element + 1) part of the number.
* We repeat step 2 and 3 until changes happen.
* We get a comma for every leaf and a semicolon for every inner node plus an extra comma because we started with two comma. So we remove a comma and the numbers' parts (`1`'s) and convert the rest to `1`'s.

The states of the string throughout the process with input `11111111111111 (unary 14)`:

```
,11111111111111,
,11;111111111111,
,11,1;11,1111,11;111;,
,11,1,11;,1111,11,1;11;;,
,11,1,11;,1111,11,1,11;;;,
,,;,,,,;;;,
11111111111

```

Many thanks for @MartinButtner for the help in chat!

# Answer
> 3 votes
## CJam (43 bytes)

```
qi,{):X),_m*{{_)*2/}/-X=}=~\,>0\{~$+}/)}%W=

```

Online demo

I'm sure that I'm missing some tricks with the advanced loops, but this does neatly exploit the CJam property (which has previously annoyed me) that inside a `%` map the results remain on the stack, and can therefore be accessed using `$` with a negative offset.

# Answer
> 2 votes
# Go, 133 bytes

```
func 算(n int)int{Σ:=1;for i:=0;i<n;i++{for j:=0;j<n;j++{if i*i+i-j*j-j==2*n{for k:=j+1;k<=i;k++{Σ+=算(k)};j,i=n,n}}};return Σ}

```

This is my first code golf, sorry if I made any mistakes.

This uses the idea that the fissile "composition" can also be seen as a difference between two sequences of ordered integers. For example take the fissile "composition" for the number 13. It is 6,7. But it can be seen as the sum of integers 1...7 minus the sum of integers 1...5

```
  A: 1 2 3 4 5 6 7  sum = 28
  B: 1 2 3 4 5      sum = 15
A-B:           6 7  sum = 13, which is also 28-15 = 13

```

Recall the formula from Gauss's school days,sum 1...n=(n^2+n)/2. So to find a composition of sequential integers for a given n, we could also say, we are searching for 'end points' p and q along the range 1...n so that (p^2+p)/2 - (q^2+q)/2 = n. In the above example, we would have been searching for 'end points' 5 and 7 because 7^2+7=56/2, 5^2+5=30/2, 56/2-30/2 = 28-15 = 13.

Now there are multiple possible ways to fissile-compose a number, as Martin noted 9 = 2 + 3 + 4 but also 4 + 5. But it seems obvious that the "lowest" starting sequence will also be the longest, because it takes more little-numbers to sum up to a big number than it does medium-sized numbers. (I have no proof unfortunately)

So to find the composition of 9, test every 'end point pair', p and q, iterating both p and q separately from 0 to 9, and test if p^p+p/2 - q^2+q/2 = 9. Or, more simply, multiply the equation by 2, to avoid the division issues of rounding and keep all math in integers. Then we are looking for p and q such that (p^p+p) - (q^q+q) = 9\*2. The first match we find will be the Fissile composition endpoints because, as noted, the lowest group of numbers will also be the longest, and we are searching low-to-high (0 to 9). We break out of the loop as soon as we find a match.

Now the recursive function finds those 'fissile end points' p and q for the given n, then recalls-itself for each of the 'children' in the tree from p to q. For 9, it would find 1 and 4, (20-2=18) then it would re-call itself on 2, 3, and 4, summing the results. For numbers like 4 it simply never finds a match, and so returns '1'. This might be shortenable but this is like my third go program, and I am no recursion expert.

Thanks for reading.

# Answer
> 2 votes
# Husk, 24 bytes

```
LΣΣU¡(fo¬εṁm₁);;
ḟo=¹ΣQḣ

```

Try it online! or Verify first 40 values

## Explanation

```
Function ₁: Get the longest slice of numbers
ḟo=¹ΣQḣ
      ḣ range 1..n
     Q  all subsequences
ḟo      get the first value which satisfies:
    Σ   sum
  =     equals
   ¹    argument?

```

Taking the first value works because Husk orders subsequences lexicographically, and the longest sequence will always be the one which is lexicographically smallest.

```
LΣΣU¡(fo¬εṁm₁);;
              ;; nest the input twice: 24 → [[24]]
                 (conversion to node)
    ¡            iterate infinitely, producing intermediate results
          ṁ      map each node list to
           m₁    it's elements converted to their fissions
          ṁ      and join them
     fo          filter using two functions
       ¬ε        is it not of length <1?
                 (this removes all nodes which cannot be broken down)
   U             cut at first non-unique element
 ΣΣ              join all the nested nodes into one list
L                length

```

# Answer
> 2 votes
# Husk, 12 bytes

```
→ṁ₀-¹ḟo=¹ΣQḣ

```

Try it online!

## Explanation

```
→ṁ₀-¹ḟo=¹ΣQḣ   Input is a number, say n=24.
           ḣ   Range from 1: [1,2,3,..,23]
          Q    All slices in increasing order of last element: [[1],[2],[1,2],[3],..,[1,2,..,24]]
     ḟ         Find first slice for which this is truthy:
      o        Composition of two functions:
         Σ      Sum
       =¹       equals n.
               Result is [7,8,9].
   -¹          Remove first occurrence of n (only relevant when the list is [n]).
 ṁ             Map and sum
  ₀            this function recursively: 12
→              Increment: 13

```

# Answer
> 1 votes
# CJam, ~~40~~ ~~35~~ 33 bytes

```
ri{__,f-_few:+{1b1$=}=|{F}*}:F~],

```

*Thanks to @Optimizer for suggesting `few`, which saved 2 bytes.*

Try it online in the CJam interpreter.

### How it works

```
ri      e# Read an integer from STDIN.
{       e# Define function F(X):
  _     e# Push X.
  _,    e# Push [0 ... X-1].
  f-    e# Subract each from X. Pushes Y := [X ... 1].
  _few  e# Push all overlapping slices of Y of length in Y.
  :+    e# Consolidate the slices of different lenghts in a single array.
  {     e# Find the first slice S such that...
    1b  e#   the sum of its elements...
    1$= e#   equals X.
  }=    e#   Since Y is in descending order, the first matching slice is also the longest.
  |     e# Set union with [X]. This adds X to the beginning of the S if S != [X].
  {F}*  e# Execute F for each element of S except the first (X).
}:F     e#
~       e# Execute F for the input.
],      e# Count the integers on the stack.

```

---
Tags: code-golf, number, sequence, integer-partitions
---


title: Hardy–Ramanujan number generalization

text:
# Question
Title: Hardy–Ramanujan number generalization
\\$1729\\$, known as the Hardy–Ramanujan number, is the smallest positive integer that can be expressed as the sum of two cubes of positive integers in two ways (\\$12^3+1^3=10^3+9^3=1729\\$). Given an integer \\$n\\$ (as input in whatever form is natural to your language of choice) find the smallest positive integer that can be expressed as the sum of two positive integers raised to the \\$n\\$th power in two unique ways. No use of external sources. Fewest characters wins.

Note that this is actually an unsolved problem for \\$n\>4\\$. For those numbers, let your program run forever in search, or die trying! Make it so that if given infinite time and resources, the program would solve the problem.

# Answer
> 3 votes
# APL  ~~45~~  41

```
{⍺←1⋄2≤+/,⍺=(v∘.≤v)×∘.+⍨⍵*⍨v←⍳⌊⍺*.5:⍺⋄⍵∇⍨⍺+1}

```

Shorter but slower version of 41 chars:

```
{⍺←1⋄2≤+/,⍺=(v∘.≤v)×∘.+⍨⍵*⍨v←⍳⍺:⍺⋄⍵∇⍨⍺+1}

```

You can try it online, just paste the function and invoke it with a number:

```
      {⍺←1⋄2≤+/,⍺=(v∘.≤v)×∘.+⍨⍵*⍨v←⍳⌊⍺*.5:⍺⋄⍵∇⍨⍺+1} 2
50
      {⍺←1⋄2≤+/,⍺=(v∘.≤v)×∘.+⍨⍵*⍨v←⍳⌊⍺*.5:⍺⋄⍵∇⍨⍺+1} 3
1729

```

(The algorithm is quite dumb though, don't expect the online interpreter to compute n=4)

The answer for n=2 is 50 = 5² + 5² = 7² + 1² because its a number that "can be expressed as the sum of two squares of positive integers—doesn't say different—in two ways."

If you want to add the distinct clause, just change `(v∘.≤v)` into `(v∘.<v)`, same number of chars, and n=2 becomes 65:

```
      {⍺←1⋄2≤+/,⍺=(v∘.<v)×∘.+⍨⍵*⍨v←⍳⌊⍺*.5:⍺⋄⍵∇⍨⍺+1} 2
65

```

I'm beating GolfScript? Can't be!!

# Answer
> 2 votes
## Ruby, 132

```
n=$*[r=0].to_i;while r+=1
r.times{|a|r.times{|b|next if
a**n+b**n!=r;r.times{|c|r.times{|d|puts(r)if
c**n+d**n==r&&a!=c&&a!=d}}}}end

```

Pass `n` as command line argument. First line to `stdout` is the solution.

Optimized for code-golf, not performance. (Runs correctly. But slow. Does more work than needed.)

---

Here is a longer, slightly faster C program. Same correct but horrible algorithm. (I really need to study more theory!)

Tested for `n`=2, `n`=3.

## C, 234

```
#include<stdio.h>#include<math.h>
r,a,b,c,d;main(n){scanf("%d",&n);while(++r){for(a=0;a<r;++a){for(b=a;b<r;++b){if(pow(a,n)+pow(b,n)!=r)continue;for(c=a+1;c<r;++c){for(d=0;d<r;++d){if(pow(c,n)+pow(d,n)==r&&a!=d)printf("%d\n",r);}}}}}}

```

The C version takes `n` on `stdin`. As above, first line to `stdout` is the solution.

# Answer
> 1 votes
## GolfScript 53

```
1\.{;\).,{}@.@\{?}+%.`{\{+}+%~}+%$.`{\{=}+,,4=}+,.!}do)

```

Input is the initial number on the stack. The number on top of the stack at the end is the answer. I'll explain this in more detail when I get a chance.

E.g.

```
{1\.{;\).,@.@\{?}+%.`{\{+}+%~}+%$.`{\{=}+,,4=}+,.!}do)}:f
2 f -> 25
3 f -> 1729

```

This is pretty slow right now. It also counts `0` (so that 25 is the answer for `n=2`, since `25=5^2+0^2=3^2+4^2`. In order to not count 0, add the 2 characters `(;` after the first `,`

```
1\.{;\).,(;{}@.@\{?}+%.`{\{+}+%~}+%$.`{\{=}+,,4=}+,.!}do)

```

To find that `2 f=65`, since `65=8^2+1^2=5^2+6^2`

# Answer
> 1 votes
## GolfScript (30 chars)

```
:N{).,{)N?}%:P{1$\-P?)},,3<}do

```

Note: this is quite slow, because it does a brute-force search rather than something elegant like a priority queue. The most elegant thing about it is reusing `N` as a lower bound from which to search: this is valid because `1^N + 2^N > N` for all `N`.

Takes `N` on the stack, leaves the corresponding taxicab number on the stack. To take `N` from stdin, prepend `~`.

The version above allows `x^N + x^N` (so for `N=2` it gives `50`). To require adding distinct numbers (giving `65` instead), change the `3` to `4`. To allow `0^N + x^N` (giving `25`), remove the `)` immediately before `N?`.

# Answer
> 0 votes
# Mathematica, 58 chars

A very very slow solution using generating function:

```
0//.i_/;(D[Sum[x^(n^#),{n,1,i}]^2,{x,i}]/.x->0)/i!<4:>i+1&

```

# Answer
> 0 votes
# Jelly, 13 bytes

```
Œċ*§ċ⁸=2
1ç1#

```

Try it online!

This is *very* inefficient for \\$n = 3\\$ and doesn't complete within 60s. However, this can be fixed for an additional 4 bytes

## How it works

```
Œċ*§ċ⁸=2 - Helper link. Takes an integer i on the left and a power n on the right
Œċ       - Yield all pairs, choosing with replacement
  *      - Raise each to the power n
   §     - Take the sum of each
    ċ⁸   - Count the occurrences of i in this list
      =2 - Is this equal to 2?

1ç1# - Main link. Takes a power n on the left
1    - Set the return value to 1
 ç1# - Return the first positive integer, i,
       where running the helper link with
      i on the left and n on the right is True

```

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


title: Alphabet Aerobics

text:
# Question
Title: Alphabet Aerobics
# Challenge

Given a single letter (a-z) as input, output the 2 lines of Blackalicious' *Alphabet Aerobics* that correspond to that letter (ignoring the intro & outro).

---

## Rules

* You may take input by any reasonable, convenient means as long as it's permitted by standard I/O rules.
* Input must either be case insensitive or consistently uppercase or lowercase.
* Output may be a newline separated string or an array/list of two strings.
* Output must be formatted (capitalisation, punctuation, etc.) exactly as it appears in the test cases below.
* Trailing spaces and newlines are not allowed.
* This is so lowest byte count wins.

---

## Test Cases

Each code block below is what should be output for each letter a-z, respectively.

```
Artificial amateurs, aren't at all amazing
Analytically, I assault, animate things

```

```
Broken barriers bounded by the bomb beat
Buildings are broken, basically I'm bombarding

```

```
Casually create catastrophes, casualties
Canceling cats got they canopies collapsing

```

```
Detonate a dime of dank daily doin' dough
Demonstrations, Don Dada on the down low

```

```
Eating other editors with each and every energetic
Epileptic episode, elevated etiquette

```

```
Furious, fat, fabulous, fantastic
Flurries of funk felt feeding the fanatics

```

```
Gift got great, global goods gone glorious
Gettin' godly in his game with the goriest

```

```
Hit em high, hella height, historical
Hey holocaust hints, hear 'em holler at your homeboy

```

```
Imitators idolize, I intimidate
In a' instant, I'll rise in a' irate state

```

```
Juiced on my jams like Jheri curls jockin' joints
Justly, it's just me, writing my journals

```

```
Kindly I'm kindling all kinds of ink on
Karate kick type Brits in my kingdom

```

```
Let me live a long life, lyrically lessons is learned
Lame louses just lose to my livery

```

```
My mind makes marvelous moves, masses
Marvel and move, many mock what I've mastered

```

```
Niggas nap knowing I'm nice, naturally
Knack, never lack, make noise nationally

```

```
Operation, opposition, off not optional
Out of sight, out of mind, wide beaming opticals

```

```
Perfected poem, powerful punchlines
Pummeling Petty powder puffs in my prime

```

```
Quite quaint quotes keep quiet it's Quannum
Quarrelers ain't got a quarter of what we got, uh

```

```
Really raw raps, risin up rapidly
Riding the rushing radioactivity

```

```
Super scientifical sound search sought
Silencing super fire saps that are soft

```

```
Tales ten times talented, too tough
Take that, challengers, get a tune up

```

```
Universal, unique, untouched
Unadulterated, the raw uncut

```

```
Verb vice lord victorious valid
Violate vibes that are vain, make em vanish

```

```
Why I'm all well, what a wise wordsmith just
Weaving up words, weeded up on my workshift

```

```
Xerox, my X-radiation holes extra large
X-height letters and xylophone tones

```

```
Yellow-back, yak mouth, young ones' yaws
Yesterday's lawn yardsale, I yawned

```

```
Zig-Zag zombies, zooming to the zenith
Zero in, zen thoughts, overzealous rhyme ZEA-LOTS!

```

# Answer
> 2 votes
# PHP, 1678 bytes

```
<?=ucfirst($argn),strtr(explode(_,gzinflate(base64_decode("LVXJktw2DL3rK5BTX3qqtPV2tGMn8ZKyHTuJ44uKEiGJFkXKXNTWfH0eNXMYDQiCWB4e0C6o/qoqEnPB0fkj3dgcAhVUaejEYz5kL0y1hWultyO9IeG9iDocSRiFJ3TKB984O7Gh9uZU6ak9G8mS2o1OTK2dW2q5yF5GpSVs4Z/a3f5IrfDJLb05zLvhDQaN8DHpOsfw3hXCB2eXsT5Sl26CqrNfhelY5wNuPQ02IA7shbGLqqmzWovFwxGHCzwIkmpmsj1JYSZ8FJxLmx9Inocxe8XzBREKdUHpry70SkhBl5S5tHdD2t6bApHsqSSWKljn6a5OxKIbgYAkXsuN2JQDh2v2elGal3AlXpS3ko/EmtcCYHBQPyKHwE106oxQfYE/0Ua9H4QJqPOa/aajcygC2fYR2fasAz4MXFJKsCuuvlF92MseANGRBm3bCmcrAcaF0zmFyH5HOFQ5WImCcxoVrgWQSOnD1wCrOjQqEM+4HMYjjQzo8MUB/cUDlHutsj+A7mi17UT0gcY8+GR6o0N6CLRLkGU7O8gzt3ZrZhWKhJOSVqtHTqTJg5qVLDh7Y0gcKPcBFePioDU55Rn5Qa0c+uVDAZCuwOxC80bfxexJq4np7Vgq6qLTnr7bbkJp3y1yyd4iq0RNFQ64SSnOiHl3KgC05OHsTOWbXD4TbYKEG9Abkk9Q5xNdsnc3BJ+uE4VtYXqJ5x5Z4f2UD9LOYBP8IpM1UUpfBog94ujN7RTWtb+gZOTKN8Mye5+gRnPrp5S0RZHBJn9wUW7NRnMuaRZTTfNtZVjSbFewfMaA1dmfSbcTDFpOWoMXKJvuY4EykAUMQ8myUcMgPBmx0GTsHZWlIs0Vj0wRHXLL3hnRTTiCq6R3EXGZjE3IG1AfRs1SQjiSXRbrVdjFvodNgArHKvsQQwLLP7HjvB9QA6BWEiPNYk5zAvYD7LLnLqCFi+X5iO+97KOmJZpu1HmdfYzzvA/wR3B0S/eyxG3fP0O+OIxsE1Vg+hFFHvC1oaaJeYGo0Iq92Z+iMCbO2ad4c6yxeUR+eJoMAbNbKFOKCa97ojuSjmPDqVlO3PG3gMcgX05xSScFgmR/qedRc9GPkJyQyoouqFWFrYlLSb5TbNLOrMhj0ZHnG1aBxy4J2WeMv+nwzCfLXjnQGWHoVKSt520fmqqmgFWJeYBQwRMDwWAthbSNvqS+nDDU3VjB1VAiRWwW1BOiYSTaGLDHVyjFpIWS/odzN4JwfxshsZfLIjlMBaBG4B1DU7a0XkFG6ySEsG8HWisls3+U1WD9qtr6OcdV5M/swHCvWPF+bManucHA3LEgjjuiAl0Hee7w6WcslETy7F8WK4oHnLselthcYAEU+yxDO/kR26sp7c9j0nx9SACDeGmR1MQ/g8Nw3QbOvj487SHMUwiptYD656bxS4AVFy51g1Ts/aHd6byJiebzCcLZDHSpD9DcffZfHUopNjBFC+zy7SZ9ta8j3Jp9ch6+iYEe8cujMHmP1iYKY0oB3yMbdcq+lZYACA50Sh1GTXYtH7kCgm7cMOLfXr94eP/hy+df/gc=")))[ord($argn)%32-1],[in,at,er,al,es,th,ou,on,ic,ar]);

```

Try it online!

# PHP, 1952 bytes

```
<?=ucfirst($argn),explode(_,strtr("rtif8i3 am1eurs, 9en't 1 3l amaz0g
An3yt83ly, I assault, anim1e 50gs_roken b9ri2s b6nded by 5e bomb be1
Build0gs 9e broken, bas83ly I'm bomb9d0g_asu3ly cre1e c1astroph4, casu3ti4
Cancel0g c1s got 5ey canopi4 collaps0g_et71e a dime of dank daily do0' d6gh
Dem7str1i7s, D7 Dada 7 5e down low_10g o52 editors wi5 each and ev2y en2get8
Epilept8 episode, elev1ed etiquette_uri6s, f1, fabul6s, fantast8
Flurri4 of funk felt feed0g 5e fan18s_ift got gre1, glob3 goods g7e glori6s
Gett0' godly 0 his game wi5 5e gori4t_it em high, hella height, histor83
Hey holocaust h0ts, he9 'em holl2 1 y6r homeboy_mit1ors idolize, I 0timid1e
In a' 0stant, I'll rise 0 a' ir1e st1e_u8ed 7 my jams like Jh2i curls jock0' jo0ts
Justly, it's just me, writ0g my j6rn3s_0dly I'm k0dl0g 3l k0ds of 0k 7
K91e k8k type Brits 0 my k0gdom_et me live a l7g life, lyr83ly l4s7s is le9ned
Lame l6s4 just lose to my liv2y_y m0d mak4 m9vel6s mov4, mass4
M9vel and move, many mock wh1 I've mast2ed_iggas nap know0g I'm n8e, n1ur3ly
Knack, nev2 lack, make noise n1i73ly_p21i7, oppositi7, off not opti73
Out of sight, 6t of m0d, wide beam0g opt83s_2fected poem, pow2ful punchl04
Pummel0g Petty powd2 puffs 0 my prime_uite qua0t quot4 keep quiet it's Quannum
Qu9rel2s a0't got a qu9t2 of wh1 we got, uh_e3ly raw raps, ris0 up rapidly
Rid0g 5e rush0g radioactivity_up2 scientif83 s6nd se9ch s6ght
Silenc0g sup2 fire saps 51 9e soft_34 ten tim4 t3ented, too t6gh
Take 51, ch3leng2s, get a tune up_niv2s3, unique, unt6ched
Unadult21ed, 5e raw uncut_2b v8e lord v8tori6s v3id
Viol1e vib4 51 9e va0, make em vanish_hy I'm 3l well, wh1 a wise wordsmi5 just
Weav0g up words, weeded up 7 my workshift_2ox, my X-radi1i7 hol4 extra l9ge
X-height lett2s and xyloph7e t74_ellow-back, yak m65, y6ng 74' yaws
Y4t2day's lawn y9ds3e, I yawned_ig-Zag zombi4, zoom0g to 5e zeni5
Z2o 0, zen 56ghts, ov2ze36s rhyme ZEA-LOTS!",[in,at,er,al,es,th,ou,on,ic,ar]))[ord($argn)%32-1];

```

Try it online!

# Answer
> 2 votes
# Jelly, ~~1052~~ 1050 bytes

```
Oị“>ḤĖwỌḞaỌHtṂþÐṿɼ×ƙ\ṀẸqė\ȧIɓịżʂñ"ḃ⁺ụPE4ĿɲɗŀÐ“¡Ƭ£`BrjŒ⁷ḷḊwṡxṙṀrẇp[ṣİ|ḲṬ⁹ⱮØẎ9ṙ“¡Npḥ8Þṿfeṗẋ⁶ż⁹ẎUøịẹYḄnṁ7ZMnb~pOṙɗḣ(Œøṙụ;ḥ⁸ƇṚỊsẎʋðỴİc⁽Ċ“jɲḷȦẒḲƑzRṀ7¥(æċȧƭḶZṘḄƤ`¬?^ḞƙṾƲq“S£÷ƑØQQʠaƭỴȤ_TỴkɦṛ¥gṄĿ²ṆḍḣṾ2ɓṘ ,“¡ẏŒpḌBḢ/c{ḶẒẠf%nM⁼ṃṫQʂrɱṿ¬4ɱUƘMẸṛŻƬÑ“¡Ɱ1ṣḞµ⁶ỌrTXçYṗ$Ȥẋ-ocñƲ“Ñ³{gøUƤ5]ẈṂȮɦµṂTœỌŒ1/Ẇ~œy2¦æƲȧ€ƝGb“€ẉ⁹6¬ƁṡLæẏẏẹyƈ"ð~¢5_Ɲḣ⁸¶mẇn⁷S9EṃẈM'}0ⱮƁṘṢŀ"¬U#~+ẋV“.¹ṗẸ6æAWḣ⁺tɼZĿẓṃẎ⁽C#ẇṣṡẆX½⁵ỵ€⁼µþȦ/]ȥṪ1“~Ṇẇ{KH9kẉḊẠ¢ỊẇLṖṛPḤ£\tkŻbḍṀPJ¡ȧṚ~QNNØ}ȷṬ“¢jÇṘ4ḥs"⁼ụ¦ṣƭRḤḍḄ$Ẉ9⁷JÞ,ẹƓ3ṡọRƓṃØ×ẠȮḞẹ+hṫ}5[ĿpQƇ(“-G>ɦɼ⁽⁷ĿtḌŒƤifLƥƒẠḄḊɲɲðṭŀRṚ-*ƭṭyƝ(Ṙḣ“¡o|ỤṛỊ iżẈṄʂtÞ⁵x⁵ⱮṫE⁾Ḋ`ıĖẹjp½ḳ{HlọḣoẎ“-ḃ]"ṅỊȮmJỵṖ<)ỴƝD_wȤ⁺ḣ4Mœnu⁴jḅȦ5“©ẆẸṡA*ßx⁹ƤƝO¹ṣUṡ4ė-ƲȤ⁾ḃKhTẸ⁵ḅ-⁻nẊẈ"nwỴß⁼ ɗ“ṡṖḟYIɱẉcẓ⁻tŻƊẎ- ṡİȮgṅƝ×`®*çq¡þ⁹Xe“µÑe0Ƭ¦w$ƊIḶ1\"Ɗø,7v&€/$jṠƝȧḋẓœẆĠc“¢ȷCṁ$°ṬḅṿkėḣC{AịB£AtṅẊRWGḂ2µ9ḌUḣœ⁵mⱮṛ⁷ṙḄḟkẆ¦œ“ƭÆ|ƤBċȦlĊæʠȥiƒ.nżṘḃọṬµṛHⱮW^ṗɲḄbX{ḊṾ3ḃʂ5⁸Ẇẓ)ẹ“¦+8ɼġtịḂZṄ⁽ƙḍṄØM.ƙḞȥU$İ¶r¡ṅ¦3Ṗ£|ƘẎẋḌF÷ẋ⁵“⁹ƓBrḍṆdmṫ©ⱮĠ£ƬƘḟ}ėm9ʂaȧQ÷ɲṭẒḃĿƒỊ,ṛ0¬¿Ɠẉṛr!rƑWĠƭ¢/,⁼ẋ'o“@⁶⁵*ƊÇṡḳƈ/ƒĿĠỌ59KɼẸṅ¦⁶Ġƙ'ƒjḶV¡Pḃ÷Ḷıʋʋḣ³8Ẇs“ȷṪjLZ÷\ĠṫĊɼƒiB½mṾf÷²ṭ³¦ṇḷµœ¢żA¢,Mḷȷ¢æⱮBḥṿḥ£İ“¡EȷịḢ/"µİ3ȧÆỴʂJ]Uƈ{Ṙ]¿þLÞƇe/ẏ⁸ƒ÷œTḃṠyuṫḍ0ɠẸ“¢ṂṖ^YḳN:⁵ẓ⁴⁸ịṚ(NṫCṭḂḷcʂW¦ṅƇẓḷ¥b⁵QSYŀ⁽×»

```

Try it online!

-2 thanks to Jonathan Allan.

Accepts uppercase.

Ironic that ~~only the first three bytes do the real work~~ this program doesn't do any real work, isn't it?

*(tfw when it takes you more than an hour and a half but the result is perfect)*

# Answer
> 1 votes
# Octave, ~~2232~~ ~~2214~~ 2176 bytes

This is an anyonymous function with one huge string hardcoded. The different outputs are separated by a `)` which is then used in `strsplit`.

```
@(n)strsplit("Artificial amateurs (...) overzealous rhyme ZEA-LOTS!",')'){n-96}

```

Try it online!

# Answer
> 1 votes
# SOGL V0.12, ~~1038~~ ~~992~~ 991 bytes

```
Ƨ, "&↑A○f8▓⁵√¹⅟²px∫Uw2ƧΚιx,═hνtεI   =*f⅞aG░‛I:┘'┘‽ΟΨ▲cμ⌠└ιŗY]š⅝&◄⅞▓æCæ»TUΓ↔τ┼≥{_‰ī(*#ģ↑ι<d^¹≈4┘¡ēY←z▓Β6→y⌠$<\ē⁵owD╬#οīλ3ņ┼┘Τ‰±╥μΛš^»KƧ↑³g(y.℮ēDī*█┘E>Ν,±→ø¶ΦKƨS⅝p□D>mƨYψCκΧū╥ō⌠d#╗ΞΡ⅝¬℮te%ΝH↑]ÆυΔ⅔;ΦVO⁹}≈Rōøυ#»→▒⁄w⌡σX╔⁾560yķψ┌λTHļķ:‛ļ:Ι≠sē8□v׀N‽MXσ&⁶┌■ qŗ3C‽Βσ4:Mk{∆▒ΨƧB ;uΡ│ΣV«ŗ╤f⌡E│?æ^νΠ‚H2ō6J>uΓηΣg.R╗|$R‼↑⅞▓^tlM║⁄bd9↔▒┐^Υ|πc⁷ø○āΟ‰□28O╤>V]lαÆøΡω┼|hΦWīūEξ5M¾(Y□ξ§+d¼r▒ģƧ╔ūl■ΡΝž@h∑κ⁸<K▼α≈βī‚⁰⁽N∙!⅟EΜ²█V¾>ΩΒEt═δ√qΛ≡w]ē↔Π⁾ΤXΒ7←η╬¶┌‰RVDΥζVΒ±%÷¤ν↔2Ζ'∙;σ¶▓m⁾ΧqΥ-Ƨυ)┐`θ∫%ψτ:←√′\Ay+‰≡≈ÆMāT┼5eτ^²─κGΘ⁷¾ayψJΘ׀G↓⅜!╔¡┌*«η[░≤k║ŗ«ΘθλΖ○Η▓|ūΕ╚↓ψƧ⅜λO¶μ⁽φ⁹╝╔Z⁽╥Σ←°e+)l$»≡≡m*≡ΞΤ‽|°eŗ)3²žΛ@crO1G└ZPvƧē√≡ΣGα.Σē╝Γ⌠ķa3J¹∞'√ā⅛νξwΤ³░ κē=mģσ↔║¶øø$!π+≡⁵⁴y▒'R≥Æķ+²⁸ēΖ⁄⅛↑↑A▲}<I‼⌠Ξ′╤Β¬C+■∫ο½⅞ΝL,#rΞ█↕ο∫8rL°νnc▼Γ)═^{Φ⅟ε³‛℮lƧčGP¾3◄Ω╗g2FAm׀λ$╗→rWΖ17⅜⌡◄Ič    εt≥q℮′?Æ>┐Τ'ņ¬V→⅔O¼■┼q,‼Β∆∆№ģW■°~¬l⁹ōJbbΘpRņžψ∞ζč╥⁵σθ≈≥⁸¤JÆε5]○¾f׀№ģ§:⅝æT¡⁷ΛΖΨ≤⅝χυ¼š:ÆΛ½±FυΚξū^ΧģƧ'↑KžΨ⁄²I;:χ~Ν(»%γp‽iξC⅝°§Ω≤lδ¦┼}℮≠lχ3╬L¦⁴Ο:gBš╔¶¤:ģMC%u÷⁴┘žYƧΣ0‛⁶0Δ.e_?[─9Νκ⅔⁷}ΦW#_↓δv≥╔Z⅞y4‽ūψqiΖW⁴ƨΡφ%7√‰η²¤š⁷╥⅞5┼/⅜ΔοΦR¾§l¶←∞‰σl1⅛!⁄⁴′νιvk⅓⁴⅛▓ε↑δ@╗ \η!└⅝S0┌²⁰≥¦⁵‘┐Θz,Ww#Θ⁾

```

sub-1000!
Splitting what is a word and what's a character took a while...

Explanation:

```
Ƨ,                 push ", "
   "...‘           push https://gist.github.com/dzaima/3053b8f0222593b8fc4f5cd177ae6dec and replace all `ŗ`s with ", "s
        ┐Θ         split on "|"
          z,W      get inputs index in the lowercase alphabet
             w     gets that item from the array
              #Θ   split on `"` (becuase quote has a single-char push command)
                ⁾  sentence case (uppercases the 1st letters)

```

Try it here! or test all test-cases! (warning: can take a while)

# Answer
> 1 votes
# Husk, 1071 bytes

```
x';!x'%¨AλḞ↕¥βα, »Ṅ'tαt◄l²Za;ṅȦẏ£₇,İ⌊⌋§,ẋZȦṅ´%ḃ⁸ṙż⁸rḃ6ΔbΨËŀ⁶⁶bȦ†;Ḃ⌉säeḃ⁸►,ḃĿ¦İ'mḃβø»)%¥◄£Ẏα¢ȧ×ẏ₅,ŀY4s;Cȧc₇gc₂ȧ≥*εyẏ⁹X∫cẊ←ρ%ż‡ṪeαŸ]1₀fḋ₄k◄ΨdżḊİ'ÿ#G;żδτÖ$,Ḋo¬ḟ×DΦε÷~←ẇ%Eȧ:ØoŸḊ*ωwȧ‼Äd√ṘżẎ₃;£Γφ£⁹&,⁷ŻË□=Ṫ%Γ2u,⌈Λ,£Γü,ẋ=Λ;Flÿ»Jθ Ḟ₂<f¦τḞŻ€εψ=Ȧ%GïΓ≥*Ġτ,⌊⁶lσ₀sżȯ γĿ‰;GẎτ'Ŀ? ¹¬ï gÄmẆwËgø₅t%Hit¦mıḣ,Ż¦Γ□±h,Ïσ»Ψ;Hey«₈öÿ#İ,ä> 'em«‼jαtÿrȮ³₆γ%żẊo¹do∟z,İ¹Ẋz…;Inα'ŸȦṪ,İ'∟l²Ë↕α'≥×8ṡṫ%ȷ;Jd₀¬mΨj≥₄←↕JhĖiŀ?üȷ<θ↕'ȷȷ5;ȷΨJ,¹t's⌋≈ṁm, ẇJγyȷ⌋l%◄/↓İ'mŻ?¹◄lȷk∫θ ΞkΦ;Ka►†ẏ<kγPβ>∫↕γy□<D%←Ṫṁm∟ıα«g←‡,γ₇Ψï◄⌊J$¹sλ≥e;LȦm¦oμW⌋'←ø†oγy£?√%MΨΔ`mφkŀ₂↑ṁØs,□ṡ▲;λ%√ÄdṁØ,Ṁẏ□KΦωζİ've⁶2₃%ȷNgasη@p⌋Ẇηİ'mẏ[ ,£γa;γŻK, ṅṘ←<,ṁ^□ȯ,ṄOṅ◄%ẎO,₀pΠΦ,Öf⁰t⁷ṗΦ;üt₀fŻḣg,øo₀fṁ%,ωχẎ₈Ġ£ρŀs%⁶ḟ3₉□m,λḟ>Ẏπ±⁷¬;Püψ⁷~ÿ/†ẇṖ,Γ%Ṗ¹¬mΨpṘβ%₂Q₈",□□‰Π<□□"¹t'sμQψ⌋n;⌊Q→Ėsα↕'t≥*α□ṙ_₀fωζẇe≥*, uh%γ⌊lrȧwrȧφ,Ÿṙİüp⁷¿δ;⌋□1ε□↔₁ḋ₂¥ωτ%üṗṠ₂ŀ‡{⁵θ∂ä#żġḢ;ẋ≥lṗ€⌈β⁵ȧφȦ…äeḞJs%Tλ$₂nïż◄/…,θσ□ö↔;ȧΣȦ…,ŀ½¦Ės,ġṪαŸ≥ üp%λ"⁵,ÿÜÜ,żμX;ÿ₈U⌋₇/, Ë►ω²¥Ξ%⁸βV√[⁷Övȷ⌈⁰ẏ←d;£×V√↕₆₅Ȧ…äeż▼ ,ṁ^¦m□▼´%Ẇ¿İ'm◄lẆ⌉,ωζαẇ≈eÖrżΔ#⌋≈;ẇψ▼üpẇ., wẊ)ρ ΦγyȮk⌋⌈≤%⌋XΞ, mΨX-żσ↕«½*Ξτa←⁴;X-hġ`λƒζȦ xy⌊₂₉£Yø%«ωŀ-₆k,γ⌋ẏ«Ḣu, γμȯε'ÿ?ws;ŸΨY'sĿwnŸψ⌐Ȧ¦,İ¥;ω%Zig-ZagŀΓḂs, zo₂σ†oεŻΩh;żZr↕,ΩΩŻ⁰↔s,√oż◄↑Ξ¿ψZEA-LOTS!¨-96ṁ½

```

Try it online!

Another lazy answer using built in compression.

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


title: Prime Wednesdays

text:
# Question
Title: Prime Wednesdays
# Prime Wednesdays

Your task is to count the number of Wednesdays that fall on a prime day of the month in a particular year. For instance, `7-13-16` is a prime Wednesday. For consistency use the Gregorian calendar for all dates.

## Input

The input to your program/function will be a year (eg `2016`) and is flexible. The year will be an integer between **1912** and **2233** inclusive.

## Output

The output is also flexible and should be the number of prime Wednesdays (eg `18`).

## Scoring

This is so shortest code in bytes wins!

## Test Cases

> input -\> output
> --------------------
> 1912 -\> 19
> 1914 -\> 16
> 1984 -\> 17
> 1996 -\> 19
> 2063 -\> 19
> 2150 -\> 16
> 2199 -\> 18
> 2233 -\> 18

# Answer
# MATL, ~~38~~ ~~36~~ 34 bytes

```
FT+"@llI$YO]q&:t8XO!s9\~)9#1$ZOZps

```

Try it online! Or verify all test cases (takes a few seconds).

### Explanation

```
FT+     % Input year implicitly. Add [0 1] element-wise. Gives array with input year
        % and next year
"       % For each of those two years
  @     %   Push year
  ll    %   Push 1 twice. This indicates January 1.
  I$YO  %   Convert year, month, day to serial date number
]       % End for each. We now have the serial date number for January 1 of the input
        % year and that of the following year
q       % Subtract 1 to the latter, to yield December 31 of the input year
&:      % Inclusive range between those two numbers. This gives an array of serial date
        % numbers for the whole input year
t       % Push another copy of that array
8XO     % Convert to date string with format 8. This gives weekday as "Mon", "Tue" etc.
        % The result is a 3-column 2D char array, where each row is a day
!s      % Transpose, sum of each column. 'Wed' gives 288 (sum of ASCII codes)
9\~     % 288 gives 0 modulo 9, and is the only weekday to do so. So we compute modulo 9
        % and negate. This gives true for Wednesdays, false for the rest
)       % Apply as logical index into the array of serial date numbers
9#1$ZO  % Array of month numbers corresponding to those serial date numbers
Zp      % Array that contains true for prime numbers, false for the rest
s       % Sum of array. Display implicitly

```
> 7 votes

# Answer
# Python 2, ~~95~~ ~~93~~ ~~68~~ 67 bytes

```
lambda y:0x10ea2c8dbb06c5619/5**((y+((y-22)/99-y/2002)*16)%28)%5+16

```

*Thanks to @Josay for golfing off 1 byte!*

Test it on Ideone.
> 20 votes

# Answer
# Brain-Flak, ~~6588~~, ~~2310~~, ~~2308~~, 2290 bytes

First things first, I did not write nearly 100% of this program, which is probably evidenced by the enormous size of the program. Most of this code was written by my own Brain-Flak golfing algorithm. Along with an additional python script I wrote to prompt it in the right direction.

Try it online!

```
({}<(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((()()())){}{}){})[()()])())()())[()()()()])())()()())[()()()])()())[()()()])()())[()]))())()())[()()()()])())()()())[()()()])())())[()])[()])()()())[()()])()())[()()()()])()())())[()()])())()())[()()()()])()())[()])()()())[()()])()())[()()()()])()())())[()()])())()())[()()()()])())()()())[()()()])()())[()()()])()())[()]))())()())[()()()()])())()()())[()()()])())())[()])[()])()()())[()()])()())[()()()()])()())())[()()])())()())[()()()()])())()()())[()()()])()())[()()()])()())[()]))())()())[()()()()])())()()())[()()()])())())[()])[()])()()())[()()])()())[()()()()])()())())[()()])())()())[()()()()])())()()())[()()()])()())[()()()])()())[()]))())()())[()()()()])())()()())[()()()])())())[()])[()])()()())[()()])()())[()()()()])()())())[()()])())()())[()()()()])())()()())[()()()])())()())[()()()()])()())())[()()])())()())[()()()()])())()()())[()()()])()())[()()()])()())[()]))())()())[()()()()])())()()())[()()()])())())[()])[()])()()())[()()])()())[()()()()])()())())[()()])())()())[()()()()])())()()())[()()()])()())[()()()])()())[()]))())()())[()()()()])())()()())[()()()])())())[()])[()])()()())[()()])()())[()()()()])()())())[()()])())()())[()()()()])())()()())[()()()])()())[()()()])()())[()]))())()())[()()()()])())()()())[()()()])())())[()])[()])()()())[()()])()())[()()()()])()())())[()()])())()())[()()()()])())()()())[()()()])()())[()()()])()())[()]))())()())[()()()()])())()()())[()()()])())())[()])[()])()()())[()()])()())[()()()()])()())())[()()])())()())[()()()()])())()()())[()()()])()())[()()()])()())[()]))())()())[()()()()])())()()())[()()()])())())[()])[()])()()())[()()])()())[()()()()])()())())[()()])())()())[()()()()])())()()())[()()()])()())[()()()])()())[()]))())()())[()()()()])())()()())[()()()])())())[()])[()])()()())[()()])()())[()()()()])()())())[()()])())()())[()()()()])())()()())[()()()])()())[()()()])()())[()]))())()())[()()()()])())()()())>[(((((((((()()()()())){}{}){}){}){}){}[()]){}){}){}]){({}[()]<{}>)}{}({}<{{}}>)

```

While this program is quite long for code golf, it really is decently short for Brain-Flak. Currently the world record for integer division is over 1000 bytes.

# Explanation

The algorithm is quite simple. Because there is a limited number of years available (321) it simply pushes the answers in reverse order under the input and uses a lookup algorithm to find the correct answer. While hardcoding all 321 possibilities may seem rather inefficient with an task as complex as this one and a language as esoteric as brain-flak it may very well be the best solution. (I plan to find out in the coming week).

Since most of the 321 numbers are about 18 on average and they differ by very little from year to year instead of pushing all the numbers individually I push the first year (2233) normally and then just duplicate and change the value a bit for each year after. This way instead of paying to push ~18 for all 321 years I only pay to push ~2 for every year.

Once all the answers have been pushed it subtracts 1912 from the input `({}[(((((((((()()()()())){}{}){}){}){}){}[()]){}){}){}])` (This may be suboptimal, I rewrote the optimizer to skip certain values that I believed would not be optimal because hardcoding numbers is a super-exponential process and running it to completion may have taken a few days).

It then subtracts one from the first element and pops the second element until the result reaches zero, `{({}[()]<{}>)}`.

It pops the zero, `{}` and all the elements below the top element `({}<{{}}>)`.
> 13 votes

# Answer
# Bash + common utilities, 39

```
ncal $1|grep W|factor|egrep -c ': \S+$'

```

Takes the input year as a command-line parameter. Typically outputs messages like this to STDERR - I think this is legal as per this meta-answer:

```
factor: ‘We’ is not a valid positive integer

```

If you want to explicitly suppress the STDERR output then you can do this instead for a score of **43**:

```
ncal $1|grep W|factor 2>-|egrep -c ': \S+$'

```
> 7 votes

# Answer
# Octave, 86 bytes

This is *not* fast, by any stretch. But that's not really the goal of a code golf, is it?

```
function r=p(y)r=0;for(i=698346:7:815953)d=datevec(i);r+=d(1)==y*isprime(d(3));end;end

```

Octave can track dates by "date number" - number of days elapsed where Jan 1, 0 is day 1. By this measure, Jan 3, 1912 (the first Wednesday in our set) is day 698,346. Start there, and iterate through every 7th day (all Wednesdays) until the end of 2233, and add 1 if the year is the target year AND the month-day is prime.
> 6 votes

# Answer
# Python 2.7, ~~166~~, ~~165~~, 150 bytes

```
from datetime import*
y=input()
d,c=date(y,1,1),0
while d.year==y:n=d.day;c+=n>1<2==d.weekday()>0<all(n%x for x in range(2,n));d+=timedelta(1)
print c

```

There is certainly room for improvement here. I am rather new to golfing in python. This uses the `datetime` module. It loops through all the days in the year adding one to an accumulator if it fits the criterion. It then prints the result. Most of the heavy lifting is in the module so the code can be quite slim.

One byte saved thanks to Morgan Thrapp and 15 bytes saved by Pietu1998.
> 5 votes

# Answer
# J, 44 bytes

```
+/@(valdate*3=weekday)@,.&(,/(>:,"0/p:)i.12)

```

I just discovered that J has builtins for date manipulation.

### Usage

Extra commands are used for formatting multiple input/output.

```
   f =: +/@(valdate*3=weekday)@,.&(,/(>:,"0/p:)i.12)
   (,.f"0) 1912 1914 1984 1996 2063 2150 2199 2233
1912 19
1914 16
1984 17
1996 19
2063 19
2150 16
2199 18
2233 18

```

### Explanation

```
+/@(valdate*3=weekday)@,.&(,/(>:,"0/p:)i.12)  Input: year
                                       i.12   The range [0, ..., 11]
                              >:              Increment each to get the months [1, ..., 12]
                                    p:        Get the first 12 primes [2, ..., 37]
                                ,"0/          Make a table between each month and prime
                           ,/                 Join the rows
                       ,.&                    Prepend the year to each
                                              The date format is YYYY MM DD
            3=weekday                         Check if each date occurs on Wednesday
    valdate*                                  and is a valid date
+/@                                           Count the number of true values and return

```
> 3 votes

# Answer
## PowerShell v3+, ~~99~~ 95 bytes

Brute force approach --

```
param($y)(1..12|%{$m=$_;2,3,5,7,11,13,17,19,23,29,31|?{(date "$m-$_-$y").DayofWeek-eq3}}).Count

```

Takes input `$y`, loops from `1` to `12`, stores the month temporarily into `$m`, then loops over every prime from `2` to `31`. For each of those, we construct a `Get-Date` of that particular day, then select only those with `DayOfWeek` `-eq`ual to `3` (i.e., Wednesday). Encapsulates that all in a parens to formulate an array, and takes the `.Count` thereof.

---

Alternatively, mathematical approach --

### PowerShell v3+, 105 bytes

```
param($y)(16,19,18,20,16,18,19)[($a=(date "1-1-$y").DayOfWeek)]+(1,-3,0,1,2)[$y%5]*($a-in0,2,3,4)*!($y%4)

```

Winds up being just a hair longer than the brute force approach, but I'm including it here since it may be beneficial to others.

Again takes input `$y` as the year. This time we're performing strictly math operations based on the first day of the year. We first calculate what day of the week that is, and store that into `$a` for use later. That indexes into the first array, which gets us the number that is usually correct. We have to add to that a second index based on whether it's a potential leap year, whether it's a Sunday, Tuesday, Wednesday, or Thursday, and based on what the year is.

This is based on the following observation. The first column is what day of week January 1st is, the second is the usual output. Unless the year is one of the middle numbers, then it's the number in parens instead. The final column describes how the %5 indexing works.

```
Jan-1 -> #  ... Except if $y=       (then it's this number) | $y % 5 =
Sun   -> 16 ... 1928 1956 1984 etc. (17)                    |    3
Mon   -> 19
Tue   -> 18 ... 1924 1952 1980 etc. (20)                    |    4
Wed   -> 20 ... 1936 1964 1992 etc. (17)                    |    1
Thur  -> 16 ... 1920 1948 1976 etc. (17)                    |    0
Fri   -> 18
Sat   -> 19

```

---

Note: Both of these assume `en-us` is the current PowerShell setting for culture/date information. The date formatting and `DayOfWeek` number may need to be adjusted accordingly for other culture variants.
> 1 votes

# Answer
# Ruby, 83 + 15 ( `-rdate -rprime` flags) = 98 bytes

Try it online! (Imported modules are inlined because idk if I can use flags in repl.it)

```
->y{k=0;Prime.each(31){|d|k+=(1..12).count{|m|Date.new(y,m,d).wday==3 rescue p}};k}

```
> 1 votes

# Answer
# R, ~~149~~ 147 bytes

```
y=function(x){s=strftime;b=ISOdate
a=seq(b(x,1,1),t=b(x,12,31),b='d')
length(a[s(a,'%u')==3&trimws(s(a,'%e'))%in%c(2,3,5,7,11,13,17,19,23,29,31)])}

```

Test it on Ideone.
> 1 votes

# Answer
## Batch, 248 bytes

```
@set/ad=0,l=1,n=20
@for /l %%i in (1913,1,%1)do @set/ad=(d+l+1)%%7,l=!(%%i%%4)-!(%%i%%100)+!(%%i%%400)
@goto %l%%d%
:03
:06
@set/an-=1
:12
:13
:16
@set/an-=1
:01
:04
:14
@set/an-=1
:00
:05
:10
:15
@set/an-=1
:02
:11
@echo %n%

```

Explanation: `d` is the day of the week, with `0` for Monday, which is conveniently 1st Jan 1912. `l` is a flag for whether the year is a leap year, `1` for 1912. We then loop through from 1913 to the input year, updating the day of week and recalculating the leap year flag as we go. Finally we use the leap year flag and day of week to index into what is effectively a big switch statement to determine `n`, the number of prime Wednesdays. Setting `n` to 20 and decrementing it with fall though is cheaper than using flow control logic, but the upshot is that if the 1st of January of a non-leap year is Thursday or Sunday then there are 16 prime Wednesdays and so on for the other cases.
> 1 votes

# Answer
# JavaScript ES6 ~~206~~ ~~203~~ ~~199~~ ~~197~~ ~~195~~ ~~183~~ ~~182~~ 179

Not the shortest, but best I can do for now... Golfing suggestions welcome...

```
p=n=>--d-1?n%d&&p(n):1;v=Date;D=(x,y)=>new v(x.setDate(x.getDate()-y));W=a=>eval('for(Z=0,z=D(w=new v(a,11,31),(w.getDay()+4)%7);z>new v(a,0,1);)Z+=~~p(d=z.getDate()),z=D(z,7);Z')

```

Changes:

1. altering ternary component from: `3>=x?3-x:10-x` to `6-(x+10)%7`, saving: 3 Changes to declaration locations;
2. merged `x=w.getDay();z=D(w,6-(x+10)%7)` to `z=D(w,6-(w.getDay()+10)%7)`, saving: 4
3. shifted `Z=0` from `for` loop to Date declaration and pushed `z=D(w,6-(x+10)%7)` into `for` loop to tidy up, saving: 2
4. shifted `w=new Date(a,Z=0,1)` declaration into `for` loop, merging with existing `w` declaration, saving: 2
5. rewriting the prime finding function to a prime testing function, saving: 12
6. changing `+!!` to `~~` to reduce and still convert `p(d=1)` from `NaN` to `0`, allowing Prime Test function to still work, saving: 1
7. Moved all extra functions out of main calling function `W`, redefined `for` loop - going in reverse from 31st Dec, writing `Date` object out as a separate variable, then re-wrote `for` loop into `eval` call; saving 3.

@PandaCoder, I'm catching up to you, mate!
> 1 votes

# Answer
# JavaScript ES6, ~~187~~ ~~182~~ ~~181~~ 179 bytes

**179** *Swapped in a for-loop for the while-loop*

```
z=y=>{D=new Date("1/3/1912");N=0;a=()=>D.getFullYear();b=()=>D.getDate();c=()=>D.setDate(b()+7);for(;a()<=y;c())N+=y-a()?0:-1<[2,3,5,7,11,13,17,19,23,29,31].indexOf(b());return N}

```

**181** *Compacted the ternary*

```
z=y=>{D=new Date("1/3/1912");N=0;a=()=>D.getFullYear();b=()=>D.getDate();c=()=>D.setDate(b()+7);while(a()<=y){N+=y-a()?0:-1<[2,3,5,7,11,13,17,19,23,29,31].indexOf(b());c()}return N}

```

**182** *Combined the two loops*

```
z=y=>{D=new Date("1/3/1912");N=0;a=()=>D.getFullYear();b=()=>D.getDate();c=()=>D.setDate(b()+7);while(a()<=y){N+=a()==y?-1<[2,3,5,7,11,13,17,19,23,29,31].indexOf(b()):0;c()}return N}

```

**187**

```
z=y=>{D=new Date("1/3/1912");N=0;a=()=>D.getFullYear();b=()=>D.getDate();c=()=>D.setDate(b()+7);while(a()<y)c();for(;a()==y;c())N+=-1<[2,3,5,7,11,13,17,19,23,29,31].indexOf(b());return N}

```
> 1 votes

# Answer
# Groovy, 126

Groovy doesn't have prime number validation, had to build that too.

```
{n->p={x->x<3||(2..Math.sqrt(x)).every{x%it}};(new Date("1/1/$n")..new Date("12/31/$n")).collect{it[7]==4&&p(it[5])?it:0}-[0]}

```
> 1 votes

# Answer
# APL (Dyalog Extended), 39 bytes

```
{+/1⍭2⊃¨¯1⎕DT{⍵/⍨3=7|⍵}⊃↓∘⍳/1⎕DT,¨⍵+⍳2}

```

Try it online!

Just *that* much away from MATL.

`∆DT` is polyfilled in this answer because it isn't available on tio.

It was created by Adám(I simply cannot thank him enough for his help).

## Explanation

```
{+/1⍭2⊃¨¯1⎕DT{⍵/⍨3=7|⍵}⊃↓∘⍳/1⎕DT,¨⍵+⍳2}
                                  ⍵+⍳2  year and year+1
                            1⎕DT,¨      convert each of those to their day numbers
                        ↓∘⍳/            get inclusive range between them
                       ⊃                remove nesting
             {⍵/⍨3=7|⍵}                 Wednesday filter:
                 3=7|⍵                  7 mod <daynum> always returns day of the week (starting on Monday)
              ⍵/⍨                       filter dates by that bitmask
        ¯1⎕DT                           convert the filtered day numbers to mm dd yy
     2⊃¨                                pick 2nd element of each(dd)
   1⍭                                   check if prime(1 or 0)
 +/                                     sum the array

```
> 1 votes

# Answer
# Japt `-x`, 20 bytes

```
366õÈ=ÐUTX)f j «3aXe

```

Try it
> 1 votes

---
Tags: code-golf, primes, date, counting
---


title: Longest arithmetic subsequence

text:
# Question
Title: Longest arithmetic subsequence
Given a non empty finite sequence of integers, return an arithmetic subsequence of maximal length.

If there are multiple of the same maximal length, any of them can be returned.

### Definitions:

An *arithmetic* sequence is a sequence \\$a(1),a(2),a(3),a(4),...\\$ such that there is a constant \\$c\\$ such that \\$a(m+1)-a(m) = c\\$ for all \\$m\\$. In other words: The difference between two subsequent terms is constant.

Given a sequence \\$b(1),b(2),b(3),b(4),...\\$ a *subsequence* is a sequence \\$b(s(1)),b(s(2)),b(s(3)),b(s(4)),...\\$ where \\$1 \<= s(1)\\$ and \\$s(m) \< s(m+1)\\$ for all \\$m\\$. In other words: Take the original sequence and remove as many entries as you want.

### Examples

```
Input                     Output
[4,1,2,3,6,5]             [1,3,5] or [1,2,3]
[5,4,2,-1,-2,-4,-4]       [5,2,-1,-4]
[1,2,1,3,1,4,1,5,1]       [1,1,1,1,1] or [1,2,3,4,5]
[1]                       [1]

```

Some longer test cases:

```
Length: 25
Input: [-9,0,5,15,-1,4,17,-3,20,13,15,9,0,-6,11,17,17,9,26,11,5,11,3,16,25]
Output: [15,13,11,9] or [17,13,9,5]

Length: 50
Input: [35,7,37,6,6,33,17,33,38,30,38,12,37,49,44,5,19,19,35,30,40,19,11,5,39,11,20,28,12,33,25,8,40,6,15,12,27,5,21,6,6,40,15,31,49,22,35,38,22,33]
Output: [6,6,6,6,6] or [39,33,27,21,15]

Length: 100
Input: [6,69,5,8,53,10,82,82,73,15,66,52,98,65,81,46,44,83,9,14,18,40,84,81,7,40,53,42,66,63,30,44,2,99,17,11,38,20,49,34,96,93,6,74,27,43,55,95,42,99,31,71,67,54,70,67,18,13,100,18,4,57,89,67,20,37,47,99,16,86,65,38,20,43,49,13,59,23,39,59,26,30,62,27,83,99,74,35,59,11,91,88,82,27,60,3,43,32,17,18]
Output: [6,18,30,42,54] or [8,14,20,26,32] or [46,42,38,34,30] or [83,63,43,23,3] or [14,17,20,23,26] or [7,17,27,37,47] or [71,54,37,20,3]

```

### Background

I got this idea when I recalled the Green-Tao-Theorem from 2004, which states that the sequence of primes contains finite arithmetic sequences of arbitrary length.

# Answer
# Jelly, 8 bytes

```
ŒPIE$ÐfṪ

```

Try it online! or verify all test cases.

### How it works

```
ŒPIE$ÐfṪ  Main link. Argument: A (list of integers)

ŒP        Powerset; generate all sublists of A, sorted by length.
     Ðf   Filter the powerset by the link to the left:
    $       Combine the two atoms to the left into a monadic link.
  I           Compute all increments.
   E          Test whether they're all equal.
          This returns all arithmetic subsequences, sorted by length.
       Ṫ  Tail; extract the last sequence.

```
> 5 votes

# Answer
## Pyth, ~~12~~ 11 bytes

```
ef!P{-VTtTy

```

Test suite.

```
          y  powerset of implicit input, generate all subsequences
ef       T   find the last subsequence (sorted increasing in length) where...
       Tt      bifurcate over tail, giving [1,2,3,4,5] [2,3,4,5]
     -V        vectorize over -, giving differences of each consecutive pair
    {          dedup (remove duplicate elements)
   P           pop, resulting in [] if all differences were equal
  !            boolean not, resulting in True if all differences were equal

```

Thanks to @LeakyNun for a byte!
> 2 votes

# Answer
# MATL, ~~19~~ ~~18~~ ~~17~~ ~~16~~ 18 bytes

*1 byte saved (and 2 bytes added back) thanks to Luis!*

```
"GX@XN!"@dun2<?vx@

```

A fairly naive approach which brute force checks all ordered permutations of the input. Obviously this can take a while for longer sequences. To save a byte, I have started with the smallest sub-sequences (length = 1) and worked up to the larger sequences (length = N).

**Try it Online!**

**Explanation**

```
                % Impilicitly grab input array (N)
"               % For each value in this array
    G           % Explicitly grab the input
    X@          % Loop index, will be [1, 2, ... length(N)] as we iterate
    XN          % Determine all permutations of k elements (nchoosek). The output is
                % each k-length permutation of the input as a different row. Order doesn't
                % matter so the result is always ordered the same as the input
    !           % Take the transpose so each k-length permutation is a column
    "           % For each column
        d       % Compute the difference between successive elements
        un      % Determine the number of unique differences
        2<?     % If there are fewer than 2 unique values
            vx  % Vertically concatenate everything on the stack so far and delete it
            @   % Push the current permuatation to the stack
                % Implicit end of if statement
                % Implicit end of for loop
                % Implicit end of for loop
                % Implicitly display the stack

```
> 2 votes

# Answer
# Husk, 6 bytes

```
►oEẊ-Ṗ

```

Try it online!

## Explanation

The return value of `E` is useful here for getting the longest list that satisfies a condition.

```
►oEẊ-Ṗ   Implicit argument: a list.
     Ṗ   List of all its subsequences.
►        Find one that maximizes:
 o        Composition of two functions:
   Ẋ       1. Apply to adjacent elements:
    -         Subtraction.
  E        2. Are all elements equal?
              Returns length+1 if they are, 0 if not.

```
> 2 votes

# Answer
# Python 2, ~~124~~ ~~115~~ ~~98~~ 97 bytes

```
p=[[]]
for n in input():p+=[x+[n][:2>len(x)or n-x[-1]==x[1]-x[0]]for x in p]
print max(p,key=len)

```

Very slow and memory intensive. Test it on Ideone.

### Alternate version, 98 bytes

```
p={()}
for n in input():p|={x+(n,)[:2>len(x)or n-x[-1]==x[1]-x[0]]for x in p}
print max(p,key=len)

```

This completes all test cases instantly. Test it on Ideone.
> 1 votes

# Answer
# Pyth checkout 8593c76, March 24th, 10 bytes

```
efq-VTtT)y

```

This is exactly the same as Doorknob's answer, except that back in march, there was a 2 byte function (`q ... )`) which checked whether all of the elements of a list were the same, which is the same as `!P{`, which is the best you can do currently.
> 0 votes

# Answer
## JavaScript (ES6), 157 bytes

```
a=>{for(m=i=0,l=a.length;i<l;i++)for(j=i;++j<l;)for(t=n=a[k=i],c=0;k<l;k++)a[k]==t&&(t+=a[j]-n,++c>m)?q=a[m=c,p=n,j]-n:q;return a.slice(-m).map(_=>(p+=q)-q)}

```

Almost 20 times longer than the Jelly answer... Ungolfed:

```
function subsequence(a) {
    var max = 0;
    for (var i = 0; i < a.length; i++) {
        for (var j = i + 1; j < a.length; j++) {
            var target = a[i];
            var count = 0;
            for (var k = i; k < a.length; k++) {
                if (a[k] == target) {
                    count++;
                    target += a[j] - a[i];
                    if (count > max) {
                        max = count;
                        start = a[i];
                        step = a[j] - a[i];
                    }
                }
            }
        }
    }
    var result = new Array(max);
    for (var i = 0; i < max; i++) {
        result[i] = start + step * i;
    }
    return result;
}

```
> 0 votes

# Answer
# Japt `-h`, 13 bytes

```
à ñÊkÈän än d

```

Try it
> 0 votes

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


title: Find the sets of sums

text:
# Question
Title: Find the sets of sums
I've enjoyed reading this site; this is my first question. Edits are welcome.

Given positive integers \\$n\\$ and \\$m\\$, compute all ordered partitions of \\$m\\$ into exactly \\$n\\$ positive integer parts, and print them delimited by commas and newlines. Any order is fine, but each partition must appear exactly once.

For example, given \\$m=6\\$ and \\$n=2\\$, possible partitions are pairs of positive integers that sum to 6:

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

```

Note that `[1,5]` and `[5,1]` are different ordered partitions. Output should be exactly in the format above, with an optional trailing newline. (EDIT: The exact order of the partitions does not matter). Input/output are via standard code-golf I/O.

Another example output for \\$m=7, n=3\\$:

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

```

The smallest code in bytes after 1 week wins.

Again, please edit if necessary.

## Addendum:

@TimmyD asked what size of integer input the program has to support. There is no hard minimum beyond the examples; indeed, the output size increases exponentially, roughly modelled by: lines = \\$e^{(0.6282 n - 1.8273)}\\$.

```
n | m | lines of output
2 | 1 | 1
4 | 2 | 2
6 | 3 | 6
8 | 4 | 20
10 | 5 | 70
12 | 6 | 252
14 | 7 | 924
16 | 8 | 3432
18 | 9 | 12870
20 | 10 | 48620
22 | 11 | 184756
24 | 12 | 705432

```

# Answer
# Pyth, 14 bytes

```
V^SQEIqsNQj\,N

```

Try it online: Demonstration or Test Suite

### Explanation:

```
V^SQEIqsNQj\,N   implicit: Q = first input number
  SQ             create the list [1, 2, ..., Q]
    E            read another number
 ^               cartesian product of the list
                 this creates all tuples of length E using the numbers in SQ
V                for each N in ^:
     IqsNQ          if sum(N) == Q:
          j\,N         join N by "," and print

```
> 8 votes

# Answer
## Python 3, 77 bytes

```
def f(n,m,s=''):[f(i,m-1,',%d'%(n-i)+s)for i in range(n)];m|n or print(s[1:])

```

A recursive function that builds each output string and prints it. Tries every possible first number, recursing down to find a solution with the corresponding decreased sum `n`, and one fewer summand `m`, and a string prefix `s` with that number. If both the required sum and the number of terms are equal 0, we've hit the mark, so we print the result, cutting off the initial comma. This is checked as `m|n` being 0 (Falsey).

79 chars in Python 2:

```
def f(n,m,s=''):
 if m|n==0:print s[1:]
 for i in range(n):f(i,m-1,','+`n-i`+s)

```
> 6 votes

# Answer
# CJam, 22 bytes

```
q~:I,:)m*{:+I=},',f*N*

```

Try it online in the CJam interpreter.

### How it works

```
q~                      Read and evaluate all input. Pushes n and m.
  :I                    Save m in I.
    ,:)                 Turn it into [1 ... I].
       m*               Push all vectors of {1 ... I}^n.
         {    },        Filter; for each vector:
          :+I=            Check if the sum of its elements equals I.
                        Keep the vector if it does.
                ',f*    Join all vectors, separating by commas.
                    N*  Join the array of vectors, separating by linefeeds.

```
> 4 votes

# Answer
## Pyth, ~~20~~ 18 bytes

*-2 bytes by @Dennis!*

```
jjL\,fqQlT{s.pM./E

```

This takes `n` as the first line of input, and `m` as the second.

Try it here.
> 3 votes

# Answer
## Haskell, 68 bytes

```
n#m=unlines[init$tail$show x|x<-sequence$replicate n[1..m],sum x==m]

```

Usage example:

```
*Main> putStr $ 2#6
1,5
2,4
3,3
4,2
5,1

```

How it works: `sequence $ replicate n list` creates all combinations of `n` elements drawn form `list`. We take all such `x` of `[1..m]` where the `sum` equals `m`. `unlines` and `init$tail$show` produce the required output format.
> 3 votes

# Answer
# Dyalog APL, 33 bytes

```
{↑1↓¨,/',',¨⍕¨↑⍺{⍵/⍨⍺=+/¨⍵},⍳⍵/⍺}

```

Takes `m` as left argument, `n` as right argument.

Almost half (between `{` and ) is for the required formatting.
> 3 votes

# Answer
# Python 3, 112

```
from itertools import*
lambda m,n:'\n'.join(','.join(map(str,x))for x in product(range(m),repeat=n)if sum(x)==m)

```

I haven't managed a 1 liner in a while. :)
> 2 votes

# Answer
## Mathematica, 65 bytes

```
StringRiffle[Permutations/@#~IntegerPartitions~{#2},"
","
",","]&

```

`IntegerPartitions` does the task. The rest is just to order the tuples and format the result.
> 2 votes

# Answer
# Jelly, 11 bytes

```
ṗS=¥Ƈ⁸j€”,Y

```

Try it online!

Boo to restrictive output formats. +5 bytes because of that.

## How it works

```
ṗS=¥Ƈ⁸j€”,Y - Main link. Takes m on the left and n on the right
ṗ           - Take the cartesian power of m and n
              This returns all lists of length n consisting of the integers 1,...,m
   ¥Ƈ       - Keep those where the following is true:
 S          -   Their sum...
  =         -   Is equal to...
     ⁸      -   m
        ”,  - Yield ","
      j€    - Join each sublist by ","
          Y - Join by newlines

```
> 2 votes

# Answer
## Python 2.7, ~~174~~ ~~170~~ 152 bytes

Fat answer. At least it's readable :)

```
import sys,itertools
m=int(sys.argv[1])
for k in itertools.product(range(1,m),repeat=int(sys.argv[2])):
    if sum(k)==m:print str(k)[1:-1].replace(" ","")

```
> 1 votes

# Answer
# Julia, 105 bytes

```
f(m,n)=for u=∪(reduce(vcat,map(i->collect(permutations(i)),partitions(m,n)))) println("$u"[2:end-1])end

```

This is a function that reads two integer arguments and writes the results to STDOUT with a single trailing line feed.

Ungolfed:

```
function f(m::Integer, n::Integer)
    # Get the integer partitions of m of length n
    p = partitions(m, n)

    # Construct an array of all permutations
    c = reduce(vcat, map(i -> collect(permutations(i)), p))

    # Loop over the unique elements
    for u in unique(c)
        # Print the array representation with no brackets
        println("$u"[2:end-1])
    end
end

```
> 1 votes

# Answer
# Husk, 14 bytes

```
moJ',msfo=¹Σπ²

```

Try it online!

with the correct output format.

# Husk, 7 bytes

```
fo=¹Σπ²

```

Try it online!

Inputs are taken as \\$n,m\\$.

## Explanation

```
fo=¹Σπ²
     π   cartesian power of n, with range 1..m
f        filter the terms where
    Σ    sum
  =      equals
   ¹     m

```
> 1 votes

# Answer
# Perl 6, 54 bytes

If the output could be a list of lists

```
{[X] (1..$^m)xx$^n .grep: $m==*.sum} # 36 bytes

```

```
my &code = {[X] (1..$^m)xx$^n .grep: $m==*.sum}
say .join(',') for code 7,3;

```

---

The way it's currently worded I have to add a `join` into the lambda.

```
{say .join(',')for [X] (1..$^m)xx$^n .grep: $m==*.sum} # 54 bytes

```

```
{...}( 7,3 );

```

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

```
> 0 votes

---
Tags: code-golf, combinatorics, number-theory, integer-partitions
---


title: Shortest pristine truth machine

text:
# Question
Title: Shortest pristine truth machine
In this challenge, the goal is to create a pristine truth machine in as few bytes as possible. For reference, a truth machine does the following:

* Takes input, which is always 0 or 1
* If the input is 0, it is printed and the program terminates
* If the input is 1, it is printed forever

A pristine program is one that does not error on its own, but will error if any single substring with a length \\$1\le n\<p\\$ is removed (where \\$p\\$ is the length of the program).

For example, if the `main` did not error in some language, it would be pristine if all of the following produced an error:

```
mai
man
min
ain
ma
mn
in
m
n

```

The goal of this challenge is to write the shortest program or function (in bytes, per language) which is a pristine truth machine.

# Answer
> 8 votes
# Rust, 109 106 bytes

```
fn t(n:i8)->Result<Box::<Iterator::<Item=i8>>,i8>{if n==0{Err(0)}else{Ok(Box::new(std::iter::repeat(1)))}}

```

Try it online!

Returns a result whose ok variant is a dynamically typed iterator that always yields one wrapped in a smart pointer so the compiler can know its size. The error variant is simply zero. The code does emit a deprecation warning, so it may randomly stop working at some point in the future. Rust's type inference is too good for me to get a pristine closure, and as verbose as this solution is it is still shorting than fully listing the returned iterator's type and much shorter than using the main function and reading from stdin.

-3 bytes because there is a method to create an endlessly repeating iterator

# Answer
> 5 votes
# `s`, 1 byte

```
w

```

The `s` flag tells the program to get it's input from STDIN rather than arguments.

It's pristine because there is only one subset of program to remove.

The power of triviality.

# Answer
> 2 votes
# C# (.NET Core), 159 bytes

```
class P{static void Main(string[]a){System.Console.Write(
#region
a[0]);while(1.ToString()==a[0]){System.Console.Write(a[
#region
0]);}}}
#endregion
#endregion

```

Try it online!

---
Tags: code-golf, pristine-programming
---