- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures

- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces

# 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

Adding both we get,

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,

#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

- Related Articles
- C++ program to find minimum difference between the sums of two subsets from first n natural numbers
- First N natural can be divided into two sets with given difference and co-prime sums in C++
- Sum of square-sums of first n natural numbers
- Program to find number of magic sets from a permutation of first n natural numbers in Python
- Average of first n even natural numbers?
- Print all possible sums of consecutive numbers with sum N in C++
- Sum of first n natural numbers in C Program
- Sum of sum of first n natural numbers in C++
- Print all increasing sequences of length k from first n natural numbers in C++
- Find the average of first N natural numbers in C++
- Finding sum of first n natural numbers in PL/SQL
- Find the sum of first $n$ odd natural numbers.
- Difference between sum of the squares of and square of sum first n natural numbers.
- Sum of squares of first n natural numbers in C Program?
- Program for cube sum of first n natural numbers in C++

Advertisements