📜  使它们的HCF和LCM相等的对数

📅  最后修改于: 2021-04-21 23:57:23             🧑  作者: Mango

给定非负整数的数组a []。任务是计算数组中对(i,j)的数量,以使LCM(a [i],a [j])= HCF(a [i],a [j])。
注意:(i,j)和(j,i)对被认为是相同的,并且我不应该等于j。
例子

Input : a[] = {3, 4, 3, 4, 5}
Output : 2
Pairs are (3, 3) and (4, 4)

Input  : a[] = {1, 1, 1}
Output : 3

天真的方法:生成所有可能的对,并用相等的HCF和LCM计数对。

C++
// Naive C++ program to count number of pairs
// such that their hcf and lcm are equal
#include 
using namespace std;
 
// Function to return HCF of two numbers
int gcd(int a, int b)
{
    if (a == 0)
        return b;
    return gcd(b % a, a);
}
 
// Function to return LCM of two numbers
int lcm(int a, int b)
{
    return (a * b) / gcd(a, b);
}
 
// Returns the number of valid pairs
int countPairs(int arr[], int n)
{
    int ans = 0; // initializing answer
 
    // Traversing the array. For each array
    // element, checking if it
    // follow the condition
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
            if (lcm(arr[i], arr[j]) == gcd(arr[i], arr[j]))
                ans++;
    return ans;
}
 
// Driver function
int main()
{
    int arr[] = { 1, 1, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << countPairs(arr, n);
    return 0;
}


Java
// Naive Java program to count number of pairs
// such that their hcf and lcm are equal
import java.util.*;
 
class GFG{
  
// Function to return HCF of two numbers
static int gcd(int a, int b)
{
    if (a == 0)
        return b;
    return gcd(b % a, a);
}
  
// Function to return LCM of two numbers
static int lcm(int a, int b)
{
    return (a * b) / gcd(a, b);
}
  
// Returns the number of valid pairs
static int countPairs(int arr[], int n)
{
    int ans = 0; // initializing answer
  
    // Traversing the array. For each array
    // element, checking if it
    // follow the condition
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
            if (lcm(arr[i], arr[j]) == gcd(arr[i], arr[j]))
                ans++;
    return ans;
}
  
// Driver function
public static void main(String[] args)
{
    int arr[] = { 1, 1, 1 };
    int n = arr.length;
    System.out.print(countPairs(arr, n));
}
}
 
// This code is contributed by Rajput-Ji


Python3
# Naive Python program to count number of pairs
# such that their hcf and lcm are equal
 
# Function to return HCF of two numbers
def gcd(a, b):
    if (a == 0):
        return b;
    return gcd(b % a, a);
 
# Function to return LCM of two numbers
def lcm(a, b):
    return (a * b) / gcd(a, b);
 
# Returns the number of valid pairs
def countPairs(arr, n):
    ans = 0; # initializing answer
 
    # Traversing the array. For each array
    # element, checking if it
    # follow the condition
    for i in range(n):
        for j in range(i+1,n):
            if (lcm(arr[i], arr[j]) == gcd(arr[i], arr[j])):
                ans+=1;
    return ans;
 
# Driver function
if __name__ == '__main__':
    arr = [ 1, 1, 1 ];
    n = len(arr);
    print(countPairs(arr, n));
 
# This code is contributed by 29AjayKumar


C#
// Naive C# program to count number of pairs
// such that their hcf and lcm are equal
using System;
 
class GFG{
   
// Function to return HCF of two numbers
static int gcd(int a, int b)
{
    if (a == 0)
        return b;
    return gcd(b % a, a);
}
   
// Function to return LCM of two numbers
static int lcm(int a, int b)
{
    return (a * b) / gcd(a, b);
}
   
// Returns the number of valid pairs
static int countPairs(int []arr, int n)
{
    int ans = 0; // initializing answer
   
    // Traversing the array. For each array
    // element, checking if it
    // follow the condition
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
            if (lcm(arr[i], arr[j]) == gcd(arr[i], arr[j]))
                ans++;
    return ans;
}
   
// Driver function
public static void Main(String[] args)
{
    int []arr = { 1, 1, 1 };
    int n = arr.Length;
    Console.Write(countPairs(arr, n));
}
}
 
// This code is contributed by 29AjayKumar


Javascript


C++
// C++ program to count number of pairs
// such that their hcf and lcm are equal
#include 
using namespace std;
 
// Function to count number of pairs
// such that their hcf and lcm are equal
int countPairs(int a[], int n)
{
    // Store frequencies of array elements
    unordered_map frequency;
    for (int i = 0; i < n; i++) {
        frequency[a[i]]++;
    }
 
    int count = 0;
 
    // Count of pairs (arr[i], arr[j])
    // where arr[i] = arr[j]
    for (auto x : frequency) {
        int f = x.second;
        count += f * (f - 1) / 2;
    }
 
    // Count of pairs (arr[i], arr[j]) where
    // arr[i] = arr[j],
    return count;
}
 
// Driver function
int main()
{
    int arr[] = { 1, 1, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << countPairs(arr, n);
    return 0;
}


Java
// Java program to count number of pairs
// such that their hcf and lcm are equal
 
import java.util.*;
 
class GFG{
  
// Function to count number of pairs
// such that their hcf and lcm are equal
static int countPairs(int arr[], int n)
{
    // Store frequencies of array elements
    HashMap frequency =
            new HashMap();
    for (int i = 0; i < n; i++) {
        if(frequency.containsKey(arr[i])){
            frequency.put(arr[i], frequency.get(arr[i])+1);
        }else{
            frequency.put(arr[i], 1);
    }
    }
  
    int count = 0;
  
    // Count of pairs (arr[i], arr[j])
    // where arr[i] = arr[j]
    for (Map.Entry x : frequency.entrySet()) {
        int f = x.getValue();
        count += f * (f - 1) / 2;
    }
  
    // Count of pairs (arr[i], arr[j]) where
    // arr[i] = arr[j],
    return count;
}
  
// Driver function
public static void main(String[] args)
{
    int arr[] = { 1, 1, 1 };
    int n = arr.length;
    System.out.print(countPairs(arr, n));
}
}
 
// This code contributed by sapnasingh4991


C#
// C# program to count number of pairs
// such that their hcf and lcm are equal
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to count number of pairs
// such that their hcf and lcm are equal
static int countPairs(int []a, int n)
{
    // Store frequencies of array elements
    Dictionary frequency = new Dictionary();
        for (int i = 0; i < n; i++)
        {
            if (frequency.ContainsKey(a[i])) 
            {
                var val = frequency[a[i]];
                frequency.Remove(a[i]);
                frequency.Add(a[i], val + 1); 
            } 
            else
            {
                frequency.Add(a[i], 1);
            }
        }
          
    int count = 0;
 
    // Count of pairs (arr[i], arr[j])
    // where arr[i] = arr[j]
    foreach(KeyValuePair entry in frequency) {
        int f = entry.Value;
        count += f * (f - 1) / 2;
    }
 
    // Count of pairs (arr[i], arr[j]) where
    // arr[i] = arr[j],
    return count;
}
 
// Driver function
public static void Main(String[] args)
{
    int []arr = { 1, 1, 1 };
    int n = arr.Length;
    Console.Write(countPairs(arr, n));
}
}
 
// This code is contributed by shivanisinghss2110


Python3
# Python 3 program to count number of pairs
# such that their hcf and lcm are equal
from collections import defaultdict
  
# Function to count number of pairs
# such that their hcf and lcm are equal
def countPairs(a, n):
 
    # Store frequencies of array elements
    frequency = defaultdict(int)
    for i in range(n) :
        frequency[a[i]] += 1
     
  
    count = 0
  
    # Count of pairs (arr[i], arr[j])
    # where arr[i] = arr[j]
    for x in frequency.keys():
        f = frequency[x]
        count += f * (f - 1) // 2
  
    # Count of pairs (arr[i], arr[j]) where
    # arr[i] = arr[j],
    return count
  
# Driver function
if __name__ == "__main__":
     
    arr = [ 1, 1, 1 ]
    n = len(arr)
    print(countPairs(arr, n))
 
# This code is contributed by chitranayal


输出:
3

高效的方法:如果仔细观察,可以证明只有当数字也相等时,两个数字的HCF和LCM才能相等。
证明

Let,
HCF(a[i], a[j]) = LCM(a[i], a[j]) = K

Since HCF(a[i], a[j]) = k,
a[i] = k*n1, a[j] = k*n2, for some natural numbers n1, n2

We know that,
HCF × LCM = Product of the two numbers

Therefore,
k*k = k*n1 × k*n2
or, n1*n2 = 1

Implies, n1 = n2 = 1, since n1, n2 are natural numbers.

Therefore,
a[i] = k*n1 = k, a[j] = k*n2 = k
i.e. the numbers must be equal.

因此,我们必须计算对中具有相同元素的对。
可以看出,只有arr [i] = arr [j]形式的对(arr [i],arr [j])会满足给定条件。因此,现在问题被简化为寻找对数(arr [i],arr [j]),从而使arr [i] = arr [j]。
下面是上述方法的实现:

C++

// C++ program to count number of pairs
// such that their hcf and lcm are equal
#include 
using namespace std;
 
// Function to count number of pairs
// such that their hcf and lcm are equal
int countPairs(int a[], int n)
{
    // Store frequencies of array elements
    unordered_map frequency;
    for (int i = 0; i < n; i++) {
        frequency[a[i]]++;
    }
 
    int count = 0;
 
    // Count of pairs (arr[i], arr[j])
    // where arr[i] = arr[j]
    for (auto x : frequency) {
        int f = x.second;
        count += f * (f - 1) / 2;
    }
 
    // Count of pairs (arr[i], arr[j]) where
    // arr[i] = arr[j],
    return count;
}
 
// Driver function
int main()
{
    int arr[] = { 1, 1, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << countPairs(arr, n);
    return 0;
}

Java

// Java program to count number of pairs
// such that their hcf and lcm are equal
 
import java.util.*;
 
class GFG{
  
// Function to count number of pairs
// such that their hcf and lcm are equal
static int countPairs(int arr[], int n)
{
    // Store frequencies of array elements
    HashMap frequency =
            new HashMap();
    for (int i = 0; i < n; i++) {
        if(frequency.containsKey(arr[i])){
            frequency.put(arr[i], frequency.get(arr[i])+1);
        }else{
            frequency.put(arr[i], 1);
    }
    }
  
    int count = 0;
  
    // Count of pairs (arr[i], arr[j])
    // where arr[i] = arr[j]
    for (Map.Entry x : frequency.entrySet()) {
        int f = x.getValue();
        count += f * (f - 1) / 2;
    }
  
    // Count of pairs (arr[i], arr[j]) where
    // arr[i] = arr[j],
    return count;
}
  
// Driver function
public static void main(String[] args)
{
    int arr[] = { 1, 1, 1 };
    int n = arr.length;
    System.out.print(countPairs(arr, n));
}
}
 
// This code contributed by sapnasingh4991

C#

// C# program to count number of pairs
// such that their hcf and lcm are equal
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to count number of pairs
// such that their hcf and lcm are equal
static int countPairs(int []a, int n)
{
    // Store frequencies of array elements
    Dictionary frequency = new Dictionary();
        for (int i = 0; i < n; i++)
        {
            if (frequency.ContainsKey(a[i])) 
            {
                var val = frequency[a[i]];
                frequency.Remove(a[i]);
                frequency.Add(a[i], val + 1); 
            } 
            else
            {
                frequency.Add(a[i], 1);
            }
        }
          
    int count = 0;
 
    // Count of pairs (arr[i], arr[j])
    // where arr[i] = arr[j]
    foreach(KeyValuePair entry in frequency) {
        int f = entry.Value;
        count += f * (f - 1) / 2;
    }
 
    // Count of pairs (arr[i], arr[j]) where
    // arr[i] = arr[j],
    return count;
}
 
// Driver function
public static void Main(String[] args)
{
    int []arr = { 1, 1, 1 };
    int n = arr.Length;
    Console.Write(countPairs(arr, n));
}
}
 
// This code is contributed by shivanisinghss2110

Python3

# Python 3 program to count number of pairs
# such that their hcf and lcm are equal
from collections import defaultdict
  
# Function to count number of pairs
# such that their hcf and lcm are equal
def countPairs(a, n):
 
    # Store frequencies of array elements
    frequency = defaultdict(int)
    for i in range(n) :
        frequency[a[i]] += 1
     
  
    count = 0
  
    # Count of pairs (arr[i], arr[j])
    # where arr[i] = arr[j]
    for x in frequency.keys():
        f = frequency[x]
        count += f * (f - 1) // 2
  
    # Count of pairs (arr[i], arr[j]) where
    # arr[i] = arr[j],
    return count
  
# Driver function
if __name__ == "__main__":
     
    arr = [ 1, 1, 1 ]
    n = len(arr)
    print(countPairs(arr, n))
 
# This code is contributed by chitranayal
输出:
3