Given an integer N, the task is to find two pairs of positive integers such that the GCD of the first pair is the same as the LCM of the second pair and the sum of the values is equal to N.
Note: If multiple outputs possible, print any of them
Examples:
Input: N = 9
Output: 6 1 1 1
Explanation: The GCD(6, 1) = 1 and LCM(1, 1) = 1, GCD is equal to LCM.
The sum of all numbers (6 + 1 + 1 + 1) = 9
Input: N = 3
Output: -1
Explanation: We can’t give positive integer values to all the four values.
Approach: The approach of the problem is based on the following observation:
GCD of any number with 1 is always 1 and LCM of 1 and 1 will always be 1.
So, fix first number of GCD N-3 and second as 1 and all other numbers of LCM as 1 and 1.
So at the end the sum of all numbers (N-3 + 1 + 1 + 1) will be N and GCD (N-3, 1) will be equal to LCM(1, 1).
Follow the steps mentioned below to implement the observation:
- If N < 4, then finding four such values is not possible.
- Else find the four values as per the above observation.
Below is the code for above implementation:
C
#include <stdio.h>
void find( int n)
{
if (n < 4) {
printf ( "-1\n" );
}
else {
int a, b, c, d;
a = n - 3;
b = 1;
c = 1;
d = 1;
printf ( "%d %d %d %d" ,a,b,c,d);
}
}
void main()
{
int N = 9;
find(9);
}
|
C++
#include <bits/stdc++.h>
using namespace std;
void find( int n)
{
if (n < 4) {
cout << -1 << endl;
}
else {
int a, b, c, d;
a = n - 3;
b = 1;
c = 1;
d = 1;
cout << a << " " << b << " "
<< c << " " << d;
}
}
int main()
{
int N = 9;
find(9);
return 0;
}
|
Java
import java.io.*;
class GFG
{
public static void find( int n)
{
if (n < 4 ) {
System.out.println(- 1 );
}
else {
int a, b, c, d;
a = n - 3 ;
b = 1 ;
c = 1 ;
d = 1 ;
System.out.print(a + " " + b + " " + c + " "
+ d);
}
}
public static void main(String[] args)
{
int N = 9 ;
find( 9 );
}
}
|
Python3
def find(n):
if (n < 4 ):
print ( "-1" ,end = " " )
else :
a = n - 3
b = 1
c = 1
d = 1
print (a, end = " " )
print (b, end = " " )
print (c, end = " " )
print (d, end = " " )
N = 9
find( 9 )
|
C#
using System;
class GFG
{
static void find( int n)
{
if (n < 4) {
Console.WriteLine(-1);
}
else {
int a, b, c, d;
a = n - 3;
b = 1;
c = 1;
d = 1;
Console.Write(a + " " + b + " " + c + " " + d);
}
}
public static void Main()
{
int N = 9;
find(9);
}
}
|
Javascript
<script>
function find(n){
if (n < 4)
document.write( "-1" , " " )
else {
let a = n - 3
let b = 1
let c = 1
let d = 1
document.write(a, " " )
document.write(b, " " )
document.write(c, " " )
document.write(d, " " )
}
}
let N = 9
find(9)
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
28 Apr, 2022
Like Article
Save Article