C++ Program to Find Range Whose Sum is Same as N



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 −

Open Compiler
#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
Updated on: 2022-03-03T07:22:36+05:30

173 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements