Minimum moves to reach target on a infinite line | Set 2 | Function to find minimum steps to reach target ; Handling negatives by symmetry ; Keep moving while sum is smaller i . e calculating n ; Case 1 : d is even ; d is odd ; Driver Code ; Function call
function StepstoReachTarget ( target ) { target = Math . abs ( target ) ; let n = Math . ceil ( ( - 1.0 + Math . sqrt ( 1 + 8.0 * target ) ) / 2 ) ; let sum = n * ( n + 1 ) / 2 ; if ( sum == target ) return n ; let d = sum - target ; if ( ( d & 1 ) == 0 ) return n ; else return n + ( ( n & 1 ) != 0 ? 2 : 1 ) ; } let target = 5 ; document . write ( StepstoReachTarget ( target ) ) ;