![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
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
Example
Check whether the absolute sum is equal to m or not. And then check for GCD.
#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; }
Output
If you run the above code, then you will get the following result.
Can split
Conclusion
If you have any queries in the tutorial, mention them in the comment section.
Advertisements