📜  在给定范围内与GCD配对等于1

📅  最后修改于: 2021-05-04 11:53:44             🧑  作者: Mango

给定一个范围,即L和R,任务是确定我们是否可以形成对,使得每对的GCD为1。LR范围内的每个数字都应准确地包含在一对中。
例子:

Input: L = 1, R = 8
Output: Yes
{2, 7}, {4, 1}, {3, 8}, {6, 5}
All pairs have GCD as 1. 

Input: L = 2, R = 4
Output: No

方法:由于范围(L,R)中的每个数字都必须在每对中精确地包含一次。因此,如果LR是偶数,则不可能。如果LR为奇数,则打印所有相邻对,因为相邻对始终将GCD设为1。
下面是上述方法的实现:

C++
// C++ program to print all pairs
#include 
using namespace std;
 
// Function to print all pairs
bool checkPairs(int l, int r)
{
    // check if even
    if ((l - r) % 2 == 0)
        return false;
 
    /* We can print all adjacent pairs
      for (int i = l; i < r; i += 2) {
          cout << "{" << i << ", " << i + 1 << "}, ";
      } */
      
    return true;
}
 
// Driver Code
int main()
{
    int l = 1, r = 8;
    if (checkPairs(l, r))
       cout << "Yes";
    else
       cout << "No";
    return 0;
}


Java
// Java program to print all pairs
class GFG
{
// Function to print all pairs
static boolean checkPairs(int l, int r)
{
    // check if even
    if ((l - r) % 2 == 0)
        return false;
 
    /* We can print all adjacent pairs
    for (int i = l; i < r; i += 2)
    {
        System.out.print("{"+i+", "+i + 1+"}, ");
    } */
     
    return true;
}
 
// Driver Code
public static void main(String[] args)
{
    int l = 1, r = 8;
    if (checkPairs(l, r))
    System.out.println("Yes");
    else
    System.out.println("No");
}
}
 
// This code is contributed by mits


Python 3
# Python 3 program to print all pairs
 
# Function to print all pairs
def checkPairs(l, r) :
 
    # check if even
    if (l - r) % 2 == 0 :
        return False
 
    """ we can print all adjacent pairs
    for i in range(l,r,2) :
        print("{",i,",",i + 1, "},")
    """
     
    return True
 
# Driver Code
if __name__ == "__main__" :
 
    l, r = 1, 8
 
    if checkPairs(l, r) :
        print("Yes")
    else :
        print("No")
            
# This code is contributed by ANKITRAI1


C#
// C# program to print all pairs
using System;
 
class GFG
{
// Function to print all pairs
static bool checkPairs(int l, int r)
{
    // check if even
    if ((l - r) % 2 == 0)
        return false;
 
    /* We can print all adjacent pairs
    for (int i = l; i < r; i += 2)
    {
        System.out.print("{"+i+", "+i + 1+"}, ");
    } */
     
    return true;
}
 
// Driver Code
static public void Main ()
{
    int l = 1, r = 8;
    if (checkPairs(l, r))
    Console.Write("Yes");
    else
    Console.Write("No");
}
}
 
// This code is contributed by Raj


PHP


Javascript


输出:
Yes

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