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

C++Server Side ProgrammingProgramming

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

 Live Demo

#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
raja
Published on 19-Dec-2019 12:06:38
Advertisements