Find minimum moves to reach target on an infinite line | JavaScript program to find minimum moves to reach target if we can move i steps in i - th move . ; Handling negatives by symmetry ; Keep moving while sum is smaller or difference is odd . ; Driver code
function reachTarget ( target ) { target = Math . abs ( target ) ; let sum = 0 , step = 0 ; while ( sum < target || ( sum - target ) % 2 != 0 ) { step ++ ; sum += step ; } return step ; } let target = 5 ; document . write ( reachTarget ( target ) ) ;