VOOZH about

URL: https://www.geeksforgeeks.org/dsa/optimal-strategy-for-the-divisor-game-using-dynamic-programming/

⇱ Optimal Strategy for the Divisor game using Dynamic Programming - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Optimal Strategy for the Divisor game using Dynamic Programming

Last Updated : 22 Oct, 2025

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.


Examples:

Input : N = 2 
Output : Player A wins 
Explanation :
Player A chooses 1, and B has no more moves.

Input : N = 3 
Output : Player B wins 
Explanation :
Player A chooses 1, player B chooses 1, and A has no more moves.  


Approach :
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 ].

Output
Player B wins

Time Complexity: O(N*log(N))
Auxiliary Space: O(N)

Comment
Article Tags:
Article Tags: