Split given number into two distinct numbers having GCD 1
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:
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++
#include <bits/stdc++.h>
using namespace std;
void find( int n)
{
if (n <= 2) {
cout << "-1" ;
}
else {
for ( int i = n / 2; i > 0; i--) {
int a = i, b = n - i;
if (__gcd(a, b) == 1 && a < b) {
cout << a << ", " << b;
return ;
}
}
}
}
int main()
{
int N = 9;
find(N);
return 0;
}
|
Java
class GFG {
public static void find( int n) {
if (n <= 2 ) {
System.out.println( "-1" );
} else {
for ( int i = n / 2 ; i > 0 ; i--) {
int a = i, b = n - i;
if (__gcd(a, b) == 1 && a < b) {
System.out.println(a + ", " + b);
return ;
}
}
}
}
static int __gcd( int a, int b) {
if (b == 0 )
return a;
return __gcd(b, a % b);
}
public static void main(String args[]) {
int N = 9 ;
find(N);
}
}
|
Python3
import math
def find(n):
if (n < = 2 ):
print ( "-1" )
else :
for i in range (n / / 2 , - 1 , - 1 ):
a = i
b = n - i
if (math.gcd(a, b) = = 1 and a < b):
print (a, "," , b)
return
if __name__ = = "__main__" :
N = 9
find(N)
|
C#
/// C# program for the above approach
using System;
public class GFG {
public static void find( int n) {
if (n <= 2) {
Console.WriteLine( "-1" );
} else {
for ( int i = n / 2; i > 0; i--) {
int a = i, b = n - i;
if (__gcd(a, b) == 1 && a < b) {
Console.WriteLine(a + ", " + b);
return ;
}
}
}
}
static int __gcd( int a, int b) {
if (b == 0)
return a;
return __gcd(b, a % b);
}
public static void Main(String []args) {
int N = 9;
find(N);
}
}
|
Javascript
<script>
function __gcd(a, b) {
if (a == 0)
return b;
if (b == 0)
return a;
if (a == b)
return a;
if (a > b)
return __gcd(a - b, b);
return __gcd(a, b - a);
}
function find(n) {
if (n <= 2) {
document.write( "-1" );
}
else {
for (let i = Math.floor(n / 2); i > 0; i--) {
let a = i, b = n - i;
if (__gcd(a, b) == 1 && a < b) {
document.write(a + ", " + b);
return ;
}
}
}
}
let N = 9;
find(N);
</script>
|
Time complexity: O(N log(N))
Auxiliary space: O(1)
Last Updated :
27 Dec, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...