- Related Questions & Answers
- C Program for Minimum number of jumps to reach the end
- Program to Find Out the Number of Moves to Reach the Finish Line in Python
- Find the minimum number of steps to reach M from N in C++
- Minimum Number of Jumps Problem
- Find the number of integers x in range (1,N) for which x and x+1 have same number of divisors in C++
- Reach a Number in C++
- Find if two people ever meet after same number of jumps in C++
- Find the minimum of maximum length of a jump required to reach the last island in exactly k jumps in Python
- Check if it is possible to reach a number by making jumps of two given length in Python
- How to find the smallest number greater than x in Python?
- Program to find the number of possible position in a line in Python
- How to TRIM x number of characters, beginning from the last in MySQL?
- Find the number of consecutive zero at the end after multiplying n numbers in Python
- Program to find number of combinations of coins to reach target in Python
- C/C++ Program to Find the Number Occurring Odd Number of Times?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have an integer X. We have to find minimum number of jumps required to reach X from 0. 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. So if X = 8, then output is 4. 0 → -1 → 1→ 4 → 8 are possible stages.

If we observe carefully, then we can say that

- If you have always jumped in the right direction, then after n jumps you will be at the point p = 1 + 2 + 3 + … + n
- If we can jump to the left also, at kth jump you will be at point p – 2k.
- If we choose carefully which jump go to the left and which go to the right, after n jumps, you can be at point between n(n+1)/2 and –(n*(n+1) / 2), with the same parity as n(n+1)/2.

#include<iostream> #include<cmath> using namespace std; inline int sumOneToN(int n) { return (n * (n + 1)) / 2; } int jumps(int n) { n = abs(n); int ans = 0; while (sumOneToN(ans) < n or (sumOneToN(ans) - n) & 1) ans++; return ans; } int main() { int n = 9; cout << "Number of jumps: " << jumps(n); }

Number of jumps: 5

Advertisements