- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

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

## 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' arr = [8,9,10] print(who_is_the_winner(arr))

## Input

[8,9,10]

## Output

P

- Related Articles
- Absolute Difference of all pairwise consecutive elements in an array (C++)?
- Check if the elements of stack are pairwise sorted in Python
- Adding elements of an array until every element becomes greater than or equal to k in C++.
- Program to find winner of array removal game in Python
- Program to find the winner of an array game using Python
- Reduce array's dimension by adding all the elements in Numpy
- Program to find minimum possible difference of indices of adjacent elements in Python
- Find the sum of maximum difference possible from all subset of a given array in Python
- How to find the cross product of two vectors in R by adding the elements?
- C++ program to Adding elements of an array until every element becomes greater than or equal to k
- Check if Queue Elements are pairwise consecutive in Python
- Maximize the median of the given array after adding K elements to the same array in C++
- Adding and Removing Elements in Perl Array
- How to find the absolute pairwise difference among values of a vector in R?
- Program to find winner of stone game in Python