C++ program to find minimum difference between the sums of two subsets from first n natural numbers


Suppose we have a number n. Consider, first n natural numbers. We have to split them into two sets A and B such that each element belongs to exactly one set and the absolute difference between the sum of elements in A and sum of elements in B is minimum, and find that difference.

So, if the input is like n = 5, then the output will be 1, because if we make A = {1, 3, 4} and B = {2, 5}, then the sum values are 8 and 7, so difference is 1.

Steps

To solve this, we will follow these steps −

return (n * (n + 1) / 2) mod 2

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

int solve(int n) {
   return (n * (n + 1) / 2) % 2;
}
int main() {
   int n = 5;
   cout << solve(n) << endl;
}

Input

5

Output

1

Updated on: 03-Mar-2022

102 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements