📜  计算数组中的可分割对

📅  最后修改于: 2021-10-27 07:53:49             🧑  作者: Mango

给定一个数组,计算数组中的对,使得对中的一个元素除以另一个。
例子:

Input  : arr[] = {1, 2, 3}
Output : 2
The two pairs are (1, 2) and (1, 3)

Input : arr[] = {2, 3, 5, 7}
Output: 0
C++
// CPP program to count divisible pairs.
#include 
using namespace std;
 
int countDivisibles(int arr[], int n)
{
    int res = 0;
 
    // Iterate through all pairs
    for (int i=0; i


Java
// Java program to count
// divisible pairs.
 
class GFG {
     
// Function returns count
// of divisible pairs
static int countDivisibles(int arr[],
                              int n)
{
    int res = 0;
 
    // Iterate through all pairs
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
         
        // Increment count if
        // one divides other
        if (arr[i] % arr[j] == 0 ||
            arr[j] % arr[i] == 0)
            res++;
 
    return res;
}
 
// Driver Code
public static void main(String[] args)
{
    int a[] = new int[]{1, 2, 3, 9};
    int n = a.length;
    System.out.print(countDivisibles(a, n));
}
}
 
// This code is contributed by Smitha.


Python3
# Python3 program to count
# divisible pairs.
 
def countDivisibles(arr, n) :
 
    res = 0
 
    # Iterate through all pairs
    for i in range(0, n) :
        for j in range(i+1, n) :
             
            # Increment count if one divides
            # other
            if (arr[i] % arr[j] == 0 or
            arr[j] % arr[i] == 0) :
                res+=1
 
    return res
 
# Driver code
if __name__=='__main__':
    a = [1, 2, 3, 9]
    n = len(a)
    print(countDivisibles(a, n) )
 
# this code is contributed by
# Smitha Dinesh Semwal


C#
// Java program to count
// divisible pairs.
using System;
 
class GFG {
     
// Function returns count
// of divisible pairs
static int countDivisibles(int []arr,
                              int n)
{
    int res = 0;
 
    // Iterate through all pairs
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
         
        // Increment count if
        // one divides other
        if (arr[i] % arr[j] == 0 ||
            arr[j] % arr[i] == 0)
            res++;
 
    return res;
}
 
// Driver Code
public static void Main(String[] args)
{
    int[] a = new int[4] {1, 2, 3, 9};
    int n = a.Length;
    Console.Write(countDivisibles(a, n));
}
}
 
// This code is contributed by Smitha.


PHP


Javascript


输出:
4

小范围数字的有效解决方案
1) 将数组的所有元素插入哈希表中。
2) 找出数组中的最大元素。
3)对于每个数组元素,在哈希表中搜索它的倍数(直到最大值)。如果找到,则增加结果。
在这里也可以通过对方法稍加修改来处理不同的情况,如负数和重复。

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