Define a game value for a pile of size as follows.
The answer is Second if , and otherwise.
The current player chooses a partition into three positive parts, while the opponent chooses which part survives. The current player can force a pile's game value to become exactly when a partition exists in which all three parts have value . Hence define
The stated formula satisfies : if , then every value can be forced, but itself cannot. To see this, write with . When all three parts have positive game value , write them as with . Their indices must satisfy or . If the last ternary digits of are nonzero and the next digit is zero, neither target can be represented by three indices of the same type. For any smaller , a representation can be constructed digit by digit. The case follows by using three parts congruent to or modulo . If , no three value-zero parts can sum to .
Now let be the XOR of the values of all piles. If , choose a pile whose value contains the highest set bit of . The other piles' XOR is smaller than this pile's value and can be forced using a suitable three-way split. Thus the opponent must move to a position with XOR zero. If , no split can make all three choices retain the old value, so the opponent can always choose a pile that leaves a nonzero XOR. Therefore, the XOR rule determines the winner.
The time complexity is , and the auxiliary space complexity is .
First