Given an integer N and two players, A and B are playing a game. On each player’s turn, that player makes a move by subtracting a divisor of current N (which is less than N) from current N, thus forming a new N for the next turn. The player who does not have any divisor left to subtract loses the game. The task is to tell which player wins the game if player A takes the first turn, assuming both players play optimally.
Input : N = 2
Output : Player A wins
Player A chooses 1, and B has no more moves.
Input : N = 3
Output : Player B wins
Player A chooses 1, player B chooses 1, and A has no more moves.
This problem mentioned above can be solved using Dynamic Programming.
We will take a DP having 2 states i.e.
N -> current number left
A -> boolean value to decide if it’s player A’s turn or not
- At each state, we will try to find all the divisors of N and will try to find the next state where the current player is winning. For player A, we will try to find the next state where the return value is true while for player B, we will try to find the next state where the return value is false (as false represents the loss of player A).
- The base cases will be for N=1 where always the player A will lose and N=2 where always the player B will lose.
- To find the answer, we just need to find the value of DP[ N ][ 1 ].
Below is the implementation of the above approach:
Player B wins
- Optimal Strategy for a Game | Set 3
- Optimal Strategy for a Game | DP-31
- Optimal Strategy for a Game | Set 2
- Optimal strategy for a Game with modifications
- Optimal Strategy for a Game | Special Gold Coin
- Optimal Substructure Property in Dynamic Programming | DP-2
- Game Theory (Normal-form game) | Set 3 (Game with Mixed Strategy)
- Game Theory (Normal-form Game) | Set 5 (Dominance Property-Mixed Strategy)
- Game Theory (Normal-form Game) | Set 4 (Dominance Property-Pure Strategy)
- Largest odd divisor Game to check which player wins
- Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)
- Dynamic Programming on Trees | Set-1
- Dynamic Programming on Trees | Set 2
- Bitmasking and Dynamic Programming | Set-2 (TSP)
- Game Theory (Normal-form Game) | Set 7 (Graphical Method [M X 2] Game)
- Game Theory (Normal-form Game) | Set 6 (Graphical Method [2 X N] Game)
- Dynamic Programming | Building Bridges
- Greedy approach vs Dynamic programming
- Top 20 Dynamic Programming Interview Questions
- Convert N to M with given operations using dynamic programming
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.