A and B are playing a game. At the beginning there are n coins. Given two more numbers x and y. In each move a player can pick x or y or l coins. A always starts the game. The player who picks the last coin wins the game. For a given value of n, find whether A will win the game or not if both are playing optimally.
Input : n = 5, x = 3, y = 4 Output : A There are 5 coins, every player can pick 1 or 3 or 4 coins on his/her turn. A can win by picking 3 coins in first chance. Now 2 coins will be left so B will pick one coin and now A can win by picking the last coin. Input : 2 3 4 Output : B
Let us take few example values of n for x = 3, y = 4.
n = 0 A can not pick any coin so he losses
n = 1 A can pick 1 coin and win the game
n = 2 A can pick only 1 coin. Now B will pick 1 coin and win the game
n = 3 4 A will win the game by picking 3 or 4 coins
n = 5, 6 A will choose 3 or 4 coins. Now B will have to choose from 2 coins so A will win.
We can observe that A wins game for n coins only when it loses for coins n-1, n-x and n-y.
This article is contributed by nuclode. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
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.
- Predict the winner of the game | Sprague-Grundy
- Count pairs (A, B) such that A has X and B has Y number of set bits and A+B = C
- Find minimum sum such that one of every three consecutive elements is taken
- Coin Change | DP-7
- Coin Change | BFS Approach
- Understanding The Coin Change Problem With Dynamic Programming
- Maximum sum in an array such that every element has exactly one adjacent element to it
- Minimum score possible for a player by selecting one or two consecutive array elements from given binary array
- Maximum games played by winner
- Optimal Strategy for a Game | DP-31
- Count number of ways to reach a given score in a game
- Optimal Strategy for a Game | Set 2
- Optimal Strategy for a Game | Set 3
- Optimal strategy for a Game with modifications
- Optimal Strategy for the Divisor game using Dynamic Programming
- Maximum subsequence sum such that no three are consecutive
- LCS (Longest Common Subsequence) of three strings
- WildCard pattern matching having three symbols ( * , + , ? )
- Check if array sum can be made K by three operations on it
- Ways to form a group from three groups with given constraints
Improved By : vt_m