Given an integers X. The task is to find the number of jumps to reach a point X in the number line starting from zero.
Note: The first jump made can be of length one unit and each successive jump will be exactly one unit longer than the previous jump in length. It is allowed to go either left or right in each jump.
Input : X = 8 Output : 4 Explanation : 0 -> -1 -> 1 -> 4-> 8 are possible stages. Input : X = 9 Output : 5 Explanation : 0 -> -1 -> -3 -> 0 -> 4-> 9 are possible stages
Approach : On observing carefully, it can be said easily that:
- If you have always jumped in the right direction then after n jumps you will be at the point p = 1 + 2 + 3 + 4 + … + n.
- If instead of jumping right, you jumped left in the kth jump, you would be at point p – 2k.
- Moreover, by carefully choosing which jumps to go left and which to go right, after n jumps, you can be at any point between n * (n + 1) / 2 and – (n * (n + 1) / 2) with the same parity as n * (n + 1) / 2.
Keeping the above points in mind, what you must do is simulate the jumping process, always jumping to the right, and if at some point, you’ve reached a point that has the same parity as X and is at or beyond X, you’ll have your answer.
Below is the implementation of the above approach:
- Minimum number of jumps to reach end
- Check if it is possible to reach a number by making jumps of two given length
- Find the minimum of maximum length of a jump required to reach the last island in exactly k jumps
- Find if two people ever meet after same number of jumps
- Find minimum moves to reach target on an infinite line
- Find the minimum number of steps to reach M from N
- Find the number of ways to reach Kth step in stair case
- Reach the numbers by making jumps of two given lengths
- Number of jumps for a thief to cross walls
- Minimum moves to reach target on a infinite line | Set 2
- Number of steps required to reach point (x,y) from (0,0) using zig-zag way
- Minimum number of moves to reach N starting from (1, 1)
- Minimize the number of steps required to reach the end of the array | Set 2
- Count number of ways to reach a given score in a Matrix
- Number of ways to reach (X, Y) in a matrix starting from the origin
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.