- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Articles
- Possible two sets from first N natural numbers difference of sums as D in C++
- Sum of square-sums of first n natural numbers
- Program to find sum of first n natural numbers in C++
- 8085 program to find the sum of first n natural numbers
- Sum of all subsets of a set formed by first n natural numbers
- Sum of first n natural numbers in C Program
- Find the average of first N natural numbers in C++
- Find the good permutation of first N natural numbers C++
- C Program for the cube sum of first n natural numbers?
- PHP program to find the sum of cubes of the first n natural numbers
- C Program for cube sum of first n natural numbers?
- C++ Program for cube sum of first n natural numbers?
- First N natural can be divided into two sets with given difference and co-prime sums in C++
- C++ Program for Sum of squares of first n natural numbers?
- Sum of squares of first n natural numbers in C Program?

Advertisements