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 with unique elements. Two players P and Q are playing a game where at each move, a player picks two numbers a and b from the array and adds |a - b| to the array if it's not already present. The player who cannot make a move loses the game. We need to find the winner if player P always starts first.

So, if the input is like A = [8, 9, 10], then the output will be P.

Algorithm

To solve this problem, we follow these steps:

  • Calculate the GCD of all elements in the array

  • Find the maximum value in the array

  • Calculate total possible moves: (max_val / gcd) - n

  • If total moves is odd, player P wins; otherwise, player Q wins

Example

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[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'

# Test the function
arr = [8, 9, 10]
print(f"Array: {arr}")
print(f"Winner: {who_is_the_winner(arr)}")
Array: [8, 9, 10]
Winner: P

How It Works

The algorithm works based on the mathematical insight that:

  • The GCD of all elements determines the minimum possible difference

  • All possible differences will be multiples of this GCD

  • The total number of possible moves equals the count of multiples of GCD between the minimum and maximum values, minus the initial array size

  • Since players alternate turns, the winner depends on whether the total moves is odd or even

Step-by-Step Trace

For the example [8, 9, 10]:

from math import gcd

arr = [8, 9, 10]
print(f"Initial array: {arr}")

# Calculate GCD
g = gcd(gcd(8, 9), 10)
print(f"GCD of all elements: {g}")

# Find maximum
max_val = max(arr)
print(f"Maximum value: {max_val}")

# Calculate total moves
total = (max_val // g) - len(arr)
print(f"Total possible moves: {total}")

# Determine winner
winner = 'P' if total % 2 == 1 else 'Q'
print(f"Winner: {winner}")
Initial array: [8, 9, 10]
GCD of all elements: 1
Maximum value: 10
Total possible moves: 7
Winner: P

Conclusion

This game theory problem uses mathematical insights about GCD and parity to determine the winner efficiently. Player P wins when the total number of possible moves is odd, making it a clever application of number theory in competitive programming.

Updated on: 2026-03-25T09:59:15+05:30

209 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements