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 ; initialise N
function divisorGame ( N , A , dp ) { if ( N == 1 N == 3 ) return false ; if ( N == 2 ) return true ; if ( dp [ N ] [ A ] != - 1 ) return dp [ N ] [ A ] ; let ans = ( A == 1 ) ? 0 : 1 ; for ( let i = 1 ; i * i <= N ; i ++ ) { if ( N % i == 0 ) { if ( A ) ans |= divisorGame ( N - i , 0 , dp ) ; else ans &= divisorGame ( N - i , 1 , dp ) ; } } return dp [ N ] [ A ] = ans ; } let N = 3 ; let dp = [ ] ; for ( let i = 0 ; i < N + 1 ; i ++ ) { let temp = [ - 1 ] for ( let j = 0 ; j < 2 ; j ++ ) { temp . push ( [ - 1 ] ) } dp . push ( temp ) } if ( divisorGame ( N , 1 , dp ) == true ) document . write ( " " ) ; else document . write ( " " ) ;