Minimum moves to reach target on a infinite line | Set 2 | Python 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
import math NEW_LINE def StepstoReachTarget ( target ) : NEW_LINE INDENT target = abs ( target ) NEW_LINE n = math . ceil ( ( - 1.0 + math . sqrt ( 1 + 8.0 * target ) ) / 2 ) NEW_LINE sum = n * ( n + 1 ) / 2 NEW_LINE if ( sum == target ) : NEW_LINE INDENT return n NEW_LINE DEDENT d = sum - target NEW_LINE if ( ( int ( d ) & 1 ) == 0 ) : NEW_LINE INDENT return n NEW_LINE DEDENT else : NEW_LINE INDENT if ( int ( d ) & 1 ) : NEW_LINE INDENT return n + 2 NEW_LINE DEDENT return n + 1 NEW_LINE DEDENT DEDENT target = 5 NEW_LINE print ( StepstoReachTarget ( target ) ) NEW_LINE