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:
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)$$$.