Find the player who will win by choosing a number in range [1, K] with sum total N
Given two integers K and N, and also given that Alice and Bob are playing a game. In a single move, a player can choose a number in the range [1, K], and the player whose number makes the total equal to N wins the game. Print Alice if Alice wins the game, else Bob, if Alice and Bob both play the game alternatively and optimally and Alice starts the game.
Examples:
Input: K = 7, N = 8
Output: Bob
Explanation: There is no way for Alice to win the game. When Alice picks any number from 1 to 7 (inclusive both), the opponent wins the game in the next turn by making the total 8 . Suppose you choose number 5, the opponent chooses 3 and wins the game, making the total 5+3=8 .
Input: K = 7, N = 50
Output: Alice
Approach: This problem can be solved using the concept of Game Theory. Observing the winning state.The trick to catch here is that Alice can always make a cycle of (K+1) repeat, whatever Bob chooses .Assume at some point if Bob chooses a, Alice can choose [(K+1)-a] keeping the selection within the range 1 to K and thus forming a cycle of (K+1).Now, as Alice has the first chance, Alice should choose Remainder left on Dividing N by (K+1) at the Starting so that afterwards she can keep repeating the cycle of (K+1) and achieve the total as N.
Now, the observation is, if N%(K+1) is 0, it is the only case when it’s impossible to win the game for Alice.
Follow the steps given below to solve the problem.
- Check if N%(K+1) is 0, Print Bob.
- In any other case, Print Alice.
Below is the implementation of the above approach.
C++14
#include <iostream>
using namespace std;
void predictTheWinner( int K, int N)
{
if (N % (K + 1) == 0)
cout << "Bob" ;
else
cout << "Alice" ;
}
int main()
{
int K = 7, N = 50;
predictTheWinner(K, N);
return 0;
}
|
Java
import java.io.*;
class GFG {
static void predictTheWinner( int K, int N)
{
if (N % (K + 1 ) == 0 )
System.out.println( "Bob" );
else
System.out.println( "Alice" );
}
public static void main (String[] args) {
int K = 7 , N = 50 ;
predictTheWinner(K, N);
}
}
|
Python3
def predictTheWinner(K, N):
if (N % (K + 1 ) = = 0 ):
print ( "Bob" )
else :
print ( "Alice" )
if __name__ = = '__main__' :
K = 7
N = 50
predictTheWinner(K, N)
|
C#
using System;
public class GFG {
static void predictTheWinner( int K, int N)
{
if (N % (K + 1) == 0)
Console.WriteLine( "Bob" );
else
Console.WriteLine( "Alice" );
}
public static void Main ( string [] args) {
int K = 7, N = 50;
predictTheWinner(K, N);
}
}
|
Javascript
<script>
function predictTheWinner(K, N)
{
if (N % (K + 1) == 0)
document.write( "Bob" );
else
document.write( "Alice" );
}
var K = 7, N = 50;
predictTheWinner(K, N);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Last Updated :
08 Sep, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...