Optimal Strategy for the Divisor game using Dynamic Programming | Python3 program for implementation of Optimal Strategy for the Divisor Game using Dynamic Programming ; Recursive function to find the winner ; check if N = 1 or N = 3 then player B wins ; check if N = 2 then player A wins ; check if current state already visited then return the previously obtained ans ; check if currently it is player A 's turn  then initialise the ans to 0 ; Traversing across all the divisors of N which are less than N ; check if current value of i is a divisor of N ; check if it is player A 's turn  then we need at least one true ; Else if it is player B 's turn  then we need at least one false ; Return the current ans ; Driver code ; initialise N
from math import sqrt NEW_LINE def divisorGame ( N , A , dp ) : NEW_LINE INDENT if ( N == 1 or N == 3 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( N == 2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( dp [ N ] [ A ] != - 1 ) : NEW_LINE INDENT return dp [ N ] [ A ] NEW_LINE DEDENT if ( A == 1 ) : NEW_LINE INDENT ans = 0 NEW_LINE DEDENT else : NEW_LINE INDENT ans = 1 NEW_LINE DEDENT for i in range ( 1 , int ( sqrt ( N ) ) + 1 , 1 ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT if ( A ) : NEW_LINE INDENT ans |= divisorGame ( N - i , 0 , dp ) NEW_LINE DEDENT else : NEW_LINE INDENT ans &= divisorGame ( N - i , 1 , dp ) NEW_LINE DEDENT DEDENT DEDENT dp [ N ] [ A ] = ans NEW_LINE return dp [ N ] [ A ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE dp = [ [ - 1 for i in range ( 2 ) ] for j in range ( N + 1 ) ] NEW_LINE if ( divisorGame ( N , 1 , dp ) == True ) : NEW_LINE INDENT print ( " Player ▁ A ▁ wins " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Player ▁ B ▁ wins " ) NEW_LINE DEDENT DEDENT