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

📅  最后修改于: 2021-10-26 02:53:03             🧑  作者: 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


Javascript


输出:

4

复杂度:O(1)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程