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

📅  最后修改于: 2021-04-26 06:23:08             🧑  作者: 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)