Find the winner by adding Pairwise difference of elements in the array until Possible in Python

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[0], max_val := arr[0]

  • 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

    • return 'P'

  • return 'Q'


Let us see the following implementation to get better understanding −

 Live Demo

from math import gcd
def who_is_the_winner(arr) :
   n = len(arr)
   g = arr[0]
   max_val = arr[0]
   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]