Find the player to be able to replace the last element that can be replaced by its divisors
Given an array arr[] consisting of N integers and two players A and B playing a game together by performing the following operations:
- Choose an integer from arr[] and replace that number with one of its divisors.
- A previously selected integer cannot be chosen again.
- As 1 does not have any divisor other than itself, a player cannot replace 1 with any other number. Hence, when the array consists of only 1s, the player who cannot make any move loses the game.
- Both the players will play optimally and A makes the first move of the game.
The task is to find the winner of the game.
Examples:
Input: arr[] = {24, 45, 45, 24}
Output: B
Explanation:
Player A replaces 24 in the first index with 1. Since, 1 is a divisor of 24. arr[] = {1, 45, 45, 24}
Player B replaces 24 in the last index with 1. Since, 1 is a divisor of 24. arr[] = {1, 45, 45, 1}
Player A replaces 45 in the second index with 1. Since, 1 is a divisor of 45. arr[] = {1, 1, 45, 24}
Player B replaces 45 in the third index with 1. Since, 1 is a divisor of 45. arr[] = {1, 1, 1, 1}
Player A cannot make a move now, since all elements are 1. Therefore, player B wins the game.
Input: arr[] = {18, 6}
Output: B
Approach: The problem can be solved based on a simple observation:
- Since 1 is a divisor of all any integers, hence, replace every array element with 1 in each operation.
- Therefore, if the array consists of a even number of elements, then player B wins.
- Otherwise, player A wins.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void winner( int arr[], int N)
{
if (N % 2 == 1) {
cout << "A" ;
}
else {
cout << "B" ;
}
}
int main()
{
int arr[] = { 24, 45, 45, 24 };
int N = sizeof (arr) / sizeof (arr[0]);
winner(arr, N);
}
|
Java
class GFG{
static void winner( int arr[], int N)
{
if (N % 2 == 1 )
{
System.out.print( "A" );
}
else
{
System.out.print( "B" );
}
}
public static void main(String[] args)
{
int arr[] = { 24 , 45 , 45 , 24 };
int N = arr.length;
winner(arr, N);
}
}
|
Python3
def winner(arr, N):
if (N % 2 = = 1 ):
print ( "A" )
else :
print ( "B" )
if __name__ = = '__main__' :
arr = [ 24 , 45 , 45 , 24 ]
N = len (arr)
winner(arr, N)
|
C#
using System;
public class GFG
{
static void winner( int []arr, int N)
{
if (N % 2 == 1)
{
Console.Write( "A" );
}
else
{
Console.Write( "B" );
}
}
public static void Main(String[] args)
{
int []arr = { 24, 45, 45, 24 };
int N = arr.Length;
winner(arr, N);
}
}
|
Javascript
<script>
function winner(arr, N) {
if (N % 2 === 1) {
document.write( "A" );
}
else {
document.write( "B" );
}
}
var arr = [24, 45, 45, 24];
var N = arr.length;
winner(arr, N);
</script>
|
Time Complexity: O(N), where N is the size of the array.
Auxiliary Space: O(1)
Last Updated :
13 May, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...