Open In App

Split first N natural numbers into two sets with minimum absolute difference of their sums

Last Updated : 28 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an integer N, split the first N natural numbers into two sets such that the absolute difference between their sum is minimum. The task is to print the minimum absolute difference that can be obtained.

Examples:

Input: N = 5
Output: 1
Explanation:
Split the first N (= 5) natural numbers into sets {1, 2, 5} (sum = 8) and {3, 4} (sum = 7).
Therefore, the required output is 1.

Input: N = 6
Output: 1

Naive Approach: This problem can be solved using the Greedy technique. Follow the steps below to solve the problem:

  • Initialize two variables, say sumSet1 and sumSet2 to store the sum of the elements from the two sets.
  • Traverse first N natural numbers from N to 1. For every number, check if the current sum of elements in set1 is less than or equal to the sum of elements in set2. If found to be true, add the currently traversed number into set1 and update sumSet1.
  • Otherwise, add the value of the current natural number to set2 and update sumSet2.
  • Finally, print abs(sumSet1 – sumSet2) as the required answer.

Below is the implementation of the above approach:

C++14




// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to split the first N
// natural numbers into two sets
// having minimum absolute
// difference of their sums
int minAbsDiff(int N)
{
    // Stores the sum of
    // elements of set1
    int sumSet1 = 0;
 
    // Stores the sum of
    // elements of set2
    int sumSet2 = 0;
 
    // Traverse first N
    // natural numbers
    for (int i = N; i > 0; i--) {
 
        // Check if sum of elements of
        // set1 is less than or equal
        // to sum of elements of set2
        if (sumSet1 <= sumSet2) {
            sumSet1 += i;
        }
        else {
            sumSet2 += i;
        }
    }
    return abs(sumSet1 - sumSet2);
}
 
// Driver Code
int main()
{
    int N = 6;
    cout << minAbsDiff(N);
}


Java




// Java program to implement
// the above approach
import java.io.*;
  
class GFG{
     
// Function to split the first N
// natural numbers into two sets
// having minimum absolute
// difference of their sums
static int minAbsDiff(int N)
{
     
    // Stores the sum of
    // elements of set1
    int sumSet1 = 0;
  
    // Stores the sum of
    // elements of set2
    int sumSet2 = 0;
  
    // Traverse first N
    // natural numbers
    for(int i = N; i > 0; i--)
    {
         
        // Check if sum of elements of
        // set1 is less than or equal
        // to sum of elements of set2
        if (sumSet1 <= sumSet2)
        {
            sumSet1 += i;
        }
        else
        {
            sumSet2 += i;
        }
    }
    return Math.abs(sumSet1 - sumSet2);
}
 
// Driver code
public static void main (String[] args)
{
    int N = 6;
     
    System.out.println(minAbsDiff(N));
}
}
 
// This code is contributed by offbeat


Python3




# Python3 program to implement
# the above approach
 
# Function to split the first N
# natural numbers into two sets
# having minimum absolute
# difference of their sums
def minAbsDiff(N):
     
    # Stores the sum of
    # elements of set1
    sumSet1 = 0
 
    # Stores the sum of
    # elements of set2
    sumSet2 = 0
 
    # Traverse first N
    # natural numbers
    for i in reversed(range(N + 1)):
         
        # Check if sum of elements of
        # set1 is less than or equal
        # to sum of elements of set2
        if sumSet1 <= sumSet2:
           sumSet1 = sumSet1 + i
        else:
           sumSet2 = sumSet2 + i
       
    return abs(sumSet1 - sumSet2)
 
# Driver Code
N = 6
 
print(minAbsDiff(N))
 
# This code is contributed by sallagondaavinashreddy7


C#




// C# program to implement
// the above approach
using System;
 
class GFG{
 
// Function to split the first N
// natural numbers into two sets
// having minimum absolute
// difference of their sums
static int minAbsDiff(int N)
{
     
    // Stores the sum of
    // elements of set1
    int sumSet1 = 0;
  
    // Stores the sum of
    // elements of set2
    int sumSet2 = 0;
  
    // Traverse first N
    // natural numbers
    for(int i = N; i > 0; i--)
    {
         
        // Check if sum of elements of
        // set1 is less than or equal
        // to sum of elements of set2
        if (sumSet1 <= sumSet2)
        {
            sumSet1 += i;
        }
        else
        {
            sumSet2 += i;
        }
    }
    return Math.Abs(sumSet1 - sumSet2);
}
 
// Driver code
static void Main()
{
    int N = 6;
     
    Console.Write(minAbsDiff(N));
}
}
 
// This code is contributed by divyeshrabadiya07


Javascript




<script>
 
// Javascript program to implement
// the above approach
 
// Function to split the first N
// natural numbers into two sets
// having minimum absolute
// difference of their sums
function minAbsDiff(N)
{
     
    // Stores the sum of
    // elements of set1
    var sumSet1 = 0;
 
    // Stores the sum of
    // elements of set2
    var sumSet2 = 0;
 
    // Traverse first N
    // natural numbers
    for(i = N; i > 0; i--)
    {
         
        // Check if sum of elements of
        // set1 is less than or equal
        // to sum of elements of set2
        if (sumSet1 <= sumSet2)
        {
            sumSet1 += i;
        }
        else
        {
            sumSet2 += i;
        }
    }
    return Math.abs(sumSet1 - sumSet2);
}
 
// Driver code
var N = 6;
 
document.write(minAbsDiff(N));
 
// This code is contributed by umadevi9616
 
</script>


Output

1






Time Complexity: O(N)
Auxiliary Space: O(1)

Efficient Approach: To optimize the above approach the idea is based on the following observations:

Splitting any 4 consecutive integers into 2 sets gives the minimum absolute difference of their sum equal to 0.

Mathematical proof:
Considering 4 consecutive integers {a1, a2, a3, a4}
a4 = a3 + 1
a1=a2  – 1
=> a4 + a1 = a3 + 1 + a2  – 1
=> a4 + a1 = a2 + a3

Follow the steps below to solve the problem:

  • If N % 4 == 0 or N % 4 == 3, then print 0.
  • Otherwise, print 1.

Below is the implementation of the above approach:

C++




// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to split the first N
// natural numbers into two sets
// having minimum absolute
// difference of their sums
int minAbsDiff(int N)
{
    if (N % 4 == 0 || N % 4 == 3) {
        return 0;
    }
    return 1;
}
 
// Driver Code
int main()
{
    int N = 6;
    cout << minAbsDiff(N);
}


Java




// Java program to implement
// the above approach
import java.io.*;
import java.util.*;
 
class GFG{
     
// Function to split the first N
// natural numbers into two sets
// having minimum absolute
// difference of their sums
static int minAbsDiff(int N)
{
    if (N % 4 == 0 || N % 4 == 3)
    {
        return 0;
    }
    return 1;
}
 
// Driver Code
public static void main (String[] args)
{
    int N = 6;
     
    System.out.println(minAbsDiff(N));
}
}
 
// This code is contributed by sallagondaavinashreddy7


Python3




# Python3 program to implement
# the above approach
 
# Function to split the first N
# natural numbers into two sets
# having minimum absolute
# difference of their sums
def minAbsDiff(N):
     
    if (N % 4 == 0 or N % 4 == 3):
        return 0
         
    return 1
 
# Driver Code
N = 6
 
print(minAbsDiff(N))
 
# This code is contributed by sallagondaavinashreddy7


C#




// C# program to implement
// the above approach
using System;
class GFG{
     
// Function to split the first N
// natural numbers into two sets
// having minimum absolute
// difference of their sums
static int minAbsDiff(int N)
{
  if (N % 4 == 0 ||
      N % 4 == 3)
  {
    return 0;
  }
  return 1;
}
 
// Driver Code
public static void Main(String[] args)
{
  int N = 6;
  Console.WriteLine(minAbsDiff(N));
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
// javascript program to implement
// the above approach   
// Function to split the first N
    // natural numbers into two sets
    // having minimum absolute
    // difference of their sums
    function minAbsDiff(N) {
        if (N % 4 == 0 || N % 4 == 3) {
            return 0;
        }
        return 1;
    }
 
    // Driver Code
     
        var N = 6;
 
        document.write(minAbsDiff(N));
 
// This code contributed by gauravrajput1
</script>


Output

1






Time Complexity: O(1)
Auxiliary Space: O(1)

Approach 3:

Approach:

  • Create a set of the first N natural numbers.
  • Initialize a variable min_diff to infinity to keep track of the minimum absolute difference found so far.
  • Loop through all possible subsets of the set of numbers. Since we are only interested in splitting the set into two subsets, we can loop through all
  • binary numbers from 1 to 2^(N-1), where each bit in the binary number represents whether the corresponding number in the set belongs to subset1 or subset2.
  • For each subset, calculate the absolute difference between the sum of the numbers in subset1 and subset2.
  • If the absolute difference is less than the current minimum difference, update the minimum difference.
  • After all subsets have been checked, return the minimum absolute difference found.

C++




#include <climits>
#include <cmath>
#include <iostream>
#include <numeric>
#include <set>
 
// Function to calculate the minimum absolute difference of
// two subsets
int minAbsoluteDiff(int N)
{
    // Create a set containing numbers from 1 to N
    std::set<int> numSet;
    for (int i = 1; i <= N; i++) {
        numSet.insert(i);
    }
 
    int minDiff = INT_MAX;
 
    // Generate all possible subsets using bitwise
    // operations
    for (int i = 1; i < std::pow(2, N - 1); i++) {
        std::set<int> subset1, subset2;
 
        // Divide the numbers into two subsets based on the
        // binary representation of i
        for (int j = 0; j < N; j++) {
            if (i & (1 << j)) {
                subset1.insert(j + 1);
            }
            else {
                subset2.insert(j + 1);
            }
        }
 
        // Calculate the absolute difference between the
        // sums of the two subsets
        int sum1 = std::accumulate(subset1.begin(),
                                   subset1.end(), 0);
        int sum2 = std::accumulate(subset2.begin(),
                                   subset2.end(), 0);
        int diff = std::abs(sum1 - sum2);
 
        // Update the minimum difference if a smaller one is
        // found
        if (diff < minDiff) {
            minDiff = diff;
        }
    }
 
    return minDiff;
}
 
int main()
{
    // Example usage and output
    std::cout << minAbsoluteDiff(5)
              << std::endl; // Output: 1
    std::cout << minAbsoluteDiff(6)
              << std::endl; // Output: 1
 
    return 0;
}


Java




import java.util.HashSet;
import java.util.Set;
 
public class MinAbsoluteDiff {
 
    // Function to find the minimum absolute difference between two subsets of {1, 2, ..., N}
    public static int minAbsoluteDiff(int N) {
        Set<Integer> numSet = new HashSet<>();
        for (int i = 1; i <= N; i++) {
            numSet.add(i);
        }
 
        int minDiff = Integer.MAX_VALUE;
 
        // Iterate through all possible non-empty subsets of {1, 2, ..., N-1}
        for (int i = 1; i < (1 << (N - 1)); i++) {
            Set<Integer> subset1 = new HashSet<>();
            Set<Integer> subset2 = new HashSet<>();
 
            // Partition the numbers into two subsets based on the binary representation of 'i'
            for (int j = 0; j < N; j++) {
                if ((i & (1 << j)) != 0) {
                    subset1.add(j + 1);
                } else {
                    subset2.add(j + 1);
                }
            }
 
            // Calculate the absolute difference between the sums of the two subsets
            int diff = Math.abs(sum(subset1) - sum(subset2));
 
            // Update the minimum difference if 'diff' is smaller
            if (diff < minDiff) {
                minDiff = diff;
            }
        }
 
        return minDiff;
    }
 
    // Function to calculate the sum of elements in a set
    public static int sum(Set<Integer> set) {
        int sum = 0;
        for (int num : set) {
            sum += num;
        }
        return sum;
    }
 
    public static void main(String[] args) {
        // Example usage
        System.out.println(minAbsoluteDiff(5)); // Output: 1
        System.out.println(minAbsoluteDiff(6)); // Output: 1
    }
}


Python3




def min_absolute_diff(N):
    num_set = set(range(1,N+1))
    min_diff = float('inf')
    for i in range(1, 2**(N-1)):
        subset1 = set()
        subset2 = set()
        for j in range(N):
            if i & (1<<j):
                subset1.add(j+1)
            else:
                subset2.add(j+1)
        diff = abs(sum(subset1)-sum(subset2))
        if diff < min_diff:
            min_diff = diff
    return min_diff
 
# Example usage
print(min_absolute_diff(5)) # Output: 1
print(min_absolute_diff(6)) # Output: 1


C#




using System;
using System.Collections.Generic;
 
class Program {
    // Function to calculate the minimum absolute difference
    // of two subsets
    static int MinAbsoluteDiff(int N)
    {
        // Create a set containing numbers from 1 to N
        HashSet<int> numSet = new HashSet<int>();
        for (int i = 1; i <= N; i++) {
            numSet.Add(i);
        }
 
        int minDiff = int.MaxValue;
 
        // Generate all possible subsets using bitwise
        // operations
        for (int i = 1; i < Math.Pow(2, N - 1); i++) {
            HashSet<int> subset1 = new HashSet<int>();
            HashSet<int> subset2 = new HashSet<int>();
 
            // Divide the numbers into two subsets based on
            // the binary representation of i
            for (int j = 0; j < N; j++) {
                if ((i & (1 << j)) != 0) {
                    subset1.Add(j + 1);
                }
                else {
                    subset2.Add(j + 1);
                }
            }
 
            // Calculate the absolute difference between the
            // sums of the two subsets
            int sum1 = 0;
            foreach(int num in subset1) { sum1 += num; }
 
            int sum2 = 0;
            foreach(int num in subset2) { sum2 += num; }
 
            int diff = Math.Abs(sum1 - sum2);
 
            // Update the minimum difference if a smaller
            // one is found
            if (diff < minDiff) {
                minDiff = diff;
            }
        }
 
        return minDiff;
    }
 
    static void Main()
    {
        // Example usage and output
        Console.WriteLine(MinAbsoluteDiff(5)); // Output: 1
        Console.WriteLine(MinAbsoluteDiff(6)); // Output: 1
    }
}


Javascript




<script>
//JavaScript program for the above approach
 
// Function to calculate the minimum absolute difference of two subsets
function minAbsoluteDiff(N) {
    // Create a set containing numbers from 1 to N
    let numSet = new Set();
    for (let i = 1; i <= N; i++) {
        numSet.add(i);
    }
 
    let minDiff = Infinity;
 
    // Generate all possible subsets using bitwise operations
    for (let i = 1; i < Math.pow(2, N - 1); i++) {
        let subset1 = new Set();
        let subset2 = new Set();
 
        // Divide the numbers into two subsets based on the binary representation of i
        for (let j = 0; j < N; j++) {
            if (i & (1 << j)) {
                subset1.add(j + 1);
            } else {
                subset2.add(j + 1);
            }
        }
 
        // Calculate the absolute difference between the sums of the two subsets
        let sum1 = [...subset1].reduce((acc, val) => acc + val, 0);
        let sum2 = [...subset2].reduce((acc, val) => acc + val, 0);
        let diff = Math.abs(sum1 - sum2);
 
        // Update the minimum difference if a smaller one is found
        if (diff < minDiff) {
            minDiff = diff;
        }
    }
 
    return minDiff;
}
 
// Example usage and output
document.write(minAbsoluteDiff(5)); // Output: 1
document.write("<br>");
document.write(minAbsoluteDiff(6)); // Output: 1
 
// This code is contributed by Susobhan Akhuli
</script>


Output

1
1






Time complexity: O(2^N)
Space complexity: O(2^N)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads