Generate a pair of integers from a range [L, R] whose LCM also lies within the range
Last Updated :
09 Dec, 2021
Given two integers L and R , the task is to find a pair of integers from the range [L, R] having LCM within the range [L, R] as well. If no such pair can be obtained, then print -1 . If multiple pairs exist, print any one of them.
Examples:
Input: L = 13, R = 69Output: X =13, Y = 26Explanation: LCM(x, y) = 26 which satisfies the conditions L ? x < y ? R and L <= LCM(x, y) <= R
Input: L = 1, R = 665Output: X = 1, Y = 2
Naive Approach: The simplest approach is to generate every pair between L and R and compute their LCM . Print a pair having LCM between the range L and R . If no pair is found to have LCM in the given range, print “-1” .
Time Complexity: O(N)Auxiliary Space: O(1)
Efficient Approach: The problem can be solved by using the Greedy technique based on the observation that LCM(x, y) is at least equal to 2*x which is LCM of (x, 2*x) . Below are the steps to implement the approach:
Select the value of x as L and compute the value of y as 2*x
Check if y is less than R or not.
If y is less than R then print the pair (x, y)
Else print “-1”
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
void lcmpair(int l, int r)
{
int x, y;
x = l;
y = 2 * l;
if (y > r) {
cout << "-1\n";
}
else {
cout << "X = " << x << " Y = "
<< y << "\n";
}
}
int main()
{
int l = 13, r = 69;
lcmpair(l, r);
return 0;
}
Java
import java.util.*;
class GFG{
static void lcmpair(int l, int r)
{
int x, y;
x = l;
y = 2 * l;
if (y > r)
{
System.out.print("-1\n");
}
else
{
System.out.print("X = " + x +
" Y = " + y + "\n");
}
}
public static void main(String[] args)
{
int l = 13, r = 69;
lcmpair(l, r);
}
}
Python3
def lcmpair(l, r):
x = l
y = 2 * l
if(y > r):
print(-1)
else:
print("X = {} Y = {}".format(x, y))
l = 13
r = 69
lcmpair(l, r)
C#
using System;
class GFG{
static void lcmpair(int l, int r)
{
int x, y;
x = l;
y = 2 * l;
if (y > r)
{
Console.Write("-1\n");
}
else
{
Console.Write("X = " + x +
" Y = " + y + "\n");
}
}
public static void Main(String[] args)
{
int l = 13, r = 69;
lcmpair(l, r);
}
}
Javascript
<script>
function lcmpair(l , r) {
var x, y;
x = l;
y = 2 * l;
if (y > r) {
document.write("-1\n");
} else {
document.write("X = " + x + " Y = " + y + "\n");
}
}
var l = 13, r = 69;
lcmpair(l, r);
</script>
Time Complexity: O(1)Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Add Your Comment
Please Login to comment...