- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

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

# Find the number of jumps to reach X in the number line from zero in C++

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.

## Example

#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); }

## Output

Number of jumps: 5

- Related Questions & Answers
- C Program for Minimum number of jumps to reach the end
- How to find the minimum number of jumps required to reach the end of the array using C#?
- 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++
- C++ Program to find out the number of jumps needed for a robot to reach a particular cell in a grid
- Minimum Number of Jumps Problem
- Program to find minimum jumps to reach home in Python
- Program to find out the number of non-zero submatrices in C++
- Find the Number of Solutions of n = x + n x using C++
- Check if it is possible to reach a number by making jumps of two given length in Python
- Find the minimum of maximum length of a jump required to reach the last island in exactly k jumps in Python
- Find the number of integers x in range (1,N) for which x and x+1 have same number of divisors in C++
- Program to find the number of possible position in a line in Python
- Program to find number of combinations of coins to reach target in Python
- How to TRIM x number of characters, beginning from the last in MySQL?

Advertisements