Minimum moves to reach target on a infinite line | Set 2 | CPP code to find minimum moves to reach target ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int StepstoReachTarget ( int target ) { target = abs ( target ) ; int n = ceil ( ( -1.0 + sqrt ( 1 + 8.0 * target ) ) / 2 ) ; int sum = n * ( n + 1 ) / 2 ; if ( sum == target ) return n ; int d = sum - target ; if ( ( d & 1 ) == 0 ) return n ; else return n + ( ( n & 1 ) ? 2 : 1 ) ; } int main ( ) { int target = 5 ; cout << StepstoReachTarget ( target ) ; return 0 ; }