Minimum Steps to obtain N from 1 by the given operations | JavaScript program to implement the above approach ; Base Case ; Recursive Call for n - 1 ; Check if n is divisible by 2 ; Check if n is divisible by 3 ; Returns a tuple ( a , b ) , where a : Minimum steps to obtain x from 1 b : Previous number ; Function that find the optimal solution ; Print the length ; Exit condition for loop = - 1 when n has reached 1 ; Return the sequence in reverse order ; Given N ; Function call
function find_sequence ( n ) { if ( n == 1 ) return [ 1 , - 1 ] ; var arr = find_sequence ( n - 1 ) ; var ans = [ arr [ 0 ] + 1 , n - 1 ] ; if ( n % 2 == 0 ) { var div_by_2 = find_sequence ( n / 2 ) ; if ( div_by_2 [ 0 ] < ans [ 0 ] ) ans = [ div_by_2 [ 0 ] + 1 , n / 2 ] ; } if ( n % 3 == 0 ) { var div_by_3 = find_sequence ( n / 3 ) ; if ( div_by_3 [ 0 ] < ans [ 0 ] ) var ans = [ div_by_3 [ 0 ] + 1 , n / 3 ] ; } return ans ; } function find_solution ( n ) { var a = find_sequence ( n ) ; document . write ( a [ 0 ] + " " ) ; var sequence = [ ] ; sequence . push ( n ) ; while ( a [ 1 ] != - 1 ) { sequence . push ( a [ 1 ] ) ; var arr = find_sequence ( a [ 1 ] ) ; a [ 1 ] = arr [ 1 ] ; } sequence . reverse ( ) ; return sequence ; } var n = 5 ; var i = find_solution ( n ) ; i . forEach ( j => { document . write ( j + " " ) ; } ) ;