Project Euler Problem 560

Coprime Nim is just like ordinary normal play Nim, but the players may only remove a number of stones from a pile that i

Project Euler Problem 560

Solution

Answer: 994345168

The Sprague–Grundy values for a pile of size $n$ in Coprime Nim collapse to a very small structure:

  • $g(1)=1$
  • for even $n$, $g(n)=0$
  • for odd $n>1$, $g(n)=1$

Thus a losing $k$-pile position is exactly one whose XOR of pile Grundy values is $0$.

Let

  • $E$ = number of even pile sizes in ${1,\dots,n-1}$
  • $O$ = number of odd pile sizes in ${1,\dots,n-1}$

For $n=10^7$:

  • $E=4,999,999$
  • $O=5,000,000$

A pile contributes Grundy value $0$ iff it is even, and $1$ iff it is odd.

Therefore the number of losing positions is the number of $k$-tuples with an even number of odd piles:

$$L(n,k) = \sum_{\substack{j=0\ j\text{ even}}}^{k} \binom{k}{j} O^j E^{k-j} = \frac{(E+O)^k + (E-O)^k}{2}.$$

Substituting $n=k=10^7$:

$$L(10^7,10^7) = \frac{(9,999,999)^{10^7} + 1}{2} \pmod{1,000,000,007}.$$

Evaluating this modular exponentiation gives:

$$994345168.$$

This matches independently published computations for Problem 560.

Answer: 994345168