- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

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; }

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

- Related Questions & Answers
- Sum of square-sums of first n natural numbers
- First N natural can be divided into two sets with given difference and co-prime sums in C++
- Program to find number of magic sets from a permutation of first n natural numbers in Python
- Sum of first n natural numbers in C Program
- Average of first n even natural numbers?
- Sum of sum of first n natural numbers in C++
- Sum of squares of first n natural numbers in C Program?
- C Program for cube sum of first n natural numbers?
- C++ Program for cube sum of first n natural numbers?
- Print all possible sums of consecutive numbers with sum N in C++
- C++ Program for Sum of squares of first n natural numbers?
- Print all increasing sequences of length k from first n natural numbers in C++
- Program to find sum of first n natural numbers in C++
- Program for cube sum of first n natural numbers in C++
- Find m-th summation of first n natural numbers in C++

Advertisements