# Possible two sets from first N natural numbers difference of sums as D in C++

In this problem, we are given two integer N and D. Our task is to check whether it is possible to have to sets from the set of first N natural numbers that have a difference of D.

Let’s take an example to understand the problem,

Input − N=5 D =3

Output − Yes

Explanation

Out of 1, 2, 3, 4, 5.
We can have two sets set1= {1, 2, 3} and set2 = {4, 5}, this will give difference 3.
{4+5} - {1+2+3} = 9- 6 = 3

For solving this problem, we will have some mathematical calculations.

We know, the sum of all number is the sum of elements of two set is,

Sum of n natural number formula,

sum(s1) + sum(s2) = (n*(n+1))/2. Given in the problem, sum(s1) - sum(s2) = D

2*sum(s1) = ((n*(n+1))/2) + D

If this condition is true, then only a solution is possible.

## Example

Program to show the implementation of our solution,

Live Demo

#include <iostream>
using namespace std;
bool isSetPossible(int N, int D) {
int set = (N * (N + 1)) / 2 + D;
return (set % 2 == 0);
}
int main() {
int N = 10;
int D = 7;
cout<<"Creating two set from first "<<N<<" natural number with difference "<<D<<" is ";
isSetPossible(N, D)?cout<<"possible":cout<<"not possible";
return 0;
}

## Output

Creating two set from first 10 natural number with difference 7 is possible