First N natural can be divided into two sets with given difference and co-prime sums in C++

In this tutorial, we have to find whether the natural numbers from 1 to n is divided into two halves or not. It has to satisfy the following conditions.

  • The absolute difference between the two series sum should be m.

  • And the GCD of two sums should be 1 i.e.., co-primes.

The sum of first n natural numbers is (n*(n+1))/2. We can find the sumOne and sumTwo as we have total sum and difference m. See the below equations.

sumOne + sumTwo = (n*(n+1))/2
sumOne - sumTwo = m


Check whether the absolute sum is equal to m or not. And then check for GCD.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
bool canSplitIntoTwoHalves(int n, int m) {
   int total_sum = (n * (n + 1)) / 2;
   int sumOne = (total_sum + m) / 2;
   int sumTwo = total_sum - sumOne;
   if (total_sum < m) {
      return false;
   if (sumOne + sumTwo == total_sum &&sumOne - sumTwo == m) {
      return (__gcd(sumOne, sumTwo) == 1);
   return false;
int main() {
   int n = 10, m = 17;
   if (canSplitIntoTwoHalves(n, m)) {
      cout << "Can split";
   else {
      cout << "Can't split";
   return 0;


If you run the above code, then you will get the following result.

Can split


If you have any queries in the tutorial, mention them in the comment section.