The Wayback Machine - https://web.archive.org/web/20211213163124/https://www.geeksforgeeks.org/split-given-number-into-two-distinct-numbers-having-gcd-1/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Split given number into two distinct numbers having GCD 1

  • Last Updated : 13 Dec, 2021

Given an Integer as N, the task is to convert N into two numbers a and b, such that a < b and GCD(a, b) is equal to 1.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: N = 12
Output: 5 7



Input: N = 9
Output: 4 5

 

Approach: The idea is to start iterating from the back of the loop starting from the number itself. Follow the steps given below to solve the problem.

  • If N is less than equal to 2, the answer doesn’t exist.
  • Otherwise iterate over the range [N/2, 0) using the variable i and perform the following tasks:
    • If the gcd of i and N-i is 1 then print this as the answer and return.

Below is the implementation of the above approach:

C++




/// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to split N into two numbers
void find(int n)
{
  
    // Base Case
    if (n <= 2) {
        cout << "-1";
    }
    else {
  
        // Since a < b
        // start from n/2
        for (int i = n / 2; i > 0; i--) {
  
            // Sum of a and b is n
            int a = i, b = n - i;
  
            // Check the gcd
            if (__gcd(a, b) == 1 && a < b) {
                cout << a <<", " << b;
                return;
            }
        }
    }
}
  
// Driver Code
int main()
{
  
    int N = 9;
  
    find(N);
  
    return 0;
}
Output
4, 5

Time complexity: O(N log(N))
Auxiliary space: O(1)




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!