Find the number of jumps to reach X in the number line from zero | C ++ program to find the number of jumps to reach X in the number line from zero ; Utility function to calculate sum of numbers from 1 to x ; Function to find the number of jumps to reach X in the number line from zero ; First make number positive Answer will be same either it is Positive or negative ; To store required answer ; Continue till number is lesser or not in same parity ; Return the required answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getsum ( int x ) { return ( x * ( x + 1 ) ) / 2 ; } int countJumps ( int n ) { n = abs ( n ) ; int ans = 0 ; while ( getsum ( ans ) < n or ( getsum ( ans ) - n ) & 1 ) ans ++ ; return ans ; } int main ( ) { int n = 9 ; cout << countJumps ( n ) ; return 0 ; }