📜  从范围 [L, R] 生成一对整数,其 LCM 也在该范围内

📅  最后修改于: 2021-10-26 06:05:47             🧑  作者: Mango

给定两个整数LR ,任务是从范围[L, R]中找到一对整数其 LCM 也在范围 [L, R] 内。如果无法获得这样的对,则打印-1 。如果存在多对,则打印其中任何一对。

例子:

朴素方法:最简单的方法是生成LR之间的每一对并计算它们的 LCM。打印 LCM 范围内LR之间的一对。如果在给定范围内没有找到 LCM 对,则打印“-1”

时间复杂度: O(N)
辅助空间: O(1)

有效的方法:问题可以通过使用来解决 基于LCM(x, y)至少等于2*x的观察的贪婪技术这是(x, 2*x) 的LCM。以下是实现该方法的步骤:

  1. 选择 x 的值作为 L 并将 y 的值计算为 2*x
  2. 检查 y 是否小于 R。
  3. 如果 y 小于 R,则打印对 (x, y)
  4. 否则打印“-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)