Minimum number of moves to make M and N equal by repeatedly adding any divisor of number to itself except 1 and the number | Function to find the minimum number of moves to make N and M equal . ; Array to maintain the numbers included . ; pair of vertex , count ; run bfs from N ; if we reached goal ; Iterate in the range ; If i is a factor of aux ; If i is less than M - aux and is not included earlier . ; If aux / i is less than M - aux and is not included earlier . ; Not possible ; Driver Code
function countOperations ( N , M ) { let visited = new Array ( 100001 ) ; let Q = [ ] ; Q . push ( [ N , 0 ] ) ; visited [ N ] = true ; while ( Q . length > 0 ) { let aux = Q [ 0 ] [ 0 ] ; let cont = Q [ 0 ] [ 1 ] ; Q . shift ( ) ; if ( aux == M ) return cont ; for ( let i = 2 ; i * i <= aux ; i ++ ) if ( aux % i == 0 ) { if ( aux + i <= M && ! visited [ aux + i ] ) { Q . push ( [ aux + i , cont + 1 ] ) ; visited [ aux + i ] = true ; } if ( aux + parseInt ( aux / i , 10 ) <= M && ! visited [ aux + parseInt ( aux / i , 10 ) ] ) { Q . push ( [ aux + parseInt ( aux / i , 10 ) , cont + 1 ] ) ; visited [ aux + parseInt ( aux / i , 10 ) ] = true ; } } } return - 1 ; } let N = 4 , M = 24 ; document . write ( countOperations ( N , M ) ) ;