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
< ? php function StepstoReachTarget ( $ target ) { $ target = abs ( $ target ) ; $ n = ceil ( ( -1.0 + sqrt ( 1 + 8.0 * $ target ) ) / 2 ) ; $ sum = $ n * ( $ n + 1 ) / 2 ; if ( $ sum == $ target ) return $ n ; $ d = $ sum - $ target ; if ( ( $ d & 1 ) == 0 ) return n ; else return $ n + ( ( $ n & 1 ) ? 2 : 1 ) ; } $ target = 5 ; echo StepstoReachTarget ( $ target ) ; ? >