Minimum number of moves to make M and N equal by repeatedly adding any divisor of number to itself except 1 and the number | C # program for the above approach . ; 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
using System ; using System . Collections ; class GFG { static int countOperations ( int N , int M ) { bool [ ] visited = new bool [ 100001 ] ; Queue Q = new Queue ( ) ; Q . Enqueue ( new Tuple < int , int > ( N , 0 ) ) ; visited [ N ] = true ; while ( Q . Count > 0 ) { int aux = ( ( Tuple < int , int > ) ( Q . Peek ( ) ) ) . Item1 ; int cont = ( ( Tuple < int , int > ) ( Q . Peek ( ) ) ) . Item2 ; Q . Dequeue ( ) ; if ( aux == M ) return cont ; for ( int i = 2 ; i * i <= aux ; i ++ ) if ( aux % i == 0 ) { if ( aux + i <= M && ! visited [ aux + i ] ) { Q . Enqueue ( new Tuple < int , int > ( aux + i , cont + 1 ) ) ; visited [ aux + i ] = true ; } if ( aux + aux / i <= M && ! visited [ aux + aux / i ] ) { Q . Enqueue ( new Tuple < int , int > ( aux + aux / i , cont + 1 ) ) ; visited [ aux + aux / i ] = true ; } } } return - 1 ; } static void Main ( ) { int N = 4 , M = 24 ; Console . WriteLine ( countOperations ( N , M ) ) ; } }