Minimum number of moves to make M and N equal by repeatedly adding any divisor of number to itself except 1 and the number | Java program for 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
import java . util . * ; class GFG { static class pair < T , V > { T first ; V second ; } static pair < Integer , Integer > make_pair ( int f , int s ) { pair < Integer , Integer > p = new pair < > ( ) ; p . first = f ; p . second = s ; return p ; } static int countOperations ( int N , int M ) { boolean [ ] visited = new boolean [ 100001 ] ; Arrays . fill ( visited , false ) ; Queue < pair < Integer , Integer > > Q = new LinkedList < > ( ) ; Q . add ( make_pair ( N , 0 ) ) ; visited [ N ] = true ; while ( ! Q . isEmpty ( ) ) { int aux = Q . peek ( ) . first ; int cont = Q . peek ( ) . second ; Q . remove ( ) ; 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 . add ( make_pair ( aux + i , cont + 1 ) ) ; visited [ aux + i ] = true ; } if ( aux + aux / i <= M && ! visited [ aux + aux / i ] ) { Q . add ( make_pair ( aux + aux / i , cont + 1 ) ) ; visited [ aux + aux / i ] = true ; } } } return - 1 ; } public static void main ( String [ ] args ) { int N = 4 , M = 24 ; System . out . println ( countOperations ( N , M ) ) ; } }