Suppose we have an array A of positive integers, the elements are unique, now, two players P and Q are playing a game. At each move, any one player picks two numbers a and b from the array and if |a – b| is not in the array after that the player adds this number to the array. When a player cannot make the move loses the game. We have to find the winner of the game if player P always starts the game.
So, if the input is like A = [8,9,10], then the output will be P.
To solve this, we will follow these steps −
n := size of arr
g := arr, max_val := arr
for i in range 1 to n, do
g := gcd(g, arr[i])
max_val := maximum of max_val, arr[i]
total :=(max_val / g) - n
if total is odd, then
Let us see the following implementation to get better understanding −
from math import gcd def who_is_the_winner(arr) : n = len(arr) g = arr max_val = arr for i in range(1, n) : g = gcd(g, arr[i]) max_val = max(max_val, arr[i]) total = (max_val / g) - n if (total % 2 == 1) : return 'P' return 'Q' arr = [8,9,10] print(who_is_the_winner(arr))