📜  使 HCF 和 LCM 相等的对数

📅  最后修改于: 2021-10-26 06:08:45             🧑  作者: Mango

给定一个非负整数数组 a[]。任务是计算数组中对 (i, j) 的数量,使得 LCM(a[i], a[j]) = HCF(a[i], a[j])。
注意:一对 (i, j) 和 (j, i) 被认为是相同的,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


Javascript


输出:
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

蟒蛇3

# 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

Javascript


输出:
3

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