C++ program to find range whose sum is same as n

C++Server Side ProgrammingProgramming

Suppose we have a number n. We need to find two integers l and r, such that l < r and l + (l + 1) + ... + (r - 1) + r = n.

So, if the input is like n = 25, then the output will be l = -2 and r = 7, because (−2) + (−1) + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 = 25. Other answers are also possible.

Steps

To solve this, we will follow these steps −

return -(n-1) and n

Example

Let us see the following implementation to get better understanding −

#include<bits/stdc++.h>
using namespace std;

void solve(int n){
   cout << -(n-1) << ", " << n;
}
int main(){
   int n = 25;
   solve(n);
}

Input

25

Output

-24, 25
raja
Updated on 03-Mar-2022 07:22:36

Advertisements