Given N and D, find if it is possible to make two sets from first N natural numbers such that the difference between the sum of 2 sets(individually) is D.
Input : 5 7 Output : yes Explanation: Keeping 1 and 3 in one set, and 2, 4 and 5 are in other set. Sum of set 1 = 4 Sum of set 2 = 11 So, the difference D = 7 Which is the required difference Input : 4 5 Output : no
Let s1 and s2 be the two sets.
Here we know that
sum(s1) + sum(s2) = N*(N+1)/2 and
sum(s1) – sum(s2) = D
Adding above 2 equations, we get
2*sum(s1) = N*(N+1)/2 + D
If sum(S1) and sum(S2) are integers, then only we can split the first N natural numbers into two sets. For that N*(N+1)/2 + D must be an even number.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Split first N natural numbers into two sets with minimum absolute difference of their sums
- Split squares of first N natural numbers into two sets with minimum absolute difference of their sums
- First N natural can be divided into two sets with given difference and co-prime sums
- Split N natural numbers into two sets having GCD of their sums greater than 1
- Sum of square-sums of first n natural numbers
- Find the permutation of first N natural numbers such that sum of i % Pi is maximum possible
- Print all possible K-length subsequences of first N natural numbers with sum N
- Difference between Sum of Cubes and Sum of First N Natural Numbers
- Maximum and minimum sums from two numbers with digit replacements
- Partition into two subarrays of lengths k and (N - k) such that the difference of sums is maximum
- Partition a set into two non-empty subsets such that the difference of subset sums is maximum
- Print all distinct Coprime sets possible from 1 to N
- Replace all elements by difference of sums of positive and negative numbers after that element
- First element of every K sets having consecutive elements with exactly K prime factors less than N
- Sum of the sums of all possible subsets
- Print squares of first n natural numbers without using *, / and -
- Print all increasing sequences of length k from first n natural numbers
- Sum of cubes of first n odd natural numbers
- Find m-th summation of first n natural numbers.
- Program to find sum of first n natural numbers
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.