给定两个数字L和R ,任务是找到两个不同的最小正整数X和Y ,以使它们的LCM在[L,R]范围内。如果不存在任何X和Y值,则打印“ -1” 。
例子:
Input: L = 3, R = 8
Output: x = 3, y=6
Explanation:
LCM of 3 and 6 is 6 which is in range 3, 8
Input: L = 88, R = 90
Output: -1
Explanation:
Minimum possible x and y are 88 and 176 respectively, but 176 is greater than 90.
方法:想法是以X和Y的LCM在给定范围[L,R]中的方式选择X和Y的值。步骤如下:
- 对于X的最小值,请选择L作为最小值,因为这是给定范围内的最小值。
- 现在为Y的值选择2 * L,因为这是LCM为L的Y的最小值。
- 现在,如果X和Y的上述两个值在[L,R]范围内,则这是必需的整数对,其中X和Y的最小可能值。
- 否则,请打印“ -1” ,因为不存在其他任何对。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find two distinct numbers
// X and Y s.t. their LCM lies between
// L and R and X, Y are minimum possible
void answer(int L, int R)
{
// Check if 2*L lies in range L, R
if (2 * L <= R)
// Print the answer
cout << L << ", "
<< 2 * L << "\n";
else
cout << -1;
}
// Driver Code
int main()
{
// Given value of ranges
int L = 3, R = 8;
// Function call
answer(L, R);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
class GFG{
// Function to find two distinct numbers
// X and Y s.t. their LCM lies between
// L and R and X, Y are minimum possible
static void answer(int L, int R)
{
// Check if 2*L lies in range L, R
if (2 * L <= R)
// Print the answer
System.out.println(L + ", " + (2 * L));
else
System.out.println("-1");
}
// Driver Code
public static void main(String[] args)
{
// Given value of ranges
int L = 3, R = 8;
// Function call
answer(L, R);
}
}
// This code is contributed by sanjoy_62
Python3
# Python3 program for the above approach
# Function to find two distinct numbers
# X and Y s.t. their LCM lies between
# L and R and X, Y are minimum possible
def answer(L, R):
# Check if 2*L lies in range L, R
if (2 * L <= R):
# Print the answer
print(L, ",", 2 * L)
else:
print(-1)
# Driver Code
# Given value of ranges
L = 3
R = 8
# Function call
answer(L, R)
# This code is contributed by sanjoy_62
C#
// C# program for the above approach
using System;
class GFG{
// Function to find two distinct numbers
// X and Y s.t. their LCM lies between
// L and R and X, Y are minimum possible
static void answer(int L, int R)
{
// Check if 2*L lies in range L, R
if (2 * L <= R)
// Print the answer
Console.WriteLine(L + ", " + (2 * L));
else
Console.WriteLine("-1");
}
// Driver Code
public static void Main()
{
// Given value of ranges
int L = 3, R = 8;
// Function call
answer(L, R);
}
}
// This code is contributed by sanjoy_62
Javascript
输出:
3, 6
时间复杂度: O(1)
辅助空间: O(1)