Given two integers N and K, where N represents the total number of cards present when game begins and K denotes the maximum number of cards that can be removed in a single turn. Two players A and B get turns to remove at most K cards, one by one starting from player A. The player to remove the last card is the winner. The task is to check if A can win the game or not. If found to be true, print ‘A’ as the answer. Otherwise, print ‘B’.
Examples:
Input: N = 14, K = 10
Output: Yes
Explanation:
Turn 1: A removes 3 cards in his first turn.
Turn 2: B removes any number of cards from the range [1 – 10]
Finally, A can remove all remaining cards and wins the game, as the number of remaining cards after turn 2 will be ≤ 10
Input: N = 11, K=10
Output: No
Approach: The idea here is to observe that whenever the value of N % (K + 1) = 0, then A will never be able to win the game. Otherwise A always win the game.
Proof:
- If N ≤ K: The person who has the first turn will win the game, i.e. A.
- If N = K + 1: A can remove any number of cards in the range [1, K]. So, the total number of cards left after the first turn are also in the range [1, K]. Now B gets the turn and number of cards left are in the range [1, K]. So, B will win the game.
- If K + 2 ≤ N ≤ 2K + 1: A removes N – (K + 1) cards in his first turn. B can remove any number of cards in the range [1, K] in the next turn. Therefore, the total number of cards left now are in the range [1, K].Now, since the remaining cards left are in the range [1, K], so A can remove all the cards and win the game.
Therefore the idea is to check if N % (K + 1) is equal to 0 or not. If found to be true, print B as the winner. Otherwise, print A as the winner.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void checkWinner( int N, int K)
{
if (N % (K + 1)) {
cout << "A" ;
}
else {
cout << "B" ;
}
}
int main()
{
int N = 50;
int K = 10;
checkWinner(N, K);
}
|
Java
import java.util.*;
class GFG{
static void checkWinner( int N, int K)
{
if (N % (K + 1 ) > 0 )
{
System.out.print( "A" );
}
else
{
System.out.print( "B" );
}
}
public static void main(String[] args)
{
int N = 50 ;
int K = 10 ;
checkWinner(N, K);
}
}
|
Python3
def checkWinner(N, K):
if (N % (K + 1 )):
print ( "A" )
else :
print ( "B" )
N = 50
K = 10
checkWinner(N, K)
|
C#
using System;
class GFG{
static void checkWinner( int N, int K)
{
if (N % (K + 1) > 0)
{
Console.Write( "A" );
}
else
{
Console.Write( "B" );
}
}
public static void Main(String[] args)
{
int N = 50;
int K = 10;
checkWinner(N, K);
}
}
|
Javascript
<script>
function checkWinner(N, K)
{
if (N % (K + 1)) {
document.write( "A" );
}
else {
document.write( "B" );
}
}
let N = 50;
let K = 10;
checkWinner(N, K);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)