给定两个整数L和R ,任务是从[L,R]范围中找到一对整数,并且LCM也在[L,R]范围内。如果无法获得这样的一对,则打印-1 。如果存在多对,则打印其中任何一对。
例子:
Input: L = 13, R = 69
Output: X =13, Y = 26
Explanation: LCM(x, y) = 26 which satisfies the conditions L ≤ x < y ≤ R and L <= LCM(x, y) <= R
Input: L = 1, R = 665
Output: X = 1, Y = 2
天真的方法:最简单的方法是生成L和R之间的每一对,并计算其LCM。打印LCM在范围L和R之间的线对。如果没有发现LCM在给定范围内,则打印“ -1” 。
时间复杂度: O(N)
辅助空间: O(1)
高效方法:可以通过使用以下方法解决问题 基于LCM(x,y)至少等于2 * x的贪婪技术,这是(x,2 * x)的LCM。以下是实现此方法的步骤:
- 选择x的值作为L,并计算y的值作为2 * x
- 检查y是否小于R。
- 如果y小于R,则打印对(x,y)
- 其他打印“ -1”
下面是上述方法的实现:
C++
// C++ implementation of the above approach
#include
using namespace std;
void lcmpair(int l, int r)
{
int x, y;
x = l;
y = 2 * l;
// Checking if any pair is possible
// or not in range(l, r)
if (y > r) {
// If not possible print(-1)
cout << "-1\n";
}
else {
// Print LCM pair
cout << "X = " << x << " Y = "
<< y << "\n";
}
}
// Driver code
int main()
{
int l = 13, r = 69;
// Function call
lcmpair(l, r);
return 0;
}
Java
// Java implementation of the above approach
import java.util.*;
class GFG{
static void lcmpair(int l, int r)
{
int x, y;
x = l;
y = 2 * l;
// Checking if any pair is possible
// or not in range(l, r)
if (y > r)
{
// If not possible print(-1)
System.out.print("-1\n");
}
else
{
// Print LCM pair
System.out.print("X = " + x +
" Y = " + y + "\n");
}
}
// Driver code
public static void main(String[] args)
{
int l = 13, r = 69;
// Function call
lcmpair(l, r);
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 implementation of the above approach
def lcmpair(l, r):
x = l
y = 2 * l
# Checking if any pair is possible
# or not in range(l, r)
if(y > r):
# If not possible print(-1)
print(-1)
else:
# Print LCM pair
print("X = {} Y = {}".format(x, y))
# Driver Code
l = 13
r = 69
# Function call
lcmpair(l, r)
# This code is contributed by Shivam Singh
C#
// C# implementation of the above approach
using System;
class GFG{
static void lcmpair(int l, int r)
{
int x, y;
x = l;
y = 2 * l;
// Checking if any pair is possible
// or not in range(l, r)
if (y > r)
{
// If not possible print(-1)
Console.Write("-1\n");
}
else
{
// Print LCM pair
Console.Write("X = " + x +
" Y = " + y + "\n");
}
}
// Driver code
public static void Main(String[] args)
{
int l = 13, r = 69;
// Function call
lcmpair(l, r);
}
}
// This code is contributed by shikhasingrajput
Javascript
输出:
X = 13 Y = 26
时间复杂度: O(1)
辅助空间: O(1)