给定两个整数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)