Minimum step to reach one | Structure represent one node in queue ; Method returns minimum step to reach one ; Set is used to visit numbers so that they won 't be pushed  in queue again ; Loop until we reach to 1 ; If current data value is 1 , return its steps from N ; Check curr - 1 , only if it not visited yet ; Loop from 2 to Math . sqrt ( value ) for its divisors ; Check divisor , only if it is not visited yet if i is divisor of val , then val / i will be its bigger divisor ; Driver code
class data { constructor ( val , steps ) { this . val = val ; this . steps = steps ; } } function minStepToReachOne ( N ) { let q = [ ] ; q . push ( new data ( N , 0 ) ) ; let st = new Set ( ) ; while ( q . length != 0 ) { let t = q . shift ( ) ; if ( t . val == 1 ) return t . steps ; if ( ! st . has ( t . val - 1 ) ) { q . push ( new data ( t . val - 1 , t . steps + 1 ) ) ; st . add ( t . val - 1 ) ; } for ( let i = 2 ; i * i <= t . val ; i ++ ) { if ( t . val % i == 0 && ! st . has ( t . val / i ) ) { q . push ( new data ( t . val / i , t . steps + 1 ) ) ; st . add ( t . val / i ) ; } } } return - 1 ; } let N = 17 ; document . write ( minStepToReachOne ( N ) + " " ) ;