A Mess Nobody Needs

According to the Sprague-Grundy theorem, if we calculate the Grundy function for each thread and then take the xor of all the obtained values, we will get a value of $$$=0$$$ if Petya's position is losing, and a value $$$>0$$$ otherwise. The only problem is that the constraints on the lengths of the threads in the problem are quite large, so it is not possible to calculate the Grundy function by definition.

To solve this, let's learn to calculate the Grundy function for a thread of length $$$x$$$. First, let's write down the value of the Grundy function by definition: $$$$$$ g(x) = \operatorname{mex} \bigl\{\, g(a)\oplus g(b) \bigm| a+b = x,\ \gcd(a,b) > 1 \bigr\}. $$$$$$

It is claimed that: $$$$$$ g(x) = \begin{cases} 0, & \text{if } x = 2 \text{ or } x \text{ is odd},\\ 1, & \text{if } x \equiv 0 \pmod{4},\\ 2, & \text{if } x \equiv 2 \pmod{4}. \end{cases} $$$$$$

During the contest, it was not difficult to notice this pattern by calculating the Grundy function for small lengths. Now we will prove it by induction:

The base case for $$$1 \leq x \leq 3$$$ is obvious.

Assume the statement is true for all $$$s < x$$$, then we will prove it for $$$x$$$.

Consider 3 cases:

  1. $$$x$$$ is odd. Then all partitions $$$x = a+b$$$ have the form: (even number $$$>2$$$) + odd. The even number cannot be equal to two, as in that case the second condition will not be satisfied: there will necessarily be $$$\gcd(2, x - 2) = 1$$$. Thus, by the induction hypothesis, $$$g(\text{odd}) = 0$$$, $$$g(\text{even})>0$$$, so their $$$\oplus$$$ will be $$$>0$$$, meaning that in the set $$$\bigl\{\, g(a)\oplus g(b) \bigm| a+b = x,\ \gcd(a,b) > 1 \bigr\}$$$ all numbers will be $$$>0$$$, hence its $$$\operatorname{mex}$$$ will be zero. Therefore, the Grundy function for an odd number is zero.

  2. $$$x \equiv 0 \pmod{4}$$$. Take the partition $$$x = \frac{x}{2} + \frac{x}{2}$$$, we get $$$g(\frac{x}{2}) \oplus g(\frac{x}{2}) = 0$$$. At the same time, xor $$$=1$$$ cannot be obtained, as cutting into 2 odd numbers will give $$$0$$$, while cutting into 2 even numbers will give $$$0$$$ or $$$3$$$. Hence, the $$$\operatorname{mex}$$$ will be equal to $$$1$$$.

  3. $$$x \equiv 2 \pmod{4}$$$. Considering the partitions $$$n = \frac{n}{2} + \frac{n}{2}$$$ and $$$n = 2 + (n - 2)$$$, we get xor equal to $$$0$$$ and $$$1$$$, respectively. From the parity of $$$x$$$, it is clear that xor equal to $$$2$$$ is impossible. Thus, $$$g(x) = 2$$$.

Next, we needed to calculate the Grundy function for the lengths of all threads and take the xor of the obtained values.

In total, the solution works in $$$\mathcal{O}(n)$$$.