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

Given an array arr[] of positive distinct integers, two players A and B are playing a game. At each move, a player selects two numbers x and y from the array and if |x – y| is not present in the array then the player adds this number to the array (size of the array increases by 1). The player who can’t make the move loses the game. The task is to find the winner of the game if players A always starts the game.

Examples:

Input: arr[] = {2, 3}Output: A
After A’s move, array will be {2, 3, 1} and B can’t make any move.

Approach: Observe here that at the end of the game (when there are no more moves to make), the resultant array will contain all the multiples of the gcd of the original array upto the maximum element of the original array.

For example, arr[] = {8, 10}
Since, gcd(8, 10) = 2. So the resultant array at the end of the game will contain all the multiples of 2 ≤ max(arr) i.e. 10.
Hence, arr[] = {2, 4, 6, 8, 10}

From the above observation, the number of moves that can be performed on the original array can be found which will determine the winner of the game, if the number of moves is even then B will be the winner of the game else A wins the game.
Number of moves can be found as, (max(arr) / gcd) – n where gcd is the gcd of the original array elements and max(arr) / gcd gives the total number of elements in the resultant array. Subtracting original count of elements from the count of elements in the resultant array will give the number of moves.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.