Problem 1015: Partisan Kayles

View on Project Euler

Project Euler Problem 1015 Solution

A row of blue and red pins is fair exactly when it has as many blue as red pins and the game of knocking over mixed blue-red pairs, which is Dawson's Kayles on its alternating blocks, has nim-sum zero. Sixteen Walsh signs and a square-root generating function count these rows; because the Dawson's Kayles values repeat with period 34, each series obeys a short recurrence, so n pins take O(n log n) time. Implementations are available in C++, Python and Java.

Detailed mathematical approach

Problem Summary

Blue and red bowling pins stand in a row, and two players, Blue and Red, take turns. On a turn a player knocks over one pin of their own colour, or two neighbouring pins of which at least one has their colour. A knocked-over pin leaves a gap, so the pins on its two sides are no longer neighbours. The player who cannot move loses. A starting row is called fair if the player who moves second wins when both players play perfectly: \(\mathtt{BRRB}\) is fair, while \(\mathtt{BRBR}\), \(\mathtt{BBRR}\) and \(\mathtt{BRBB}\) are not (\(\mathtt B\) is a blue pin and \(\mathtt R\) a red pin). With \(f(n)\) the number of fair rows of \(n\) pins, we are given \(f(6)=8\) and \(f(20)=49844\), and we must find the last \(9\) digits of \(f(1000)\). [1] The game is a two-coloured cousin of Kayles, a game invented by Henry Dudeney in which players take turns knocking over one pin or two neighbouring pins from a row of bowling pins. [2]

The whole solution in one sentence: a row is fair exactly when it has as many blue pins as red pins and a small hidden game inside it, the game of knocking over mixed pairs, is lost by the player who has to move; both conditions can be counted with a generating function, and because the values of the hidden game repeat every \(34\) pins once a block has at least \(53\) pins, that generating function obeys a short step-by-step rule, so the count for \(n\) pins takes only about \(n\log n\) steps, where \(\log n\) grows like the number of digits of \(n\). The sections below build this up slowly, starting from tiny rows, so that every step can be checked by hand.

Mathematical Approach

We first find out who wins any row, without playing the game to the end. Then we count the rows in which the second player wins, and finally we turn the count into a fast step-by-step rule.

1. Small rows

Perfect play means that each player always picks a move that keeps a win if such a move exists. Every row then has exactly one of four results: Blue wins no matter who starts, Red wins no matter who starts, the first player wins, or the second player wins. Only the last kind is fair. Three tiny examples:

  • \(\mathtt B\): if Blue moves first, Blue knocks the pin over and Red has no move left, so Red loses. If Red moves first, Red has nothing to knock over and loses at once. Blue wins either way.
  • \(\mathtt{BR}\): whoever moves first knocks over both pins, which is allowed because one of them has the mover's colour, and the other player is left with nothing. The first player wins, so the row is not fair.
  • \(\mathtt{BBRR}\): the first player knocks over the middle pair \(\mathtt{BR}\), which either player may do. One blue pin and one red pin are left, far apart. Now each player can only knock over their own last pin, and the second player has to do it first, so the second player is the one left without a move. The first player wins, so this row is not fair either.

The fair row \(\mathtt{BRRB}\) can be checked by hand as well. Suppose Blue moves first. If Blue knocks over one blue pin, Red knocks over the mixed pair that holds the other blue pin, and Blue has no move left. If Blue knocks over one end pair, \(\mathtt{BR}\) or \(\mathtt{RB}\), Red knocks over the other end pair, and again Blue has no move left. Blue may not touch the middle pair \(\mathtt{RR}\), which has no blue pin. So Blue loses. In the same way Red loses when Red moves first; Red's one extra move, knocking over \(\mathtt{RR}\), leaves two blue pins and no red pin, so after Blue's reply Red has nothing to knock over. The second player always wins, so the row is fair.

Checking longer rows by hand quickly becomes hopeless, because every move creates a new position with its own possible moves. So we look for a pattern instead.

2. Pins are spare moves

Think of every blue pin as a sweet that belongs to Blue and every red pin as a sweet that belongs to Red. A player who knocks over a single pin of their own colour eats one of their own sweets. There are exactly three kinds of moves:

  • knock over one of your own pins: you lose one sweet;
  • knock over two neighbouring pins of your own colour: you lose two sweets;
  • knock over a mixed pair, one blue pin next to one red pin: each player loses one sweet.

Let \(d\) be the number of blue pins minus the number of red pins, the lead of Blue. The first two kinds of move bring the lead closer to the opponent's side: Blue's own moves lower \(d\) by \(1\) or \(2\), and Red's own moves raise it by \(1\) or \(2\). A mixed pair does not change \(d\) at all; it is a fair trade. In the language of combinatorial game theory an integer counts free moves, the move advantage of one player, [6] and \(d\) will play exactly that role here.

Mixed pairs have one more special property: both players may knock over any mixed pair, because it always contains a pin of each colour. Moves that are available to both players in the same way form an impartial game, and impartial games are well understood. [5]

3. Mixed pairs live in alternating blocks

Cut the row between every two neighbouring pins that have the same colour, and, once pins have been knocked over, also at every gap. The pieces are alternating blocks, in which the colours take turns. For example, \(\mathtt{BBRRBR}\) is cut into \(\mathtt B\), \(\mathtt{BR}\) and \(\mathtt{RBR}\), blocks of lengths \(1\), \(2\) and \(3\). A mixed pair is exactly a pair of neighbouring pins inside one block.

If a mixed pair is knocked out of a block of length \(L\), two shorter blocks of lengths \(i\) and \(L-2-i\) remain, separated by the new gap, and each of them still alternates. Colours no longer matter inside a block: the mixed-pair game on one block is a row of \(L\) counters from which a move removes two neighbouring counters. This game is known as Dawson's Kayles, the octal game \(0.07\). [3]

4. A number for every block

For impartial games there is a wonderful shortcut, the Sprague–Grundy theorem: every position gets a number, its Grundy value, and a position with value \(0\) is lost by the player who has to move in it. [5] The value of a position is the first of the numbers \(0,1,2,\dots\) that is not among the values of the positions reachable in one move; this smallest missing number is called the mex. Writing \(\oplus\) for the way values of separate pieces are combined, which Section 5 explains, the value of a block of \(L\) pins is

$$g(L)=\operatorname{mex}\{\,g(i)\oplus g(L-2-i)\,\},$$

where \(i\) runs over \(0,1,\dots,L-2\), and \(g(0)=g(1)=0\) because no mixed pair fits into a block of \(0\) or \(1\) pin, and the smallest number missing from an empty list is \(0\). A block of \(2\) pins has a single move, which leaves an empty block of value \(0\), so \(g(2)=1\). A block of \(3\) pins always leaves one single pin, of value \(0\), so \(g(3)=1\) as well. Next, from a block of \(4\) pins one can knock over pins one and two, leaving a block of \(2\) with value \(1\); pins two and three, leaving two single pins with value \(0\oplus0=0\); or pins three and four, again with value \(1\). The reachable values are \(0\) and \(1\), the smallest missing number is \(2\), and so \(g(4)=2\). Continuing in this way gives the values for \(L=0,1,\dots,20\):

\(0, 0, 1, 1, 2, 0, 3, 1, 1, 0, 3,\)
\(3, 2, 2, 4, 0, 5, 2, 2, 3, 3.\)

The largest value is \(9\), reached for the first time at \(L=86\). The last irregular value is at \(L=52\); from \(L=53\) on the values repeat with period \(34\), that is, \(g(L+34)=g(L)\) for every \(L\ge53\). The On-Line Encyclopedia of Integer Sequences lists the same values, shifted by one place, under Dawson's Chess, together with this period. [4] A repetition seen on a computer screen could in principle break down at some huge length; Section 12 shows why this one never does, and the program checks the conditions of that proof whenever it builds its counting rules.

5. Adding blocks with the nim-sum

Write each value in binary, with only the digits \(0\) and \(1\), where each place is worth twice the place to its right: \(2=10_2\), \(3=11_2\), \(5=101_2\) and \(6=110_2\). Think of every binary digit as a light switch. Combining two values flips the switches of the first value wherever the second value has a \(1\); this is the nim-sum \(\oplus\), also called exclusive or. For example \(1\oplus1=0\); \(2\oplus3=1\), because flipping both switches of \(10_2\) gives \(01_2\); and \(5\oplus3=6\), because flipping the last two switches of \(101_2\) gives \(110_2\). A game made of several separate pieces, where each move happens in one piece, has as its value the nim-sum of the values of the pieces. [5] The mixed-pair game of a whole row, with blocks of lengths \(L_1,\dots,L_k\), therefore has the value

$$x=g(L_1)\oplus g(L_2)\oplus\dots\oplus g(L_k).$$

Two facts follow from the definition of the mex. If \(x\ne0\), some mixed-pair move makes the value \(0\). If \(x=0\), every mixed-pair move makes it different from \(0\).

6. The winner rule

Now the whole game can be decided with two numbers, the lead \(d\) and the value \(x\):

  • if \(d\gt0\), Blue wins, no matter who starts;
  • if \(d\lt0\), Red wins, no matter who starts;
  • if \(d=0\) and \(x\ne0\), the first player wins;
  • if \(d=0\) and \(x=0\), the second player wins, so the row is fair.

Put simply: with perfect play, whoever has more sweets wins, because the other player runs out of moves first. The richer player must still choose well: from \(\mathtt{BBR}\), Blue wins by knocking over the mixed pair \(\mathtt{BR}\), but loses after knocking over \(\mathtt{BB}\). When both have the same number of sweets, nobody wants to eat one of their own, since that hands the lead to the other player, so only the mixed-pair game matters.

The precise proof goes by induction on the number of pins left; the rule is about any position, also one with gaps. With no pins at all, \(d=x=0\) and the player to move loses, so the rule holds. Now assume the rule for every position with fewer pins, and suppose \(d\gt0\). If Blue moves first and the row has a mixed pair, Blue knocks it over: \(d\) stays positive and Red is to move, so Blue wins by the induction hypothesis. If there is no mixed pair, Blue knocks over one blue pin, which exists because \(d\gt0\). Then \(d-1\ge0\), and there is still no mixed pair, because knocking pins over never creates new neighbours, so \(x=0\); with Red to move, both \(d-1\gt0\) and the case \(d-1=0\), \(x=0\) are wins for Blue. If Red moves first, every move of Red leaves \(d\) positive or raises it, and Blue to move wins again; a Red player without moves simply loses. The case \(d\lt0\) is the mirror image. Finally suppose \(d=0\). If \(x\ne0\), the player to move knocks over a mixed pair that makes \(x=0\) and leaves \(d=0\), and the opponent then loses. If \(x=0\), a mixed-pair move leaves \(d=0\) and \(x\ne0\), so the opponent wins; any other move hands the opponent a positive lead, which also wins for the opponent. So the player to move loses exactly when \(x=0\).

The examples of the statement agree. \(\mathtt{BRRB}\) has \(d=0\) and the blocks \(\mathtt{BR}\), \(\mathtt{RB}\), so \(x=1\oplus1=0\): fair. \(\mathtt{BRBR}\) is a single block of length \(4\) with \(x=2\), and \(\mathtt{BBRR}\) has the blocks \(\mathtt B\), \(\mathtt{BR}\), \(\mathtt R\) with \(x=0\oplus1\oplus0=1\): in both the first player wins. \(\mathtt{BRBB}\) has \(d=2\), so Blue always wins. In game-theory language, every row has the same winner as the number \(d\) plus the nimber \(*x\). [6]

7. What has to be counted

A row of \(n\) pins is fair exactly when it has \(n/2\) blue pins and \(x=0\). Rows of odd length are never fair. For \(n=6\) there are eight fair rows, which is the given \(f(6)=8\): \(\mathtt{BBRRBR}\), \(\mathtt{BBRRRB}\), \(\mathtt{BRBBRR}\), \(\mathtt{BRRRBB}\), \(\mathtt{RBBBRR}\), \(\mathtt{RBRRBB}\), \(\mathtt{RRBBBR}\) and \(\mathtt{RRBBRB}\). For instance \(\mathtt{BRBBRR}\) has the blocks \(\mathtt{BRB}\), \(\mathtt{BR}\), \(\mathtt R\) with \(x=1\oplus1\oplus0=0\).

Write \(n=2m\), and call a row balanced when it has as many blue pins as red pins, that is, \(d=0\). Without the condition \(x=0\) the count would be easy: we only have to choose which \(m\) of the \(2m\) places are blue, so there are \(\binom{2m}{m}\) balanced rows of length \(2m\), the central binomial coefficient. [7] For \(n=6\) there are \(\binom63=20\) balanced rows, and only \(8\) of them are fair. The difficulty is to count only the balanced rows with \(x=0\).

8. The sign trick

Every block value is at most \(9\), as Section 12 confirms for every length, so it is below \(16\) and has at most four binary digits. For two numbers \(h\) and \(v\) between \(0\) and \(15\), let \(h\cdot v\) be the number of binary places in which both have the digit \(1\); here the dot is not ordinary multiplication. For example, \(3=0011_2\) and \(5=0101_2\) both have a \(1\) only in the last place, so for \(h=3\) and \(v=5\) we get \(h\cdot v=1\). Then

$$\frac1{16}\sum_{h=0}^{15}(-1)^{h\cdot v}$$

equals \(1\) when \(v=0\) and \(0\) otherwise. The reason is simple. If \(v=0\), every term is \(+1\). If \(v\) has a digit \(1\) in some place, flipping that digit of \(h\) changes the sign of the term, so the sixteen terms split into pairs of \(+1\) and \(-1\) that cancel, like one step forward and one step back. These signs are the characters behind the Walsh–Hadamard transform. [8]

The sign of a nim-sum is the product of the signs of its parts. Only the places where \(h\) has a \(1\) matter. If exactly one part has a \(1\) in such a place, the nim-sum has a \(1\) there too, and both sides get one minus sign. If both parts have a \(1\) there, the product gets two minus signs, which cancel, and the nim-sum has a \(0\) there and gets no minus sign. So for a row with blocks of lengths \(L_1,\dots,L_k\),

$$(-1)^{h\cdot x}=w_h(L_1)\,w_h(L_2)\cdots w_h(L_k),$$

with \(w_h(L)=(-1)^{h\cdot g(L)}\). Let \(c_h(m)\) be the sum of these products over all balanced rows of length \(2m\). Averaging over \(h\) keeps exactly the rows with \(x=0\):

$$f(2m)=\frac1{16}\sum_{h=0}^{15}c_h(m).$$

For each of the \(16\) signs \(h\) we now need \(c_h(m)\), a sum of products over blocks, and such sums are what generating functions are good at. A generating function keeps a whole list of numbers in one expression: the number in front of \(t^n\), called its coefficient, is the entry for \(n\) pins. When the list goes on forever, as in \(1+t+t^2+t^3+\dots\), the expression is called a power series.

9. Building a row block by block

A starting row, which has no gaps, is described exactly by the colour of its first pin and the list of its block lengths from Section 3; two neighbouring blocks always meet with two pins of the same colour. A block of odd length starts and ends with the same colour, so the next block starts with that colour again, and the block changes the lead by \(+1\) if that colour is blue and by \(-1\) if it is red. A block of even length ends with the other colour, so the next block starts with the other colour, and it does not change the lead.

Let \(t\) count pins and \(y\) count the lead, so that a row of \(n\) pins and lead \(d\) contributes \(t^n y^d\) times its product of signs. For example, \(\mathtt{BRB}\) has \(3\) pins and lead \(1\), so it contributes \(t^3y\) times its sign, and \(\mathtt{RBR}\) contributes \(t^3y^{-1}\) times its sign, where \(y^{-1}=1/y\). Collect the signed blocks of each kind in two power series:

$$E=\sum_{j\ge1}w_h(2j)\,t^{2j},$$

$$O=\sum_{j\ge0}w_h(2j+1)\,t^{2j+1}.$$

Remember the colour with which the next block starts, blue or red. One block then acts like the matrix

$$P=\begin{pmatrix}yO&E\\E&y^{-1}O\end{pmatrix},$$

a small table whose row is the colour with which a block starts and whose column is the colour with which the next block starts: the first row describes a block that starts with blue and the second row a block that starts with red. Multiplying such tables chains blocks together: to join two blocks, multiply their entries and add over the colour at the place where they meet. For example, the blue-to-blue entry of \(P^2\) is \((yO)^2+E^2\), because either both blocks have odd length or both have even length. So \(P^2\) describes two blocks one after the other, \(P^3\) three blocks, and so on. Adding up \(I\), \(P\), \(P^2\), \(P^3\) and so on, where the identity matrix \(I\) stands for no block at all, over both colours of the first pin, gives the signed rows of every length. Just as \(1+q+q^2+\dots=1/(1-q)\), this sum is \((I-P)^{-1}\). The empty row appears once for each starting colour, and one copy is removed:

$$F=\begin{pmatrix}1&1\end{pmatrix}(I-P)^{-1}\begin{pmatrix}1\\1\end{pmatrix}-1.$$

Inverting the \(2\times2\) matrix and simplifying gives

$$F=\frac{(1+E)^2-O^2}{1+O^2-E^2-(y+y^{-1})O}.$$

10. Keeping the colours balanced

The balanced rows are the terms with \(y^0\). Picture the lead as a walk that steps up for each blue odd block and down for each red one: we only keep the walks that come back to where they started. For power series \(a\) with constant term \(1\) and \(b\) with constant term \(0\), where the constant term is the part without any \(t\), the rule \(1/(1-q)=1+q+q^2+\dots\) with \(q=b(y+y^{-1})/a\) gives

$$\frac1{a-b(y+y^{-1})}=\sum_{k\ge0}\frac{b^k(y+y^{-1})^k}{a^{k+1}}.$$

The power \((y+y^{-1})^k\) has a term with \(y^0\) only when \(k=2j\) is even, and then its coefficient is \(\binom{2j}{j}\), the number of ways to take \(j\) steps up and \(j\) steps down. Since \(\sum_j\binom{2j}{j}z^j=1/\sqrt{1-4z}\), [7] the part with \(y^0\) is

$$\frac1{a}\cdot\frac1{\sqrt{1-4b^2/a^2}}=\frac1{\sqrt{a^2-4b^2}}.$$

Here \(a=1+O^2-E^2\) and \(b=O\), and \(a^2-4b^2\) factors as \(\bigl((1-E)^2-O^2\bigr)\)\(\bigl((1+E)^2-O^2\bigr)\). Every square root here means the power series whose constant term is \(1\). Cancelling the common factor with the numerator of \(F\) gives the series of the balanced rows, which all have even length:

$$\sum_{m\ge0}c_h(m)\,t^{2m}=\sqrt{\frac{(1+E)^2-O^2}{(1-E)^2-O^2}}.$$

For each of the \(16\) values of \(h\), the program needs one coefficient of this series. One could find it with a long division followed by a square root taken term by term, where each new coefficient of the root is found from the earlier ones because the root times itself must give the fraction. But then every new coefficient looks back at all earlier ones, and the work grows like the square of the number of pins. The program uses this slow method only as a check. The next sections replace it by a rule that produces each new coefficient from a fixed number of earlier ones.

11. A check with all signs equal to plus one

For \(h=0\) every sign is \(+1\), and the formula must simply count all balanced rows. Indeed, with \(u=t^2\) we get \(E=u/(1-u)\) and \(O^2=u/(1-u)^2\), so \((1+E)^2-O^2=1/(1-u)\) and \((1-E)^2-O^2\)\({}=(1-4u)/(1-u)\). The fraction under the root is \(1/(1-4u)\), and its square root \(1/\sqrt{1-4u}\) is the generating function of \(\binom{2m}{m}\), exactly the number of balanced rows found in Section 7. [7]

12. The block values repeat forever

Section 4 says that \(g(L+34)=g(L)\) from \(L=53\) on. A computer can only check finitely many lengths, but for games like this one a finite check is enough; this is the periodicity theorem of Guy and Smith. [9] In everyday words: in a long block, at least one of the two pieces left after a move is long, and a long piece behaves exactly like a piece that is \(34\) pins shorter.

Here is the argument for our game. Suppose we have checked \(g(L+34)=g(L)\) for every \(L\) with \(53\le L\lt142\). Take a longer block, \(L\ge142\), and assume that the repetition already holds for all lengths from \(53\) up to \(L-1\). A move in a block of \(L+34\) pins knocks over two neighbouring pins and leaves two blocks of lengths \(a\) and \(b\) with \(a+b=L+32\). Since \(L+32\ge174\), while two lengths of at most \(86\) pins add up to at most \(172\), one of them, say \(b\), has at least \(87\) pins. So \(b-34\) lies between \(53\) and \(L-1\), and the repetition gives \(g(b)=g(b-34)\). The move therefore has the same value \(g(a)\oplus g(b)\) as the move in a block of \(L\) pins that leaves \(a\) and \(b-34\) pins. In the other direction, a move in a block of \(L\) pins leaves two blocks with \(a+b=L-2\ge140\), so one of them has at least \(70\) pins; making that block \(34\) pins longer gives a move in the block of \(L+34\) pins with the same value. So the two blocks reach exactly the same values, they have the same mex, and \(g(L+34)=g(L)\). Step by step this covers every length.

The program checks exactly these \(89\) lengths whenever it builds its counting rules of Section 14, also in the self-test. After that, the value of every block, even one with \(10^8\) pins, can be read from a table of \(87\) numbers: \(g(0),\dots,g(52)\) and one period \(g(53),\dots,g(86)\). For a longer block, subtract \(34\) until the length is at most \(86\); for example \(g(100)=g(66)=3\). In particular no block value is ever larger than \(9\).

13. Repeating signs make the series short

From now on write \(u=t^2\), so that a row of \(2m\) pins goes with \(u^m\). Write \(E=\sum_{j\ge1}e_ju^j\) and \(O=t\sum_{j\ge0}o_ju^j\), where \(e_j=w_h(2j)\) and \(o_j=w_h(2j+1)\), so that \(O^2=u\,\bigl(\sum_{j\ge0}o_ju^j\bigr)^2\). Because the block values repeat with period \(34\), so do the signs, and adding \(17\) to \(j\) adds \(34\) to the block lengths \(2j\) and \(2j+1\): \(e_{j+17}=e_j\) as soon as \(2j\ge53\), that is \(j\ge27\), and \(o_{j+17}=o_j\) as soon as \(2j+1\ge53\), that is \(j\ge26\).

A list that repeats hides a simple fraction. For example, multiply \(1+u+u^2+u^3+\dots\) by \(1-u\): every term cancels against its neighbour, only \(1\) is left, and so the endless list is \(1/(1-u)\). An irregular start only makes the result a little longer: the list \(1,2,1,1,1,\dots\) repeats from its third entry on, and \((1+2u+u^2+u^3+\dots)\)\((1-u)\)\({}=1+u-u^2\) stops after \(u^2\). In the same way, multiplying \(E\) by \(1-u^{17}\) subtracts from every coefficient the one \(17\) places earlier, \(e_j-e_{j-17}\), and this is \(0\) as soon as both lie in the repeating part, that is for \(j\ge44\); for the odd signs, \(o_j-o_{j-17}=0\) already for \(j\ge43\). So

$$A=(1-u^{17})\,E,\qquad B=(1-u^{17})\sum_{j\ge0}o_ju^j$$

are polynomials, that is, power series with only finitely many terms. The degree of a polynomial is its highest power of \(u\); for example, \(1+u-u^2\) has degree \(2\). So \(A\) has degree at most \(43\), and \(B\) at most \(42\).

Now multiply the numerator and the denominator under the square root of Section 10 by \((1-u^{17})^2\). Since \((1-u^{17})(1+E)\)\({}=1-u^{17}+A\), \((1-u^{17})(1-E)\)\({}=1-u^{17}-A\) and \((1-u^{17})^2\,O^2=u\,B^2\), with \(H=\sum_{m\ge0}c_h(m)\,u^m\) this gives

$$H^2=\frac{N_+}{N_-},$$

$$N_+=(1-u^{17}+A)^2-u\,B^2,$$

$$N_-=(1-u^{17}-A)^2-u\,B^2.$$

Both \(N_+\) and \(N_-\) are polynomials of degree at most \(86\) with integer coefficients, and both start with \(1\). So the endless series of Section 10 is the square root of a fraction of two polynomials of moderate size.

14. A rule for the next coefficient

Such a square root obeys a simple equation for its rate of change, its derivative, written with a dash: \(H'\) is the derivative of \(H\). For a power series the derivative is taken term by term: \(u^m\) becomes \(m\,u^{m-1}\); for example, the derivative of \(1+3u+5u^2\) is \(3+10u\). The derivative of a product of two series is the derivative of the first times the second plus the first times the derivative of the second; on single terms this is \((u^i\cdot u^k)'=(i+k)\,u^{i+k-1}\)\({}=i\,u^{i-1}\cdot u^k+u^i\cdot k\,u^{k-1}\). So the derivative of \(H^2=H\cdot H\) is \(H'H+HH'=2HH'\), and, as for ordinary functions, the derivative of a fraction is \((N_+'N_--N_+N_-')/N_-^2\). So \(H^2=N_+/N_-\) gives

$$2HH'=\frac{N_+'N_--N_+N_-'}{N_-^2}.$$

Dividing by \(2H^2=2N_+/N_-\), then multiplying by \(N_+N_-H\), gives

$$T\,H'=U\,H,$$

$$T=N_+N_-,\qquad U=\tfrac12\,(N_+'N_--N_+N_-').$$

The capital letters \(T\) and \(U\) are names for these two new polynomials, not the counting letters \(t\) and \(u\). The polynomial \(U\) has integer coefficients, which matters because the program works only with whole numbers. Indeed \(N_+\) and \(N_-\) differ only in the sign of \(A\), and \((1-u^{17}+A)^2\)\({}-(1-u^{17}-A)^2\)\({}=4(1-u^{17})A\), so \(N_+-N_-=4C\) with \(C=(1-u^{17})A\). Substituting \(N_+=N_-+4C\) gives \(N_+'N_--N_+N_-'\)\({}=4(C'N_--CN_-')\), and so \(U=2(C'N_--CN_-')\).

Write \(T=\sum_jT_ju^j\) and \(U=\sum_jU_ju^j\), where coefficients beyond the degree count as \(0\); here \(T_0=1\), because \(N_+\) and \(N_-\) start with \(1\). The coefficient of \(u^{m-1}\) in \(H'\) is \(m\,c_h(m)\). So the coefficient of \(u^{m-1}\) on the left of \(T\,H'=U\,H\) is \(\sum_{j=0}^{m-1}T_j\,(m-j)\,c_h(m-j)\), whose first term is \(m\,c_h(m)\) because \(T_0=1\), and on the right it is \(\sum_{j=1}^{m}U_{j-1}\,c_h(m-j)\). Setting the two equal and moving the other terms of the left side to the right gives the rule, for every \(m\ge1\) and starting from \(c_h(0)=1\):

$$m\,c_h(m)=\sum_{j=1}^{m}\bigl(U_{j-1}-(m-j)\,T_j\bigr)\,c_h(m-j).$$

Only finitely many terms are not \(0\): \(T\) has degree at most \(172\) and \(U\) at most \(171\), so every new coefficient needs at most the \(172\) previous ones, a fixed amount of work, and one division by \(m\). For the sixteen values of \(h\) the rule looks back between \(67\) and \(172\) places, with \(2059\) terms in all. Series whose coefficients follow a rule like this one, in which the earlier coefficients are multiplied by numbers such as \(U_{j-1}-(m-j)\,T_j\) that are polynomials in \(m\), are called holonomic or D-finite. Every algebraic function, that is, every solution of a polynomial equation whose coefficients are polynomials in \(u\), is of this kind; our \(H\) is one, because \(N_-H^2-N_+=0\). [10]

Again \(h=0\) is a good check. There \(H=1/\sqrt{1-4u}\) by Section 11, and the equation \(T\,H'=U\,H\) reduces to \((1-4u)H'=2H\), whose rule is \(m\,c_0(m)\)\({}=2(2m-1)\,c_0(m-1)\). Starting from \(c_0(0)=1\), it gives \(c_0(1)=2\cdot1\cdot1/1=2\), \(c_0(2)=2\cdot3\cdot2/2=6\) and \(c_0(3)=2\cdot5\cdot6/3=20\), the \(20\) balanced rows of \(6\) pins from Section 7; in general it is the step from \(\binom{2m-2}{m-1}\) to \(\binom{2m}{m}\). The program does not cancel common factors of \(N_+\) and \(N_-\), so its rule for \(h=0\) is longer, but it produces the same numbers.

15. Only the last nine digits

Only the last nine digits of \(f(1000)\) are needed, that is, \(f(1000)\) modulo \(10^9\): the remainder left after dividing by \(10^9\). At the end, however, we divide by \(16\), and the remainder of \(16f(1000)\) modulo \(10^9\) would not be enough: because \(16\cdot62500000=10^9\), adding \(62500000\) to \(f(1000)\) would not change it. So every \(c_h(m)\) is computed modulo \(M=16\cdot10^9\). The true sum of the sixteen values is \(16f(1000)\), and \(16\) divides \(M\), so the sum modulo \(M\) is divisible by \(16\) as well, and dividing it by \(16\) gives \(f(1000)\) modulo \(10^9\).

The rule of Section 14 divides by \(m\). With remainders, dividing is easy by a number that shares no prime factor with the modulus, the number by which we divide to get the remainders: modulo \(10\), for instance, dividing by \(3\) is the same as multiplying by \(7\), because \(3\cdot7=21\) leaves the remainder \(1\). Such a partner is found with the extended Euclidean algorithm, which divides with remainder again and again and keeps track of each remainder; for \(3\) and \(10\) one step is enough: \(10=3\cdot3+1\), so \(1=10-3\cdot3\), and the partner of \(3\) is \(-3\), which leaves the same remainder as \(7\). But \(M=16\cdot10^9=2^{13}\cdot5^9\), and the divisor \(m\) is often even or a multiple of \(5\). So the program works with the two prime powers \(2^{13}\) and \(5^9\) separately, because then only one prime, \(2\) or \(5\), can get in the way of a division, and the next paragraphs deal with it. The Chinese remainder theorem then puts the two remainders back together into one remainder modulo \(M\). [11] For example, a number that leaves the remainder \(1\) after division by \(2\) and the remainder \(3\) after division by \(5\) leaves the remainder \(3\) after division by \(10\).

Fix one of the two primes, \(p=2\) with \(r=13\) or \(p=5\) with \(r=9\), so that we need the remainders modulo \(p^r\). Write \(m=p^v\,m'\), where \(m'\) is not divisible by \(p\); for example, for \(p=2\) and \(m=12\) we get \(v=2\) and \(m'=3\). Dividing by \(m'\) is harmless. Dividing by \(p^v\) is where digits get lost. For example, with ordinary decimal digits: if all we know about a multiple of \(10\) is that its last two digits are \(20\), it could be \(20\), \(120\), \(220\) and so on, so its tenth could be \(2\), \(12\), \(22\) and so on, and only the last digit is still known. In the same way each division by \(p^v\) loses \(v\) digits in base \(p\). The program therefore keeps extra digits. Let \(\ell\) be the largest number of factors \(p\) that any \(m\) up to the last one can have, so that \(p^\ell\le n/2\lt p^{\ell+1}\). The program works modulo \(p^s\) with

$$s=\max(r+\ell,\,2\ell).$$

The part \(r+\ell\) keeps the \(r\) digits we need, and the part \(2\ell\) makes every division possible; the next paragraphs show why. For \(1000\) pins, \(m\le500\). Since \(2^8=256\le500\lt512=2^9\), we get \(\ell=8\) and \(s=\max(13+8,\,16)=21\) for \(p=2\); since \(5^3=125\le500\lt625=5^4\), we get \(\ell=3\) and \(s=\max(9+3,\,6)=12\) for \(p=5\).

The lost digits could, in principle, pile up from step to step. They do not, and the reason is the equation of Section 14 itself. Suppose the program has computed the numbers \(\widehat c_h(0)=1,\widehat c_h(1),\dots,\widehat c_h(k)\), and let \(\widehat H\) be the polynomial with these coefficients. Every finished step \(m\le k\) makes \(m\) times the new number differ by a multiple of \(p^s\) from the right-hand side of the rule, filled in with the earlier computed numbers. So in \(\rho=T\,\widehat H'-U\,\widehat H\) the coefficients of \(u^0,\dots,u^{k-1}\) are multiples of \(p^s\). Let \(D=\widehat H-H\) be the error. The coefficients of \(T\) are integers, and so are those of \(H\), because they are signed counts of rows. Both start with \(1\), and a long division by a series with integer coefficients that starts with \(1\) never needs fractions, so \(K=D/H\) and \(1/(TH)\) have integer coefficients. The derivative of a product gives \(D'=H'K+HK'\), so \(T\,D'-U\,D\)\({}=(T\,H'-U\,H)\,K+T\,H\,K'\), and because \(T\,H'=U\,H\), this is \(T\,H\,K'\). Since \(T\,D'-U\,D=\rho\), we get \(K'=\rho/(TH)\), whose coefficients of \(u^0,\dots,u^{k-1}\) are multiples of \(p^s\). The constant coefficient of \(K\) is \(0\), because \(\widehat H\) and \(H\) both start with \(1\). For \(1\le i\le k\), the coefficient of \(u^{i-1}\) in \(K'\) is \(i\) times the coefficient of \(u^i\) in \(K\), a whole number; \(i\) has at most \(\ell\) factors \(p\), so that coefficient of \(K\) is a multiple of \(p^{s-\ell}\). Multiplying by the integer series \(H\) keeps this, so every coefficient of \(D=HK\) up to \(u^k\) is a multiple of \(p^{s-\ell}\): every computed number is right modulo \(p^{s-\ell}\), and \(s-\ell\ge r\).

The same estimate shows, step by step, that every division is possible. When step \(m\) is reached, the numbers before it are right modulo \(p^{s-\ell}\), so the number to be divided differs from \(m\,c_h(m)\) by a multiple of \(p^{s-\ell}\). Since \(s-\ell\ge\ell\ge v\), it is, like \(m\,c_h(m)\), a multiple of \(p^v\); the program takes its remainder modulo \(p^s\), divides that remainder by \(p^v\), and multiplies by the partner of \(m'\) modulo \(p^{s-v}\). The result \(\widehat c_h(m)\) makes \(m\,\widehat c_h(m)\) differ from the right-hand side of the rule by a multiple of \(p^s\), which completes the step.

The extra digits are really needed. In a test with \(m\le300\), where \(\ell=8\) and \(s=21\) for \(p=2\), working modulo \(2^{20}\) instead of \(2^{21}\) already gives wrong remainders modulo \(2^{13}\) for \(8\) of the \(16\cdot301=4816\) coefficients. Finally, for each \(h\) the two remainders are combined into one remainder modulo \(M\), the sixteen results are added, and the sum is divided by \(16\).

How the Code Works

When the C++ program [12] first builds its rules, it calls certify_period. This function uses grundy_values to compute \(g(L)\) for \(L\le175\) with the mex rule of Section 4, checks \(g(L+34)=g(L)\) for \(53\le L\lt142\) as Section 12 requires, and checks that no value reaches \(16\). character_sign returns the sign \((-1)^{h\cdot g(L)}\) of Section 8 by counting the binary ones of the common digits. make_recurrence handles one value of \(h\): it reads the signs from the table of \(87\) numbers of Section 12, builds \(A\), \(B\), \(N_+\), \(N_-\), \(T\) and \(U\) of Sections 13 and 14 with exact integer arithmetic, checks that \(T\) starts with \(1\) and that all coefficients of \(N_+'N_--N_+N_-'\) are even, and stores the rule of Section 14 as a list of the places \(j\) with their two numbers \(U_{j-1}+j\,T_j\) and \(-T_j\), so that the multiplier of \(c_h(m-j)\) in the rule is \(U_{j-1}+j\,T_j+m\,(-T_j)\); places where both numbers are \(0\) are left out. recurrences builds the sixteen rules once.

working_modulus chooses the exponent \(s\) of Section 15 for \(p=2\) and for \(p=5\). character_coefficients runs one rule for both primes side by side and keeps only the values that the rule still needs. divide_step removes the factors \(p\) from \(m\), checks that the division is possible and multiplies by the partner of the rest, which inverse finds with the extended Euclidean algorithm; combine applies the Chinese remainder theorem. fair_counts_at adds the sixteen results modulo \(M\), checks that every sum is divisible by \(16\) and divides. solve returns \(1\) for \(n=0\) and \(0\) for odd \(n\). Without arguments the main program prints the last nine digits of \(f(1000)\), with leading zeros; given a length \(n\) up to \(10^8\), it prints those of \(f(n)\).

With --self-test, run_tests checks \(f(0)=1\), \(f(6)=8\) and \(f(20)=49844\). For every \(h\) and every \(2m\le1000\) it compares the coefficient from the rule, modulo \(M\), with the result of quadratic_character, the slow method of Section 10. That function uses block values found with the mex rule itself, without the table of Section 12. It computes the quotient modulo \(2M\), and then finds each coefficient of the square root modulo \(M\) by computing twice that coefficient modulo \(2M\) and halving it. It checks that table against the mex rule for every \(L\) up to \(1000\). brute_outcomes solves the original game directly, with all \(3^{12}=531441\) positions of up to \(12\) places, each place empty, blue or red, and predicted_outcome confirms that the winner rule of Section 6 gives the same result for every one of them; counting the fair starting rows among these positions reproduces \(f(n)\) for every \(n\le12\). For \(19\) lengths from \(n=14\) to \(n=1000\), among them every length in this range at which the number of extra digits changes and the even length just below it, the count computed for that length alone, which keeps only the extra digits that this length needs, agrees with the one from the run for all lengths up to \(1000\). For \(h=0\) the rule must give the central binomial coefficients: they are compared modulo \(10^9\) for every \(2m\le1000\), and modulo \(2^{13}\) and \(5^9\) for \(m\) around \(2^{13}=8192\), \(5^6=15625\) and \(2^{14}=16384\), where central_binomial_residue computes them independently. The Python and Java versions follow the C++ program function by function; Python uses exact whole numbers, and Java uses overflow-checked long arithmetic and a small 128-bit helper built from two long values for products and sums that need more than 64 bits.

Complexity and Verification

Everything before the main loop has a fixed size: the Grundy table has \(176\) entries, and each of the sixteen rules is built from polynomials of degree at most \(86\). For \(n\) pins each rule is then run for \(m=1,2,\dots,n/2\). One step goes through at most \(172\) terms of the rule; each term costs one multiplication to form its multiplier and one more for each of the two primes. Then each of the two primes needs one division, whose partner the extended Euclidean algorithm finds in about \(\log n\) steps, because the working moduli have about \(\log n\) digits. Counting each arithmetic operation on the program's numbers, which always fit into a fixed number of machine words, as one step, the time grows like \(n\log n\). For a single length the memory stays fixed: each rule keeps only its last values. For \(n=1000\) this is a few million operations. The slow method of Section 10 looks back at all earlier coefficients for every new one, so its work grows like \(n^2\): for \(n=10^6\) its long divisions and square roots need about \(3\cdot10^{12}\) multiplications for the sixteen series, against about \(3\cdot10^9\) for the rules, whose \(2059\) terms cost three multiplications each in each of the \(5\cdot10^5\) steps. In tests on a desktop computer, \(n=10^6\) took at most a few seconds; the program accepts every \(n\) up to \(10^8\).

All three programs print the same nine digits and pass the self-test. Independent checks, which are not part of the published solutions, confirm the result. A separately written program using the slow method of Section 10 gives the same last nine digits for \(26\) lengths from \(n=2\) to \(n=40000\), among them \(n=16384\), \(31250\) and \(32768\), where the number of extra digits changes, and the neighbouring lengths \(n=16382\) and \(16386\). An exact computation with whole numbers, without any remainders, confirms for every \(h\) and every \(m\le300\) that the rule of Section 14 and the square root of Section 10 give the same coefficients. A separately written solver of the original game checks the winner rule on every position of up to \(20\) places, \(3^{20}=3486784401\) positions, and counts the fair rows by brute force for every \(n\le20\), including \(f(20)=49844\). A direct dynamic programme walks along the row pin by pin, remembering the colour of the last pin, the lead, the nim-sum of the finished blocks and the length of the current block, without any generating function or sign trick; it gives the exact \(f(n)\) for every even \(n\le200\) and the same last nine digits of \(f(n)\) for every even \(n\le1000\).

Footnotes and References

The references below supply the background facts used above. The winner rule with the lead \(d\) and the value \(x\), the generating function of the signed rows and its balanced part, the rule of Section 14 and the precision argument of Section 15 are derived explicitly in this article.

  1. Project Euler 1015 — Partisan Kayles. The official statement: Blue and Red knock over one pin of their own colour or two adjacent pins of which at least one has their colour, a knocked-over pin leaves a gap, and the player who cannot move loses. A starting row is fair if, with perfect play by both players, the second player wins; BRRB is fair, BRBR, BBRR and BRBB are not, f(6) = 8, f(20) = 49844, and the task asks for the last 9 digits of f(1000).
  2. Wikipedia — Kayles. Kayles, invented by Henry Dudeney, is played on a row of bowling pins; on a turn a player knocks out one pin or two adjacent pins, and the player without a legal move loses. In octal notation it is the game 0.77.
  3. Wikipedia — Octal game. In the game 0.07, called Dawson's Kayles, a move removes exactly two tokens from a heap and leaves the rest as zero, one or two heaps. For a row, this is knocking over two neighbouring pins, as in the mixed-pair game of Section 3.
  4. OEIS A002187 — Sprague–Grundy values for Dawson's Chess. The entry notes that Dawson's Kayles, the octal game .07, has the values a(n − 1), and that the sequence has period 34 with the only exceptions at n = 0, 14, 16, 17, 31, 34 and 51. In the numbering of this article, g(L) = a(L − 1) for L ≥ 1.
  5. Wikipedia — Sprague–Grundy theorem. Every finite impartial game under the normal play convention is equivalent to a nimber; the value of a position is the mex of the values of its options, and the value of a sum of games is the nim-sum of the values of its parts.
  6. Wikipedia — Combinatorial game theory. Numbers represent the number of free moves, or the move advantage of one player, with positive numbers favouring Left; sums of number games behave like the integers. Star, written ∗ = {0 | 0}, is a first-player win, and impartial games correspond to nimbers.
  7. Wikipedia — Central binomial coefficient. The central binomial coefficients C(2n, n) are 1, 2, 6, 20, 70, 252, … and their ordinary generating function is 1/√(1 − 4x).
  8. Wikipedia — Hadamard transform. The entries of the Walsh–Hadamard matrix are (−1)^(i·j), up to a normalising factor, where i·j is the bitwise dot product of the binary representations of i and j; the characters of (ℤ/2ℤ)ⁿ have the same form.
  9. Aaron N. Siegel — Misère Games and Misère Quotients (lecture notes, arXiv:math/0612616). Theorem 2.4, the Guy–Smith Periodicity Theorem, in normal play: consider an octal game with finitely many non-zero code digits, let k be the position of the last non-zero code digit, which is the largest number of boxes that one move may remove, and write G(H(n)) for the Grundy value of a strip of n boxes. If, for some n₀ > 0 and p > 0, G(H(n + p)) = G(H(n)) for every n with n₀ ≤ n < 2n₀ + p + k, then G(H(n + p)) = G(H(n)) for all n ≥ n₀. The notes list Dawson's Kayles, the game 0.07, as having period 34, and their table of its Grundy values uses the same numbering as this article: G(H(L)) = g(L). For 0.07 we have k = 2, so with n₀ = 53 and p = 34 the check runs over 53 ≤ n < 142.
  10. Wikipedia — Holonomic function. Holonomic, or D-finite, functions satisfy linear differential equations with polynomial coefficients; their coefficient sequences are the P-recursive sequences, which satisfy linear recurrences with polynomial coefficients, and all algebraic functions are holonomic.
  11. Wikipedia — Chinese remainder theorem. If the remainders of an integer after division by several pairwise coprime integers are known, its remainder after division by their product is determined uniquely.
  12. C++ — Euler1015.cpp. The linked immutable C++ revision contains certify_period, make_recurrence, character_coefficients, fair_counts_at and the checks run by --self-test. It is the implementation record for this article.

Problem 1015 source code

C++

#include <algorithm>
#include <charconv>
#include <cstdint>
#include <cstdlib>
#include <exception>
#include <iomanip>
#include <iostream>
#include <limits>
#include <pthread.h>
#include <stdexcept>
#include <string>
#include <system_error>
#include <thread>
#include <vector>

namespace {

using u64 = std::uint64_t;
using i64 = std::int64_t;
using i128 = __int128_t;
using u128 = __uint128_t;
using Polynomial = std::vector<i64>;
constexpr unsigned DEFAULT_LENGTH = 1000;
constexpr unsigned MAX_LENGTH = 100'000'000;
constexpr unsigned PREPERIOD = 53;
constexpr unsigned PERIOD = 34;
constexpr unsigned CHARACTERS = 16;
constexpr unsigned TWO_EXPONENT = 13;
constexpr unsigned FIVE_EXPONENT = 9;
constexpr u64 MOD = 1'000'000'000;
constexpr u64 SCALED_MOD = CHARACTERS * MOD;

constexpr u64 power(const u64 base, const unsigned exponent) {
    u64 result = 1;
    for (unsigned i = 0; i < exponent; ++i) result *= base;
    return result;
}

constexpr u64 TWO_MOD = power(2, TWO_EXPONENT);
constexpr u64 FIVE_MOD = power(5, FIVE_EXPONENT);
static_assert(TWO_MOD * FIVE_MOD == SCALED_MOD);

void require(const bool condition, const std::string& description) {
    if (!condition) throw std::runtime_error("Check failed: " + description);
}

std::vector<unsigned> grundy_values(const unsigned limit) {
    std::vector<unsigned> grundy(limit + 1), seen(limit + 2);
    for (unsigned n = 2; n <= limit; ++n) {
        for (unsigned left = 0; left <= (n - 2) / 2; ++left) {
            const unsigned value = grundy[left] ^ grundy[n - 2 - left];
            if (value < seen.size()) seen[value] = n;
        }
        while (seen[grundy[n]] == n) ++grundy[n];
    }
    return grundy;
}

int character_sign(unsigned value) {
    int sign = 1;
    for (; value; value &= value - 1) sign = -sign;
    return sign;
}

u64 residue(i128 value, const u64 modulus) {
    value %= static_cast<i128>(modulus);
    if (value < 0) value += modulus;
    return static_cast<u64>(value);
}

std::vector<u64> quadratic_character(const std::vector<unsigned>& grundy,
                                    const unsigned character, const u64 modulus) {
    const unsigned degree = static_cast<unsigned>(grundy.size() - 1) / 2;
    std::vector<int> odd(degree), even(degree + 1), numerator(degree + 1), denominator(degree + 1);
    for (unsigned n = 0; n < degree; ++n) odd[n] = character_sign(character & grundy[2 * n + 1]);
    for (unsigned n = 1; n <= degree; ++n) even[n] = character_sign(character & grundy[2 * n]);
    numerator[0] = denominator[0] = 1;
    for (unsigned n = 1; n <= degree; ++n) {
        int common = 0;
        for (unsigned i = 1; i < n; ++i) common += even[i] * even[n - i];
        for (unsigned i = 0; i < n; ++i) common -= odd[i] * odd[n - 1 - i];
        numerator[n] = common + 2 * even[n];
        denominator[n] = common - 2 * even[n];
    }

    const u64 double_modulus = 2 * modulus;
    std::vector<u64> square(degree + 1), root(degree + 1);
    square[0] = root[0] = 1;
    for (unsigned n = 1; n <= degree; ++n) {
        i128 coefficient = numerator[n];
        for (unsigned i = 1; i <= n; ++i) {
            coefficient -= static_cast<i128>(denominator[i]) * square[n - i];
        }
        square[n] = residue(coefficient, double_modulus);
        u128 products = 0;
        for (unsigned i = 1; 2 * i < n; ++i) products += u128{2} * root[i] * root[n - i];
        if (n % 2 == 0) products += static_cast<u128>(root[n / 2]) * root[n / 2];
        const u64 twice_root = (square[n] + double_modulus
            - static_cast<u64>(products % double_modulus)) % double_modulus;
        require(twice_root % 2 == 0, "integral square-root coefficient");
        root[n] = twice_root / 2;
    }
    return root;
}

void trim(Polynomial& polynomial) {
    while (polynomial.size() > 1 && polynomial.back() == 0) polynomial.pop_back();
}

Polynomial product(const Polynomial& a, const Polynomial& b) {
    Polynomial result(a.size() + b.size() - 1);
    for (std::size_t i = 0; i < a.size(); ++i) {
        for (std::size_t j = 0; j < b.size(); ++j) result[i + j] += a[i] * b[j];
    }
    trim(result);
    return result;
}

Polynomial difference(Polynomial a, const Polynomial& b) {
    a.resize(std::max(a.size(), b.size()));
    for (std::size_t i = 0; i < b.size(); ++i) a[i] -= b[i];
    trim(a);
    return a;
}

Polynomial derivative(const Polynomial& polynomial) {
    Polynomial result(std::max<std::size_t>(1, polynomial.size() - 1));
    for (std::size_t i = 1; i < polynomial.size(); ++i) result[i - 1] = static_cast<i64>(i) * polynomial[i];
    trim(result);
    return result;
}

std::vector<unsigned> certify_period() {
    constexpr unsigned END = 2 * PREPERIOD + PERIOD + 2;
    auto grundy = grundy_values(END + PERIOD - 1);
    // Guy-Smith: this finite window certifies the period for every n >= PREPERIOD.
    for (unsigned n = PREPERIOD; n < END; ++n) {
        require(grundy[n] == grundy[n + PERIOD], "Grundy periodicity certificate");
    }
    require(*std::max_element(grundy.begin(), grundy.end()) < CHARACTERS, "Walsh dimension");
    return grundy;
}

struct Term {
    unsigned lag;
    i64 constant, linear;
};

struct Recurrence {
    unsigned width;
    std::vector<Term> terms;
};

Recurrence make_recurrence(const unsigned character, const std::vector<unsigned>& grundy) {
    const auto sign = [&](unsigned n) {
        if (n >= PREPERIOD) n = PREPERIOD + (n - PREPERIOD) % PERIOD;
        return character_sign(character & grundy[n]);
    };
    constexpr unsigned HALF_PERIOD = PERIOD / 2;
    constexpr unsigned ODD_LENGTH = (PREPERIOD - 1) / 2 + HALF_PERIOD;
    constexpr unsigned EVEN_LENGTH = (PREPERIOD + 1) / 2 + HALF_PERIOD;
    Polynomial odd(ODD_LENGTH), even(EVEN_LENGTH);
    for (unsigned i = 0; i < ODD_LENGTH; ++i) {
        odd[i] = sign(2 * i + 1) - (i >= HALF_PERIOD ? sign(2 * (i - HALF_PERIOD) + 1) : 0);
    }
    for (unsigned i = 1; i < EVEN_LENGTH; ++i) {
        even[i] = sign(2 * i) - (i > HALF_PERIOD ? sign(2 * (i - HALF_PERIOD)) : 0);
    }
    Polynomial plus = even, minus = even;
    for (i64& value : minus) value = -value;
    ++plus[0];
    ++minus[0];
    --plus[HALF_PERIOD];
    --minus[HALF_PERIOD];
    auto odd_square = product(odd, odd);
    odd_square.insert(odd_square.begin(), 0);
    const auto p = difference(product(plus, plus), odd_square);
    const auto q = difference(product(minus, minus), odd_square);
    const auto t = product(p, q);
    auto u = difference(product(derivative(p), q), product(p, derivative(q)));
    // H^2 = P/Q gives (PQ)H' = (P'Q-PQ')H/2.
    for (i64& value : u) {
        require(value % 2 == 0, "integral differential equation");
        value /= 2;
    }
    require(t[0] == 1, "unit leading coefficient");
    const unsigned width = static_cast<unsigned>(std::max(t.size() - 1, u.size()));
    Recurrence recurrence{width, {}};
    for (unsigned lag = 1; lag <= width; ++lag) {
        const i64 tj = lag < t.size() ? t[lag] : 0;
        const i64 uj = lag <= u.size() ? u[lag - 1] : 0;
        if (tj != 0 || uj != 0) recurrence.terms.push_back({lag, uj + static_cast<i64>(lag) * tj, -tj});
    }
    return recurrence;
}

const std::vector<Recurrence>& recurrences() {
    static const auto result = [] {
        const auto grundy = certify_period();
        std::vector<Recurrence> values;
        for (unsigned h = 0; h < CHARACTERS; ++h) values.push_back(make_recurrence(h, grundy));
        return values;
    }();
    return result;
}

u64 inverse(const u64 value, const u64 modulus) {
    u64 remainder = modulus, next = value % modulus;
    i128 coefficient = 0, next_coefficient = 1;
    while (next != 0) {
        const u64 quotient = remainder / next;
        const u64 temporary = remainder % next;
        remainder = next;
        next = temporary;
        const i128 next_value = coefficient - static_cast<i128>(quotient) * next_coefficient;
        coefficient = next_coefficient;
        next_coefficient = next_value;
    }
    require(remainder == 1, "invertible unit");
    return residue(coefficient, modulus);
}

u64 working_modulus(const unsigned prime, const unsigned exponent, const unsigned limit) {
    unsigned logarithm = 0;
    for (unsigned n = limit; n >= prime; n /= prime) ++logarithm;
    // Integrating a residual modulo p^E loses at most L=floor(log_p n) digits.
    // E >= e+L preserves the target; E >= 2L permits every division.
    const unsigned digits = std::max(exponent + logarithm, 2 * logarithm);
    u64 modulus = 1;
    for (unsigned i = 0; i < digits; ++i) {
        require(modulus <= std::numeric_limits<u64>::max() / prime, "working modulus fits");
        modulus *= prime;
    }
    return modulus;
}

u64 divide_step(const i128 numerator, unsigned n, const unsigned prime, const u64 modulus) {
    u64 divisor = 1;
    while (n % prime == 0) {
        n /= prime;
        divisor *= prime;
    }
    const u64 value = residue(numerator, modulus);
    if (value % divisor != 0) throw std::runtime_error("Nonintegral prime-power division");
    const u64 reduced = modulus / divisor;
    return static_cast<u64>(static_cast<u128>(value / divisor) * inverse(n, reduced) % reduced);
}

u64 combine(const u64 two, const u64 five) {
    static const u64 multiplier = inverse(FIVE_MOD % TWO_MOD, TWO_MOD);
    const u64 b = five % FIVE_MOD;
    const u64 multiple = ((two % TWO_MOD + TWO_MOD - b % TWO_MOD) * multiplier) % TWO_MOD;
    return b + FIVE_MOD * multiple;
}

std::vector<u64> character_coefficients(const Recurrence& recurrence, const std::vector<unsigned>& indices) {
    const unsigned last = indices.back();
    const u64 mod2 = working_modulus(2, TWO_EXPONENT, last);
    const u64 mod5 = working_modulus(5, FIVE_EXPONENT, last);
    struct Residues { u64 two = 0, five = 0; };
    std::vector<Residues> history(2 * recurrence.width);
    history[0] = history[recurrence.width] = {1, 1};
    std::vector<u64> values;
    values.reserve(indices.size());
    std::size_t next = 0;
    if (indices[0] == 0) {
        values.push_back(1);
        ++next;
    }
    for (unsigned n = 1; n <= last; ++n) {
        const unsigned position = n % recurrence.width;
        const unsigned end = recurrence.width + position;
        i128 numerator2 = 0, numerator5 = 0;
        for (const auto& term : recurrence.terms) {
            if (term.lag > n) break;
            const i64 factor = term.constant + static_cast<i64>(n) * term.linear;
            const auto& previous = history[end - term.lag];
            numerator2 += static_cast<i128>(factor) * previous.two;
            numerator5 += static_cast<i128>(factor) * previous.five;
        }
        const Residues current{divide_step(numerator2, n, 2, mod2), divide_step(numerator5, n, 5, mod5)};
        history[position] = history[end] = current;
        if (next < indices.size() && n == indices[next]) {
            values.push_back(combine(current.two, current.five));
            ++next;
        }
    }
    return values;
}

struct CharacterWork {
    const std::vector<Recurrence>* recurrences;
    const std::vector<unsigned>* indices;
    std::vector<std::vector<u64>>* coefficients;
    unsigned first, stride;
    std::exception_ptr error;
};

void* calculate_characters(void* argument) {
    auto& work = *static_cast<CharacterWork*>(argument);
    try {
        for (unsigned h = work.first; h < CHARACTERS; h += work.stride) {
            (*work.coefficients)[h] = character_coefficients((*work.recurrences)[h], *work.indices);
        }
    } catch (...) {
        work.error = std::current_exception();
    }
    return nullptr;
}

std::vector<u64> fair_counts_at(const std::vector<unsigned>& indices, unsigned thread_count = 0) {
    if (indices.empty()) return {};
    const auto& equations = recurrences();
    if (thread_count == 0) {
        thread_count = indices.back() < 64 ? 1 : std::min(8U, std::max(1U, std::thread::hardware_concurrency()));
    }
    thread_count = std::min(thread_count, CHARACTERS);
    std::vector<std::vector<u64>> coefficients(CHARACTERS);
    std::vector<CharacterWork> work(thread_count);
    std::vector<pthread_t> threads(thread_count);
    std::vector<bool> started(thread_count);
    for (unsigned i = 0; i < thread_count; ++i) {
        work[i] = {&equations, &indices, &coefficients, i, thread_count, nullptr};
    }
    for (unsigned i = 1; i < thread_count; ++i) {
        started[i] = pthread_create(&threads[i], nullptr, calculate_characters, &work[i]) == 0;
        if (!started[i]) calculate_characters(&work[i]);
    }
    calculate_characters(&work[0]);
    for (unsigned i = 1; i < thread_count; ++i) {
        if (started[i] && pthread_join(threads[i], nullptr) != 0) std::terminate();
    }
    for (const auto& job : work) {
        if (job.error) std::rethrow_exception(job.error);
    }
    std::vector<u64> counts(indices.size());
    for (const auto& character : coefficients) {
        for (std::size_t i = 0; i < counts.size(); ++i) counts[i] = (counts[i] + character[i]) % SCALED_MOD;
    }
    for (u64& count : counts) {
        require(count % CHARACTERS == 0, "integral Walsh average");
        count /= CHARACTERS;
    }
    return counts;
}

u64 solve(const unsigned length, const unsigned thread_count = 0) {
    if (length > MAX_LENGTH) throw std::invalid_argument("Supported length is at most 100000000");
    if (length == 0) return 1;
    if (length % 2 != 0) return 0;
    return fair_counts_at({length / 2}, thread_count)[0];
}

std::vector<unsigned char> brute_outcomes(const unsigned length, std::vector<unsigned>& powers) {
    powers.assign(length + 1, 1);
    for (unsigned i = 1; i <= length; ++i) powers[i] = 3 * powers[i - 1];
    std::vector<unsigned char> outcomes(powers[length]);
    for (unsigned state = 1; state < outcomes.size(); ++state) {
        unsigned remaining = state;
        unsigned char result = 0;
        for (unsigned i = 0; i < length && result != 3; ++i) {
            const unsigned pin = remaining % 3;
            remaining /= 3;
            if (pin == 0) continue;
            const unsigned single = state - pin * powers[i];
            if (pin == 1 && !(outcomes[single] & 2)) result |= 1;
            if (pin == 2 && !(outcomes[single] & 1)) result |= 2;
            const unsigned next = remaining % 3;
            if (next == 0) continue;
            const unsigned pair = single - next * powers[i + 1];
            if ((pin == 1 || next == 1) && !(outcomes[pair] & 2)) result |= 1;
            if ((pin == 2 || next == 2) && !(outcomes[pair] & 1)) result |= 2;
        }
        outcomes[state] = result;
    }
    return outcomes;
}

unsigned predicted_outcome(unsigned state, const unsigned length, const std::vector<unsigned>& grundy) {
    int balance = 0;
    unsigned previous = 0, run = 0, nim_sum = 0;
    for (unsigned i = 0; i < length; ++i) {
        const unsigned pin = state % 3;
        state /= 3;
        if (pin == 1) ++balance;
        if (pin == 2) --balance;
        if (pin != 0 && previous != 0 && pin != previous) ++run;
        else {
            nim_sum ^= grundy[run];
            run = pin == 0 ? 0 : 1;
        }
        previous = pin;
    }
    nim_sum ^= grundy[run];
    if (balance > 0) return 1;
    if (balance < 0) return 2;
    return nim_sum == 0 ? 0 : 3;
}

u64 central_binomial_residue(const unsigned n, const unsigned prime, const unsigned exponent) {
    const u64 modulus = power(prime, exponent);
    u64 numerator = 1, denominator = 1;
    int valuation = 0;
    for (unsigned i = 1; i <= n; ++i) {
        unsigned top = n + i, bottom = i;
        while (top % prime == 0) {
            top /= prime;
            ++valuation;
        }
        while (bottom % prime == 0) {
            bottom /= prime;
            --valuation;
        }
        numerator = numerator * top % modulus;
        denominator = denominator * bottom % modulus;
    }
    require(valuation >= 0, "integral binomial coefficient");
    if (static_cast<unsigned>(valuation) >= exponent) return 0;
    return numerator * inverse(denominator, modulus) % modulus
        * power(prime, static_cast<unsigned>(valuation)) % modulus;
}

void run_tests() {
    constexpr unsigned SMALL = 12;
    constexpr unsigned CHECK_LENGTH = 1000;
    std::vector<unsigned> indices(CHECK_LENGTH / 2 + 1);
    for (unsigned i = 0; i < indices.size(); ++i) indices[i] = i;
    const auto counts = fair_counts_at(indices);
    require(counts[0] == 1, "empty arrangement");
    require(counts[3] == 8, "given f(6)");
    require(counts[10] == 49'844, "given f(20)");
    require(fair_counts_at(indices, 1) == counts, "serial and pthread agreement");

    const auto grundy = grundy_values(CHECK_LENGTH);
    std::vector<u64> expected_counts(indices.size()), unsigned_counts;
    for (unsigned h = 0; h < CHARACTERS; ++h) {
        const auto expected = quadratic_character(grundy, h, SCALED_MOD);
        require(character_coefficients(recurrences()[h], indices) == expected,
                "every character coefficient agrees with quadratic extraction");
        for (std::size_t i = 0; i < indices.size(); ++i) {
            expected_counts[i] = (expected_counts[i] + expected[i]) % SCALED_MOD;
        }
        if (h == 0) unsigned_counts = expected;
    }
    for (u64& count : expected_counts) count /= CHARACTERS;
    require(counts == expected_counts, "all fair counts agree with quadratic extraction");
    for (unsigned n = PREPERIOD; n <= CHECK_LENGTH; ++n) {
        require(grundy[n] == grundy[PREPERIOD + (n - PREPERIOD) % PERIOD], "periodic Grundy lookup");
    }

    std::vector<unsigned> powers;
    const auto outcomes = brute_outcomes(SMALL, powers);
    for (unsigned state = 0; state < outcomes.size(); ++state) {
        require(outcomes[state] == predicted_outcome(state, SMALL, grundy),
                "original-game minimax agrees with balance and alternating blocks");
    }
    for (unsigned n = 0; n <= SMALL; ++n) {
        u64 expected = 0;
        for (unsigned word = 0; word < (1U << n); ++word) {
            unsigned state = 0;
            for (unsigned i = 0; i < n; ++i) state += (1 + ((word >> i) & 1U)) * powers[i];
            expected += outcomes[state] == 0;
        }
        require(expected == (n % 2 == 0 ? counts[n / 2] : 0), "exhaustive initial arrangements");
        require(solve(n, 1) == expected, "short-prefix consistency");
    }

    for (const unsigned n : {14U, 16U, 18U, 30U, 32U, 48U, 50U, 62U, 64U, 126U, 128U,
                            248U, 250U, 254U, 256U, 510U, 512U, 998U, 1000U}) {
        require(solve(n, 1) == counts[n / 2], "agreement across working-precision boundaries");
    }
    require(solve(MAX_LENGTH - 1) == 0, "large odd length");

    std::vector<u64> binomial(CHECK_LENGTH + 1);
    binomial[0] = 1;
    for (unsigned n = 1; n <= CHECK_LENGTH; ++n) {
        for (unsigned k = n; k > 0; --k) binomial[k] = (binomial[k] + binomial[k - 1]) % MOD;
        if (n % 2 == 0) require(unsigned_counts[n / 2] % MOD == binomial[n / 2], "central binomial coefficients");
    }
    const std::vector<unsigned> large_indices{
        8191, 8192, 8193, 15624, 15625, 15626, 16383, 16384, 16385
    };
    const auto large_binomials = character_coefficients(recurrences()[0], large_indices);
    for (std::size_t i = 0; i < large_indices.size(); ++i) {
        const unsigned n = large_indices[i];
        require(large_binomials[i] % TWO_MOD == central_binomial_residue(n, 2, TWO_EXPONENT),
                "binomial product across powers of two");
        require(large_binomials[i] % FIVE_MOD == central_binomial_residue(n, 5, FIVE_EXPONENT),
                "binomial product across powers of five");
    }
    std::cout << "All checks passed; " << outcomes.size()
              << " original-game positions, " << CHARACTERS * indices.size()
              << " character coefficients, periodicity, and prime-power precision.\n";
}

unsigned parse_length(const std::string& text) {
    unsigned length = 0;
    const auto parsed = std::from_chars(text.data(), text.data() + text.size(), length);
    if (parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size() || length > MAX_LENGTH) {
        throw std::invalid_argument("Length must be an integer from 0 to 100000000");
    }
    return length;
}

}

int main(int argc, char* argv[]) {
    try {
        if (argc == 2 && std::string(argv[1]) == "--self-test") run_tests();
        else {
            if (argc > 2) throw std::invalid_argument("Usage: Euler1015 [n | --self-test]");
            const unsigned length = argc == 2 ? parse_length(argv[1]) : DEFAULT_LENGTH;
            std::cout << std::setfill('0') << std::setw(9) << solve(length) << '\n';
        }
    } catch (const std::exception& error) {
        std::cerr << error.what() << '\n';
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

Python

#!/usr/bin/env python3
"""Project Euler Problem 1015 - Partisan Kayles."""

import functools
import os
import sys
from collections import namedtuple

DEFAULT_LENGTH = 1000
MAX_LENGTH = 100_000_000
PREPERIOD = 53
PERIOD = 34
CHARACTERS = 16
TWO_EXPONENT = 13
FIVE_EXPONENT = 9
MOD = 1_000_000_000
SCALED_MOD = CHARACTERS * MOD
U64_MAX = (1 << 64) - 1


def power(base, exponent):
    result = 1
    for _ in range(exponent):
        result *= base
    return result


TWO_MOD = power(2, TWO_EXPONENT)
FIVE_MOD = power(5, FIVE_EXPONENT)
assert TWO_MOD * FIVE_MOD == SCALED_MOD


def require(condition, description):
    if not condition:
        raise RuntimeError("Check failed: " + description)


def grundy_values(limit):
    grundy = [0] * (limit + 1)
    seen = [0] * (limit + 2)
    for n in range(2, limit + 1):
        for left in range((n - 2) // 2 + 1):
            value = grundy[left] ^ grundy[n - 2 - left]
            if value < len(seen):
                seen[value] = n
        while seen[grundy[n]] == n:
            grundy[n] += 1
    return grundy


def character_sign(value):
    sign = 1
    while value:
        sign = -sign
        value &= value - 1
    return sign


def residue(value, modulus):
    # Python's % already returns a value in [0, modulus).
    return value % modulus


def quadratic_character(grundy, character, modulus):
    degree = (len(grundy) - 1) // 2
    odd = [0] * degree
    even = [0] * (degree + 1)
    numerator = [0] * (degree + 1)
    denominator = [0] * (degree + 1)
    for n in range(degree):
        odd[n] = character_sign(character & grundy[2 * n + 1])
    for n in range(1, degree + 1):
        even[n] = character_sign(character & grundy[2 * n])
    numerator[0] = denominator[0] = 1
    for n in range(1, degree + 1):
        common = 0
        for i in range(1, n):
            common += even[i] * even[n - i]
        for i in range(n):
            common -= odd[i] * odd[n - 1 - i]
        numerator[n] = common + 2 * even[n]
        denominator[n] = common - 2 * even[n]

    double_modulus = 2 * modulus
    square = [0] * (degree + 1)
    root = [0] * (degree + 1)
    square[0] = root[0] = 1
    for n in range(1, degree + 1):
        coefficient = numerator[n]
        for i in range(1, n + 1):
            coefficient -= denominator[i] * square[n - i]
        square[n] = residue(coefficient, double_modulus)
        products = 0
        i = 1
        while 2 * i < n:
            products += 2 * root[i] * root[n - i]
            i += 1
        if n % 2 == 0:
            products += root[n // 2] * root[n // 2]
        twice_root = (square[n] + double_modulus - products % double_modulus) % double_modulus
        require(twice_root % 2 == 0, "integral square-root coefficient")
        root[n] = twice_root // 2
    return root


def trim(polynomial):
    while len(polynomial) > 1 and polynomial[-1] == 0:
        polynomial.pop()


def product(a, b):
    result = [0] * (len(a) + len(b) - 1)
    for i in range(len(a)):
        for j in range(len(b)):
            result[i + j] += a[i] * b[j]
    trim(result)
    return result


def difference(a, b):
    a = a + [0] * max(0, len(b) - len(a))
    for i in range(len(b)):
        a[i] -= b[i]
    trim(a)
    return a


def derivative(polynomial):
    result = [0] * max(1, len(polynomial) - 1)
    for i in range(1, len(polynomial)):
        result[i - 1] = i * polynomial[i]
    trim(result)
    return result


def certify_period():
    END = 2 * PREPERIOD + PERIOD + 2
    grundy = grundy_values(END + PERIOD - 1)
    # Guy-Smith: this finite window certifies the period for every n >= PREPERIOD.
    for n in range(PREPERIOD, END):
        require(grundy[n] == grundy[n + PERIOD], "Grundy periodicity certificate")
    require(max(grundy) < CHARACTERS, "Walsh dimension")
    return grundy


Term = namedtuple("Term", "lag constant linear")
Recurrence = namedtuple("Recurrence", "width terms")


def make_recurrence(character, grundy):
    def sign(n):
        if n >= PREPERIOD:
            n = PREPERIOD + (n - PREPERIOD) % PERIOD
        return character_sign(character & grundy[n])

    HALF_PERIOD = PERIOD // 2
    ODD_LENGTH = (PREPERIOD - 1) // 2 + HALF_PERIOD
    EVEN_LENGTH = (PREPERIOD + 1) // 2 + HALF_PERIOD
    odd = [0] * ODD_LENGTH
    even = [0] * EVEN_LENGTH
    for i in range(ODD_LENGTH):
        odd[i] = sign(2 * i + 1) - (sign(2 * (i - HALF_PERIOD) + 1) if i >= HALF_PERIOD else 0)
    for i in range(1, EVEN_LENGTH):
        even[i] = sign(2 * i) - (sign(2 * (i - HALF_PERIOD)) if i > HALF_PERIOD else 0)
    plus = even[:]
    minus = [-value for value in even]
    plus[0] += 1
    minus[0] += 1
    plus[HALF_PERIOD] -= 1
    minus[HALF_PERIOD] -= 1
    odd_square = product(odd, odd)
    odd_square.insert(0, 0)
    p = difference(product(plus, plus), odd_square)
    q = difference(product(minus, minus), odd_square)
    t = product(p, q)
    u = difference(product(derivative(p), q), product(p, derivative(q)))
    # H^2 = P/Q gives (PQ)H' = (P'Q-PQ')H/2.
    for i in range(len(u)):
        require(u[i] % 2 == 0, "integral differential equation")
        u[i] //= 2
    require(t[0] == 1, "unit leading coefficient")
    width = max(len(t) - 1, len(u))
    terms = []
    for lag in range(1, width + 1):
        tj = t[lag] if lag < len(t) else 0
        uj = u[lag - 1] if lag <= len(u) else 0
        if tj != 0 or uj != 0:
            terms.append(Term(lag, uj + lag * tj, -tj))
    return Recurrence(width, terms)


@functools.cache
def recurrences():
    grundy = certify_period()
    return [make_recurrence(h, grundy) for h in range(CHARACTERS)]


def inverse(value, modulus):
    remainder = modulus
    next = value % modulus
    coefficient = 0
    next_coefficient = 1
    while next != 0:
        quotient = remainder // next
        temporary = remainder % next
        remainder = next
        next = temporary
        next_value = coefficient - quotient * next_coefficient
        coefficient = next_coefficient
        next_coefficient = next_value
    require(remainder == 1, "invertible unit")
    return residue(coefficient, modulus)


def working_modulus(prime, exponent, limit):
    logarithm = 0
    n = limit
    while n >= prime:
        logarithm += 1
        n //= prime
    # Integrating a residual modulo p^E loses at most L=floor(log_p n) digits.
    # E >= e+L preserves the target; E >= 2L permits every division.
    digits = max(exponent + logarithm, 2 * logarithm)
    modulus = 1
    for _ in range(digits):
        require(modulus <= U64_MAX // prime, "working modulus fits")
        modulus *= prime
    return modulus


def divide_step(numerator, n, prime, modulus):
    divisor = 1
    while n % prime == 0:
        n //= prime
        divisor *= prime
    value = residue(numerator, modulus)
    if value % divisor != 0:
        raise RuntimeError("Nonintegral prime-power division")
    reduced = modulus // divisor
    return value // divisor * inverse(n, reduced) % reduced


def combine(two, five):
    multiplier = inverse(FIVE_MOD % TWO_MOD, TWO_MOD)
    b = five % FIVE_MOD
    multiple = ((two % TWO_MOD + TWO_MOD - b % TWO_MOD) * multiplier) % TWO_MOD
    return b + FIVE_MOD * multiple


def character_coefficients(recurrence, indices):
    last = indices[-1]
    mod2 = working_modulus(2, TWO_EXPONENT, last)
    mod5 = working_modulus(5, FIVE_EXPONENT, last)
    width = recurrence.width
    history = [(0, 0)] * (2 * width)
    history[0] = history[width] = (1, 1)
    values = []
    next = 0
    if indices[0] == 0:
        values.append(1)
        next += 1
    for n in range(1, last + 1):
        position = n % width
        end = width + position
        numerator2 = numerator5 = 0
        for lag, constant, linear in recurrence.terms:
            if lag > n:
                break
            factor = constant + n * linear
            two, five = history[end - lag]
            numerator2 += factor * two
            numerator5 += factor * five
        current = (divide_step(numerator2, n, 2, mod2), divide_step(numerator5, n, 5, mod5))
        history[position] = history[end] = current
        if next < len(indices) and n == indices[next]:
            values.append(combine(*current))
            next += 1
    return values


def calculate_characters(equations, indices, coefficients, first, stride):
    for h in range(first, CHARACTERS, stride):
        coefficients[h] = character_coefficients(equations[h], indices)


def fair_counts_at(indices, thread_count=0):
    if not indices:
        return []
    equations = recurrences()
    if thread_count == 0:
        thread_count = 1 if indices[-1] < 64 else min(8, max(1, os.cpu_count() or 0))
    thread_count = min(thread_count, CHARACTERS)
    coefficients = [None] * CHARACTERS
    # The same stride classes as in the C++ version, computed one after another.
    for i in range(thread_count):
        calculate_characters(equations, indices, coefficients, i, thread_count)
    counts = [0] * len(indices)
    for character in coefficients:
        for i in range(len(counts)):
            counts[i] = (counts[i] + character[i]) % SCALED_MOD
    for i in range(len(counts)):
        require(counts[i] % CHARACTERS == 0, "integral Walsh average")
        counts[i] //= CHARACTERS
    return counts


def solve(length, thread_count=0):
    if length > MAX_LENGTH:
        raise ValueError("Supported length is at most 100000000")
    if length == 0:
        return 1
    if length % 2 != 0:
        return 0
    return fair_counts_at([length // 2], thread_count)[0]


def brute_outcomes(length, powers):
    powers[:] = [1] * (length + 1)
    for i in range(1, length + 1):
        powers[i] = 3 * powers[i - 1]
    outcomes = bytearray(powers[length])
    for state in range(1, len(outcomes)):
        remaining = state
        result = 0
        for i in range(length):
            if result == 3:
                break
            pin = remaining % 3
            remaining //= 3
            if pin == 0:
                continue
            single = state - pin * powers[i]
            if pin == 1 and not (outcomes[single] & 2):
                result |= 1
            if pin == 2 and not (outcomes[single] & 1):
                result |= 2
            next = remaining % 3
            if next == 0:
                continue
            pair = single - next * powers[i + 1]
            if (pin == 1 or next == 1) and not (outcomes[pair] & 2):
                result |= 1
            if (pin == 2 or next == 2) and not (outcomes[pair] & 1):
                result |= 2
        outcomes[state] = result
    return outcomes


def predicted_outcome(state, length, grundy):
    balance = 0
    previous = run = nim_sum = 0
    for _ in range(length):
        pin = state % 3
        state //= 3
        if pin == 1:
            balance += 1
        if pin == 2:
            balance -= 1
        if pin != 0 and previous != 0 and pin != previous:
            run += 1
        else:
            nim_sum ^= grundy[run]
            run = 0 if pin == 0 else 1
        previous = pin
    nim_sum ^= grundy[run]
    if balance > 0:
        return 1
    if balance < 0:
        return 2
    return 0 if nim_sum == 0 else 3


def central_binomial_residue(n, prime, exponent):
    modulus = power(prime, exponent)
    numerator = denominator = 1
    valuation = 0
    for i in range(1, n + 1):
        top = n + i
        bottom = i
        while top % prime == 0:
            top //= prime
            valuation += 1
        while bottom % prime == 0:
            bottom //= prime
            valuation -= 1
        numerator = numerator * top % modulus
        denominator = denominator * bottom % modulus
    require(valuation >= 0, "integral binomial coefficient")
    if valuation >= exponent:
        return 0
    return numerator * inverse(denominator, modulus) % modulus * power(prime, valuation) % modulus


def run_tests():
    SMALL = 12
    CHECK_LENGTH = 1000
    indices = list(range(CHECK_LENGTH // 2 + 1))
    counts = fair_counts_at(indices)
    require(counts[0] == 1, "empty arrangement")
    require(counts[3] == 8, "given f(6)")
    require(counts[10] == 49_844, "given f(20)")
    require(fair_counts_at(indices, 1) == counts, "serial and strided agreement")

    grundy = grundy_values(CHECK_LENGTH)
    expected_counts = [0] * len(indices)
    unsigned_counts = []
    for h in range(CHARACTERS):
        expected = quadratic_character(grundy, h, SCALED_MOD)
        require(character_coefficients(recurrences()[h], indices) == expected,
                "every character coefficient agrees with quadratic extraction")
        for i in range(len(indices)):
            expected_counts[i] = (expected_counts[i] + expected[i]) % SCALED_MOD
        if h == 0:
            unsigned_counts = expected
    for i in range(len(expected_counts)):
        expected_counts[i] //= CHARACTERS
    require(counts == expected_counts, "all fair counts agree with quadratic extraction")
    for n in range(PREPERIOD, CHECK_LENGTH + 1):
        require(grundy[n] == grundy[PREPERIOD + (n - PREPERIOD) % PERIOD], "periodic Grundy lookup")

    powers = []
    outcomes = brute_outcomes(SMALL, powers)
    for state in range(len(outcomes)):
        require(outcomes[state] == predicted_outcome(state, SMALL, grundy),
                "original-game minimax agrees with balance and alternating blocks")
    for n in range(SMALL + 1):
        expected = 0
        for word in range(1 << n):
            state = 0
            for i in range(n):
                state += (1 + ((word >> i) & 1)) * powers[i]
            expected += outcomes[state] == 0
        require(expected == (counts[n // 2] if n % 2 == 0 else 0), "exhaustive initial arrangements")
        require(solve(n, 1) == expected, "short-prefix consistency")

    for n in (14, 16, 18, 30, 32, 48, 50, 62, 64, 126, 128,
              248, 250, 254, 256, 510, 512, 998, 1000):
        require(solve(n, 1) == counts[n // 2], "agreement across working-precision boundaries")
    require(solve(MAX_LENGTH - 1) == 0, "large odd length")

    binomial = [0] * (CHECK_LENGTH + 1)
    binomial[0] = 1
    for n in range(1, CHECK_LENGTH + 1):
        for k in range(n, 0, -1):
            binomial[k] = (binomial[k] + binomial[k - 1]) % MOD
        if n % 2 == 0:
            require(unsigned_counts[n // 2] % MOD == binomial[n // 2], "central binomial coefficients")
    large_indices = [
        8191, 8192, 8193, 15624, 15625, 15626, 16383, 16384, 16385
    ]
    large_binomials = character_coefficients(recurrences()[0], large_indices)
    for i in range(len(large_indices)):
        n = large_indices[i]
        require(large_binomials[i] % TWO_MOD == central_binomial_residue(n, 2, TWO_EXPONENT),
                "binomial product across powers of two")
        require(large_binomials[i] % FIVE_MOD == central_binomial_residue(n, 5, FIVE_EXPONENT),
                "binomial product across powers of five")
    print(f"All checks passed; {len(outcomes)} original-game positions, "
          f"{CHARACTERS * len(indices)} character coefficients, "
          f"periodicity, and prime-power precision.")


def parse_length(text):
    digits = text.lstrip("0") or "0"
    if (not text or any(c not in "0123456789" for c in text)
            or len(digits) > len(str(MAX_LENGTH)) or int(digits) > MAX_LENGTH):
        raise ValueError("Length must be an integer from 0 to 100000000")
    return int(digits)


def main(argv):
    try:
        if len(argv) == 2 and argv[1] == "--self-test":
            run_tests()
        else:
            if len(argv) > 2:
                raise ValueError("Usage: Euler1015.py [n | --self-test]")
            length = parse_length(argv[1]) if len(argv) == 2 else DEFAULT_LENGTH
            print(f"{solve(length):09d}")
    except (ValueError, RuntimeError) as error:
        print(error, file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv))

Java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.IntUnaryOperator;

public class Euler1015 {
    private static final int DEFAULT_LENGTH = 1000;
    private static final int MAX_LENGTH = 100_000_000;
    private static final int PREPERIOD = 53;
    private static final int PERIOD = 34;
    private static final int CHARACTERS = 16;
    private static final int TWO_EXPONENT = 13;
    private static final int FIVE_EXPONENT = 9;
    private static final long MOD = 1_000_000_000L;
    private static final long SCALED_MOD = CHARACTERS * MOD;
    private static final long TWO_MOD = power(2, TWO_EXPONENT);
    private static final long FIVE_MOD = power(5, FIVE_EXPONENT);

    static {
        require(TWO_MOD * FIVE_MOD == SCALED_MOD, "scaled modulus factors as 2^13 * 5^9");
    }

    static long power(long base, int exponent) {
        long result = 1;
        for (int i = 0; i < exponent; ++i) result = Math.multiplyExact(result, base);
        return result;
    }

    private static void require(boolean condition, String description) {
        if (!condition) throw new IllegalStateException("Check failed: " + description);
    }

    // Java has no 128-bit integer: high * 2^64 + (unsigned) low stands in for the C++ __int128.
    private static final class Int128 {
        long high, low;

        static Int128 product(long a, long b) {
            Int128 result = new Int128();
            result.addProduct(a, b);
            return result;
        }

        // this += a * b, exactly; addExact throws where the 128-bit value would overflow.
        void addProduct(long a, long b) {
            long sum = low + a * b;
            long carry = Long.compareUnsigned(sum, low) < 0 ? 1 : 0;
            high = Math.addExact(high, Math.multiplyHigh(a, b) + carry);
            low = sum;
        }
    }

    static int[] grundyValues(int limit) {
        int[] grundy = new int[limit + 1], seen = new int[limit + 2];
        for (int n = 2; n <= limit; ++n) {
            for (int left = 0; left <= (n - 2) / 2; ++left) {
                int value = grundy[left] ^ grundy[n - 2 - left];
                if (value < seen.length) seen[value] = n;
            }
            while (seen[grundy[n]] == n) ++grundy[n];
        }
        return grundy;
    }

    static int characterSign(int value) {
        int sign = 1;
        for (; value != 0; value &= value - 1) sign = -sign;
        return sign;
    }

    static long residue(long value, long modulus) {
        value %= modulus;
        if (value < 0) value += modulus;
        return value;
    }

    // Long division of high * 2^64 + low: each step brings down as many bits of low as keep
    // result * 2^bits below 2^64 (the modulus is positive).
    static long residue(Int128 value, long modulus) {
        long result = residue(value.high, modulus);
        int step = Long.numberOfLeadingZeros(modulus);
        for (int remaining = 64; remaining > 0; ) {
            int bits = Math.min(step, remaining);
            remaining -= bits;
            long chunk = (value.low >>> remaining) & ((1L << bits) - 1);
            result = Long.remainderUnsigned(result << bits | chunk, modulus);
        }
        return result;
    }

    static long[] quadraticCharacter(int[] grundy, int character, long modulus) {
        int degree = (grundy.length - 1) / 2;
        int[] odd = new int[degree], even = new int[degree + 1];
        int[] numerator = new int[degree + 1], denominator = new int[degree + 1];
        for (int n = 0; n < degree; ++n) odd[n] = characterSign(character & grundy[2 * n + 1]);
        for (int n = 1; n <= degree; ++n) even[n] = characterSign(character & grundy[2 * n]);
        numerator[0] = denominator[0] = 1;
        for (int n = 1; n <= degree; ++n) {
            int common = 0;
            for (int i = 1; i < n; ++i) common += even[i] * even[n - i];
            for (int i = 0; i < n; ++i) common -= odd[i] * odd[n - 1 - i];
            numerator[n] = common + 2 * even[n];
            denominator[n] = common - 2 * even[n];
        }

        long doubleModulus = Math.multiplyExact(2L, modulus);
        long[] square = new long[degree + 1], root = new long[degree + 1];
        square[0] = root[0] = 1;
        for (int n = 1; n <= degree; ++n) {
            // |denominator[i]| <= 2i + 1 and square < 2M keep this sum far below 2^63 here.
            long coefficient = numerator[n];
            for (int i = 1; i <= n; ++i) {
                coefficient = Math.subtractExact(coefficient, Math.multiplyExact((long) denominator[i], square[n - i]));
            }
            square[n] = residue(coefficient, doubleModulus);
            Int128 products = new Int128();
            for (int i = 1; 2 * i < n; ++i) products.addProduct(Math.multiplyExact(2L, root[i]), root[n - i]);
            if (n % 2 == 0) products.addProduct(root[n / 2], root[n / 2]);
            long twiceRoot = (Math.addExact(square[n], doubleModulus)
                - residue(products, doubleModulus)) % doubleModulus;
            require(twiceRoot % 2 == 0, "integral square-root coefficient");
            root[n] = twiceRoot / 2;
        }
        return root;
    }

    static long[] trim(long[] polynomial) {
        int size = polynomial.length;
        while (size > 1 && polynomial[size - 1] == 0) --size;
        return Arrays.copyOf(polynomial, size);
    }

    static long[] product(long[] a, long[] b) {
        long[] result = new long[a.length + b.length - 1];
        for (int i = 0; i < a.length; ++i) {
            for (int j = 0; j < b.length; ++j) result[i + j] = Math.addExact(result[i + j], Math.multiplyExact(a[i], b[j]));
        }
        return trim(result);
    }

    static long[] difference(long[] a, long[] b) {
        a = Arrays.copyOf(a, Math.max(a.length, b.length));
        for (int i = 0; i < b.length; ++i) a[i] = Math.subtractExact(a[i], b[i]);
        return trim(a);
    }

    static long[] derivative(long[] polynomial) {
        long[] result = new long[Math.max(1, polynomial.length - 1)];
        for (int i = 1; i < polynomial.length; ++i) result[i - 1] = Math.multiplyExact((long) i, polynomial[i]);
        return trim(result);
    }

    static int[] certifyPeriod() {
        final int END = 2 * PREPERIOD + PERIOD + 2;
        int[] grundy = grundyValues(END + PERIOD - 1);
        // Guy-Smith: this finite window certifies the period for every n >= PREPERIOD.
        for (int n = PREPERIOD; n < END; ++n) {
            require(grundy[n] == grundy[n + PERIOD], "Grundy periodicity certificate");
        }
        require(Arrays.stream(grundy).max().getAsInt() < CHARACTERS, "Walsh dimension");
        return grundy;
    }

    private record Term(int lag, long constant, long linear) {}

    private record Recurrence(int width, Term[] terms) {}

    static Recurrence makeRecurrence(int character, int[] grundy) {
        IntUnaryOperator sign = n -> {
            if (n >= PREPERIOD) n = PREPERIOD + (n - PREPERIOD) % PERIOD;
            return characterSign(character & grundy[n]);
        };
        final int HALF_PERIOD = PERIOD / 2;
        final int ODD_LENGTH = (PREPERIOD - 1) / 2 + HALF_PERIOD;
        final int EVEN_LENGTH = (PREPERIOD + 1) / 2 + HALF_PERIOD;
        long[] odd = new long[ODD_LENGTH], even = new long[EVEN_LENGTH];
        for (int i = 0; i < ODD_LENGTH; ++i) {
            odd[i] = sign.applyAsInt(2 * i + 1) - (i >= HALF_PERIOD ? sign.applyAsInt(2 * (i - HALF_PERIOD) + 1) : 0);
        }
        for (int i = 1; i < EVEN_LENGTH; ++i) {
            even[i] = sign.applyAsInt(2 * i) - (i > HALF_PERIOD ? sign.applyAsInt(2 * (i - HALF_PERIOD)) : 0);
        }
        long[] plus = even.clone(), minus = even.clone();
        for (int i = 0; i < minus.length; ++i) minus[i] = -minus[i];
        ++plus[0];
        ++minus[0];
        --plus[HALF_PERIOD];
        --minus[HALF_PERIOD];
        long[] oddProduct = product(odd, odd);
        long[] oddSquare = new long[oddProduct.length + 1];
        System.arraycopy(oddProduct, 0, oddSquare, 1, oddProduct.length);
        long[] p = difference(product(plus, plus), oddSquare);
        long[] q = difference(product(minus, minus), oddSquare);
        long[] t = product(p, q);
        long[] u = difference(product(derivative(p), q), product(p, derivative(q)));
        // H^2 = P/Q gives (PQ)H' = (P'Q-PQ')H/2.
        for (int i = 0; i < u.length; ++i) {
            require(u[i] % 2 == 0, "integral differential equation");
            u[i] /= 2;
        }
        require(t[0] == 1, "unit leading coefficient");
        int width = Math.max(t.length - 1, u.length);
        List<Term> terms = new ArrayList<>();
        for (int lag = 1; lag <= width; ++lag) {
            long tj = lag < t.length ? t[lag] : 0;
            long uj = lag <= u.length ? u[lag - 1] : 0;
            if (tj != 0 || uj != 0) terms.add(new Term(lag, Math.addExact(uj, Math.multiplyExact((long) lag, tj)), -tj));
        }
        return new Recurrence(width, terms.toArray(new Term[0]));
    }

    private static Recurrence[] recurrenceTable;

    static synchronized Recurrence[] recurrences() {
        if (recurrenceTable == null) {
            int[] grundy = certifyPeriod();
            Recurrence[] values = new Recurrence[CHARACTERS];
            for (int h = 0; h < CHARACTERS; ++h) values[h] = makeRecurrence(h, grundy);
            recurrenceTable = values;
        }
        return recurrenceTable;
    }

    static long inverse(long value, long modulus) {
        long remainder = modulus, next = value % modulus;
        // The Bezout coefficients never exceed the modulus in absolute value, so a long holds them.
        long coefficient = 0, nextCoefficient = 1;
        while (next != 0) {
            long quotient = remainder / next;
            long temporary = remainder % next;
            remainder = next;
            next = temporary;
            long nextValue = Math.subtractExact(coefficient, Math.multiplyExact(quotient, nextCoefficient));
            coefficient = nextCoefficient;
            nextCoefficient = nextValue;
        }
        require(remainder == 1, "invertible unit");
        return residue(coefficient, modulus);
    }

    static long workingModulus(int prime, int exponent, int limit) {
        int logarithm = 0;
        for (int n = limit; n >= prime; n /= prime) ++logarithm;
        // Integrating a residual modulo p^E loses at most L=floor(log_p n) digits.
        // E >= e+L preserves the target; E >= 2L permits every division.
        int digits = Math.max(exponent + logarithm, 2 * logarithm);
        long modulus = 1;
        for (int i = 0; i < digits; ++i) {
            require(modulus <= Long.MAX_VALUE / prime, "working modulus fits");
            modulus *= prime;
        }
        return modulus;
    }

    static long divideStep(Int128 numerator, int n, int prime, long modulus) {
        long divisor = 1;
        while (n % prime == 0) {
            n /= prime;
            divisor *= prime;
        }
        long value = residue(numerator, modulus);
        if (value % divisor != 0) throw new IllegalStateException("Nonintegral prime-power division");
        long reduced = modulus / divisor;
        return residue(Int128.product(value / divisor, inverse(n, reduced)), reduced);
    }

    private static final long COMBINE_MULTIPLIER = inverse(FIVE_MOD % TWO_MOD, TWO_MOD);

    static long combine(long two, long five) {
        long b = five % FIVE_MOD;
        long multiple = ((two % TWO_MOD + TWO_MOD - b % TWO_MOD) * COMBINE_MULTIPLIER) % TWO_MOD;
        return b + FIVE_MOD * multiple;
    }

    static long[] characterCoefficients(Recurrence recurrence, int[] indices) {
        int last = indices[indices.length - 1];
        long mod2 = workingModulus(2, TWO_EXPONENT, last);
        long mod5 = workingModulus(5, FIVE_EXPONENT, last);
        int width = recurrence.width();
        // The C++ history of (two, five) residue pairs, kept as two arrays.
        long[] historyTwo = new long[2 * width], historyFive = new long[2 * width];
        historyTwo[0] = historyTwo[width] = 1;
        historyFive[0] = historyFive[width] = 1;
        long[] values = new long[indices.length];
        int next = 0;
        if (indices[0] == 0) values[next++] = 1;
        for (int n = 1; n <= last; ++n) {
            int position = n % width;
            int end = width + position;
            Int128 numerator2 = new Int128(), numerator5 = new Int128();
            for (Term term : recurrence.terms()) {
                if (term.lag() > n) break;
                long factor = Math.addExact(term.constant(), Math.multiplyExact((long) n, term.linear()));
                int previous = end - term.lag();
                numerator2.addProduct(factor, historyTwo[previous]);
                numerator5.addProduct(factor, historyFive[previous]);
            }
            long two = divideStep(numerator2, n, 2, mod2), five = divideStep(numerator5, n, 5, mod5);
            historyTwo[position] = historyTwo[end] = two;
            historyFive[position] = historyFive[end] = five;
            if (next < indices.length && n == indices[next]) values[next++] = combine(two, five);
        }
        return Arrays.copyOf(values, next);
    }

    private static final class CharacterWork {
        final Recurrence[] recurrences;
        final int[] indices;
        final long[][] coefficients;
        final int first, stride;
        RuntimeException error;

        CharacterWork(Recurrence[] recurrences, int[] indices, long[][] coefficients, int first, int stride) {
            this.recurrences = recurrences;
            this.indices = indices;
            this.coefficients = coefficients;
            this.first = first;
            this.stride = stride;
        }
    }

    private static void calculateCharacters(CharacterWork work) {
        try {
            for (int h = work.first; h < CHARACTERS; h += work.stride) {
                work.coefficients[h] = characterCoefficients(work.recurrences[h], work.indices);
            }
        } catch (RuntimeException error) {
            work.error = error;
        }
    }

    static long[] fairCountsAt(int[] indices) {
        return fairCountsAt(indices, 0);
    }

    static long[] fairCountsAt(int[] indices, int threadCount) {
        if (indices.length == 0) return new long[0];
        Recurrence[] equations = recurrences();
        if (threadCount == 0) {
            threadCount = indices[indices.length - 1] < 64 ? 1
                : Math.min(8, Math.max(1, Runtime.getRuntime().availableProcessors()));
        }
        threadCount = Math.min(threadCount, CHARACTERS);
        long[][] coefficients = new long[CHARACTERS][];
        CharacterWork[] work = new CharacterWork[threadCount];
        for (int i = 0; i < threadCount; ++i) {
            work[i] = new CharacterWork(equations, indices, coefficients, i, threadCount);
        }
        // As in the C++, work[0] runs on the calling thread and the others on worker threads.
        ExecutorService pool = threadCount > 1 ? Executors.newFixedThreadPool(threadCount - 1) : null;
        try {
            List<Future<?>> started = new ArrayList<>();
            for (int i = 1; i < threadCount; ++i) {
                CharacterWork job = work[i];
                started.add(pool.submit(() -> calculateCharacters(job)));
            }
            calculateCharacters(work[0]);
            for (Future<?> thread : started) thread.get();
        } catch (InterruptedException error) {
            Thread.currentThread().interrupt();
            throw new IllegalStateException("Interrupted while waiting for character workers", error);
        } catch (ExecutionException error) {
            throw new IllegalStateException("Character worker failed: " + error.getCause(), error.getCause());
        } finally {
            if (pool != null) pool.shutdown();
        }
        for (CharacterWork job : work) {
            if (job.error != null) throw job.error;
        }
        long[] counts = new long[indices.length];
        for (long[] character : coefficients) {
            for (int i = 0; i < counts.length; ++i) counts[i] = (counts[i] + character[i]) % SCALED_MOD;
        }
        for (int i = 0; i < counts.length; ++i) {
            require(counts[i] % CHARACTERS == 0, "integral Walsh average");
            counts[i] /= CHARACTERS;
        }
        return counts;
    }

    static long solve(int length) {
        return solve(length, 0);
    }

    static long solve(int length, int threadCount) {
        if (length > MAX_LENGTH) throw new IllegalArgumentException("Supported length is at most 100000000");
        if (length == 0) return 1;
        if (length % 2 != 0) return 0;
        return fairCountsAt(new int[] {length / 2}, threadCount)[0];
    }

    // Fills powers (length + 1 entries) with 3^i, like the C++ output parameter.
    static byte[] bruteOutcomes(int length, int[] powers) {
        Arrays.fill(powers, 1);
        for (int i = 1; i <= length; ++i) powers[i] = 3 * powers[i - 1];
        byte[] outcomes = new byte[powers[length]];
        for (int state = 1; state < outcomes.length; ++state) {
            int remaining = state;
            int result = 0;
            for (int i = 0; i < length && result != 3; ++i) {
                int pin = remaining % 3;
                remaining /= 3;
                if (pin == 0) continue;
                int single = state - pin * powers[i];
                if (pin == 1 && (outcomes[single] & 2) == 0) result |= 1;
                if (pin == 2 && (outcomes[single] & 1) == 0) result |= 2;
                int next = remaining % 3;
                if (next == 0) continue;
                int pair = single - next * powers[i + 1];
                if ((pin == 1 || next == 1) && (outcomes[pair] & 2) == 0) result |= 1;
                if ((pin == 2 || next == 2) && (outcomes[pair] & 1) == 0) result |= 2;
            }
            outcomes[state] = (byte) result;
        }
        return outcomes;
    }

    static int predictedOutcome(int state, int length, int[] grundy) {
        int balance = 0;
        int previous = 0, run = 0, nimSum = 0;
        for (int i = 0; i < length; ++i) {
            int pin = state % 3;
            state /= 3;
            if (pin == 1) ++balance;
            if (pin == 2) --balance;
            if (pin != 0 && previous != 0 && pin != previous) ++run;
            else {
                nimSum ^= grundy[run];
                run = pin == 0 ? 0 : 1;
            }
            previous = pin;
        }
        nimSum ^= grundy[run];
        if (balance > 0) return 1;
        if (balance < 0) return 2;
        return nimSum == 0 ? 0 : 3;
    }

    static long centralBinomialResidue(int n, int prime, int exponent) {
        long modulus = power(prime, exponent);
        long numerator = 1, denominator = 1;
        int valuation = 0;
        for (int i = 1; i <= n; ++i) {
            int top = n + i, bottom = i;
            while (top % prime == 0) {
                top /= prime;
                ++valuation;
            }
            while (bottom % prime == 0) {
                bottom /= prime;
                --valuation;
            }
            numerator = Math.multiplyExact(numerator, (long) top) % modulus;
            denominator = Math.multiplyExact(denominator, (long) bottom) % modulus;
        }
        require(valuation >= 0, "integral binomial coefficient");
        if (valuation >= exponent) return 0;
        return Math.multiplyExact(Math.multiplyExact(numerator, inverse(denominator, modulus)) % modulus,
            power(prime, valuation)) % modulus;
    }

    private static void runTests() {
        final int SMALL = 12;
        final int CHECK_LENGTH = 1000;
        int[] indices = new int[CHECK_LENGTH / 2 + 1];
        for (int i = 0; i < indices.length; ++i) indices[i] = i;
        long[] counts = fairCountsAt(indices);
        require(counts[0] == 1, "empty arrangement");
        require(counts[3] == 8, "given f(6)");
        require(counts[10] == 49_844, "given f(20)");
        require(Arrays.equals(fairCountsAt(indices, 1), counts), "serial and thread-pool agreement");

        int[] grundy = grundyValues(CHECK_LENGTH);
        long[] expectedCounts = new long[indices.length], unsignedCounts = null;
        for (int h = 0; h < CHARACTERS; ++h) {
            long[] expected = quadraticCharacter(grundy, h, SCALED_MOD);
            require(Arrays.equals(characterCoefficients(recurrences()[h], indices), expected),
                "every character coefficient agrees with quadratic extraction");
            for (int i = 0; i < indices.length; ++i) {
                expectedCounts[i] = (expectedCounts[i] + expected[i]) % SCALED_MOD;
            }
            if (h == 0) unsignedCounts = expected;
        }
        for (int i = 0; i < expectedCounts.length; ++i) expectedCounts[i] /= CHARACTERS;
        require(Arrays.equals(counts, expectedCounts), "all fair counts agree with quadratic extraction");
        for (int n = PREPERIOD; n <= CHECK_LENGTH; ++n) {
            require(grundy[n] == grundy[PREPERIOD + (n - PREPERIOD) % PERIOD], "periodic Grundy lookup");
        }

        int[] powers = new int[SMALL + 1];
        byte[] outcomes = bruteOutcomes(SMALL, powers);
        for (int state = 0; state < outcomes.length; ++state) {
            require(outcomes[state] == predictedOutcome(state, SMALL, grundy),
                "original-game minimax agrees with balance and alternating blocks");
        }
        for (int n = 0; n <= SMALL; ++n) {
            long expected = 0;
            for (int word = 0; word < (1 << n); ++word) {
                int state = 0;
                for (int i = 0; i < n; ++i) state += (1 + ((word >> i) & 1)) * powers[i];
                expected += outcomes[state] == 0 ? 1 : 0;
            }
            require(expected == (n % 2 == 0 ? counts[n / 2] : 0), "exhaustive initial arrangements");
            require(solve(n, 1) == expected, "short-prefix consistency");
        }

        for (int n : new int[] {14, 16, 18, 30, 32, 48, 50, 62, 64, 126, 128,
                                248, 250, 254, 256, 510, 512, 998, 1000}) {
            require(solve(n, 1) == counts[n / 2], "agreement across working-precision boundaries");
        }
        require(solve(MAX_LENGTH - 1) == 0, "large odd length");

        long[] binomial = new long[CHECK_LENGTH + 1];
        binomial[0] = 1;
        for (int n = 1; n <= CHECK_LENGTH; ++n) {
            for (int k = n; k > 0; --k) binomial[k] = (binomial[k] + binomial[k - 1]) % MOD;
            if (n % 2 == 0) require(unsignedCounts[n / 2] % MOD == binomial[n / 2], "central binomial coefficients");
        }
        int[] largeIndices = {8191, 8192, 8193, 15624, 15625, 15626, 16383, 16384, 16385};
        long[] largeBinomials = characterCoefficients(recurrences()[0], largeIndices);
        for (int i = 0; i < largeIndices.length; ++i) {
            int n = largeIndices[i];
            require(largeBinomials[i] % TWO_MOD == centralBinomialResidue(n, 2, TWO_EXPONENT),
                "binomial product across powers of two");
            require(largeBinomials[i] % FIVE_MOD == centralBinomialResidue(n, 5, FIVE_EXPONENT),
                "binomial product across powers of five");
        }
        System.out.println("All checks passed; " + outcomes.length
            + " original-game positions, " + CHARACTERS * indices.length
            + " character coefficients, periodicity, and prime-power precision.");
    }

    // Like std::from_chars into an unsigned value: decimal digits only, no sign or spaces.
    static int parseLength(String text) {
        long length = 0;
        boolean digits = !text.isEmpty();
        for (int i = 0; i < text.length() && digits && length <= MAX_LENGTH; ++i) {
            char digit = text.charAt(i);
            digits = digit >= '0' && digit <= '9';
            length = 10 * length + (digit - '0');
        }
        if (!digits || length > MAX_LENGTH) {
            throw new IllegalArgumentException("Length must be an integer from 0 to 100000000");
        }
        return (int) length;
    }

    public static void main(String[] args) {
        try {
            if (args.length == 1 && args[0].equals("--self-test")) runTests();
            else {
                if (args.length > 1) throw new IllegalArgumentException("Usage: java Euler1015 [n | --self-test]");
                int length = args.length == 1 ? parseLength(args[0]) : DEFAULT_LENGTH;
                System.out.println(String.format("%09d", solve(length)));
            }
        } catch (RuntimeException error) {
            System.err.println(error.getMessage());
            System.exit(1);
        }
    }
}