📜  [L,R]范围内的所有可能的互质不同元素对

📅  最后修改于: 2021-04-29 14:46:23             🧑  作者: Mango

给定一个范围[L,R],任务是从该范围中查找所有可能的互质对,以使一个元素不会出现在单个对中。

例子:

Input : L=1 ; R=6
Output : 3
The answer is 3 [(1, 2) (3, 4) (5, 6)], 
all these pairs have GCD 1.

Input : L=2 ; R=4
Output : 1
The answer is 1 [(2, 3) or (3, 4)] 
as '3' can only be chosen for a single pair.

方法:对该问题的关键观察是,差为“ 1”的数字始终彼此互质,即互质。
该对的GCD始终为“ 1”。因此,答案将是(R-L + 1)/ 2 [(范围内的总数)/ 2]

  • 如果R-L + 1为奇数,则将剩下一个不能成对的元素。
  • 如果R-L + 1是偶数,则所有元素都可以形成对。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to count possible pairs
void CountPair(int L, int R)
{
  
    // total count of numbers in range
    int x = (R - L + 1);
  
    // Note that if 'x' is odd then
    // there will be '1' element left
    // which can't form a pair
  
    // printing count of pairs
    cout << x / 2 << "\n";
}
  
// Driver code
int main()
{
  
    int L, R;
  
    L = 1, R = 8;
    CountPair(L, R);
  
    return 0;
}


Java
// Java implementation of the approach
import java.util.*;
class solution
{
  
// Function to count possible pairs
static void CountPair(int L, int R)
{
  
    // total count of numbers in range
    int x = (R - L + 1);
  
    // Note that if 'x' is odd then
    // there will be '1' element left
    // which can't form a pair
  
    // printing count of pairs
    System.out.println(x / 2 + "\n");
}
  
// Driver code
public static void main(String args[])
{
  
    int L, R;
  
    L = 1; R = 8;
    CountPair(L, R);
  
}
}
//contributed by Arnab Kundu


Python3
# Python3 implementation of 
# the approach 
  
# Function to count possible 
# pairs
def CountPair(L,R):
  
    # total count of numbers 
    # in range
    x=(R-L+1)
  
    # Note that if 'x' is odd then 
    # there will be '1' element left 
    # which can't form a pair
    # printing count of pairs
    print(x//2)
  
# Driver code
if __name__=='__main__':
    L,R=1,8
    CountPair(L,R)
      
# This code is contributed by 
# Indrajit Sinha.


C#
// C# implementation of the approach
using System;
class GFG
{
  
// Function to count possible pairs
static void CountPair(int L, int R)
{
  
    // total count of numbers in range
    int x = (R - L + 1);
  
    // Note that if 'x' is odd then
    // there will be '1' element left
    // which can't form a pair
  
    // printing count of pairs
    Console.WriteLine(x / 2 + "\n");
}
  
// Driver code
public static void Main()
{
    int L, R;
  
    L = 1; R = 8;
    CountPair(L, R);
}
}
  
// This code is contributed 
// by inder_verma..


PHP


输出:
4

复杂度:O(1)