Python program to find a number in minimum steps

Python program to find a number in minimum steps

Take a number line. You are on 0th position. You start at 0 and can go either to the left or to the right. The condition is that in i%u2019th move, you take i steps. That is,
At first stage, you can take 1 step. For second stage, you can take 2 steps and soon. Here we can safetly assume the negetive numbers, if provided, as absolute values, because we start from 0 in symmetrical way.

Goal is to move in one direction as long as possible, this will give minimum moves. Starting at 0, for fist move, we land on 1. Second move, we land on 3. Third move, we land on 6. To find our target value, we add moves until we find the nth move such that 1+2+3+%u2026+n>=target.

Now when sum is greater than target, we find the difference by how much we are ahead, i.e sum %u2013 target. Let the difference be d = sum %u2013 target. Taking the i-th move backward then the new sum will become (sum %u2013 2i), i.e 1+2+3+%u2026-x+x+1%u2026+n. Now if sum-2i = target then our job is done.

Here, two cases arise:

Case 1 : Difference is even then answer is n.

Case 2 : Difference is odd, then we take one more step, i.e add n+1 to sum and now again take the difference. If difference is even then n+1 is the answer else we would have to take one more move and this will certainly make the difference even, then answer will be n+2.

Python Program:

def steps(target) : target = abs(int(target)) sum = 0 step = 0 while (sum < target or (sum - target) % 2 != 0) : step = step + 1 sum = sum + step return step if __name__ == '__main__': target = input("Enter target value: ") print(steps(target))


Enter target value: 50

Enter target value: -200