Find minimum moves to reach target on an infinite line | CPP 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
#include <iostream> NEW_LINE using namespace std ; int reachTarget ( int target ) { target = abs ( target ) ; int sum = 0 , step = 0 ; while ( sum < target || ( sum - target ) % 2 != 0 ) { step ++ ; sum += step ; } return step ; } int main ( ) { int target = 5 ; cout << reachTarget ( target ) ; return 0 ; }