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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: K = 7, N = 8
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
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.
Time Complexity: O(1)
Auxiliary Space: O(1)