📌  相关文章
📜  从具有等于对中最小元素的 GCD 的数组中计算对

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

给定一个由N 个整数组成的数组arr[] ,任务是找到对的数量,使得任何一对数组元素的 GCD 是该对的最小元素。

例子:

朴素方法:解决给定问题的最简单方法是从给定数组中生成所有可能的对,如果存在任何对的 GCD 等于该对的最小元素,则计算该对。检查所有对后,打印得到的计数值作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to count pairs from an
// array having GCD equal to
// minimum element of that pair
int countPairs(int arr[], int N)
{
    // Stores the resultant count
    int count = 0;
 
    // Iterate over the range [0, N - 2]
    for (int i = 0; i < N - 1; i++) {
 
        // Iterate over the range [i + 1, N]
        for (int j = i + 1; j < N; j++) {
 
            // If arr[i] % arr[j] is 0
            // or arr[j] % arr[i] is 0
            if (arr[i] % arr[j] == 0
                || arr[j] % arr[i] == 0) {
 
                // Increment count by 1
                count++;
            }
        }
    }
 
    // Return the resultant count
    return count;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 3, 1, 2 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << countPairs(arr, N);
 
    return 0;
}


Java
// java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
public class GFG {
 
    // Function to count pairs from an
    // array having GCD equal to
    // minimum element of that pair
    static int countPairs(int arr[], int N)
    {
       
        // Stores the resultant count
        int count = 0;
 
        // Iterate over the range [0, N - 2]
        for (int i = 0; i < N - 1; i++) {
 
            // Iterate over the range [i + 1, N]
            for (int j = i + 1; j < N; j++) {
 
                // If arr[i] % arr[j] is 0
                // or arr[j] % arr[i] is 0
                if (arr[i] % arr[j] == 0
                    || arr[j] % arr[i] == 0) {
 
                    // Increment count by 1
                    count++;
                }
            }
        }
 
        // Return the resultant count
        return count;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        int arr[] = { 2, 3, 1, 2 };
        int N = arr.length;
        System.out.print(countPairs(arr, N));
    }
}
 
// This code is contributed by Kingash.


Python3
# Python3 program for the above approach
 
# Function to count pairs from an
# array having GCD equal to
# minimum element of that pair
def countPairs(arr, N):
   
    # Stores the resultant count
    count = 0
 
    # Iterate over the range [0, N - 2]
    for i in range(N - 1):
       
        # Iterate over the range [i + 1, N]
        for j in range(i + 1, N):
           
            # If arr[i] % arr[j] is 0
            # or arr[j] % arr[i] is 0
            if (arr[i] % arr[j] == 0 or arr[j] % arr[i] == 0):
                 
                # Increment count by 1
                count += 1
                  
    # Return the resultant count
    return count
 
# Driver Code
if __name__ == '__main__':
    arr = [2, 3, 1, 2]
    N = len(arr)
    print (countPairs(arr, N))
 
# This code is contributed by mohit kumar 29.


C#
// C# program for the above approach
 
using System;
 
public class GFG {
 
    // Function to count pairs from an
    // array having GCD equal to
    // minimum element of that pair
    static int countPairs(int[] arr, int N)
    {
 
        // Stores the resultant count
        int count = 0;
 
        // Iterate over the range [0, N - 2]
        for (int i = 0; i < N - 1; i++) {
 
            // Iterate over the range [i + 1, N]
            for (int j = i + 1; j < N; j++) {
 
                // If arr[i] % arr[j] is 0
                // or arr[j] % arr[i] is 0
                if (arr[i] % arr[j] == 0
                    || arr[j] % arr[i] == 0) {
 
                    // Increment count by 1
                    count++;
                }
            }
        }
 
        // Return the resultant count
        return count;
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
 
        int[] arr = { 2, 3, 1, 2 };
        int N = arr.Length;
        Console.WriteLine(countPairs(arr, N));
    }
}
 
// This code is contributed by ukasp.


Javascript


C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to count pairs from an
// array having GCD equal to
// minimum element of that pair
int CountPairs(int arr[], int N)
{
    // Stores the resultant count
    int res = 0;
 
    // Stores the frequency of
    // each array element
    map mp;
 
    // Traverse the array arr[]
    for (int i = 0; i < N; i++) {
        mp[arr[i]]++;
    }
    // Iterate over the Map mp
    for (auto p : mp) {
 
        // Stores the array element
        int x = p.first;
 
        // Stores the count
        // of array element x
        int y = p.second;
 
        // If x is 1
        if (x == 1) {
 
            // Increment res by N-1
            res += N - 1;
            continue;
        }
 
        // Increment res by yC2
        res += (y * (y - 1)) / 2;
 
        // Iterate over the
        // range [2, sqrt(x)]
        for (int j = 2;
             j <= sqrt(x); j++) {
 
            // If x is divisble by j
            if (x % j == 0) {
 
                // Increment the value
                // of res by mp[j]
                res += mp[j];
 
                // If j is not equal to x/j
                if (j != x / j)
 
                    // Increment res
                    // by mp[x/j]
                    res += mp[x / j];
            }
        }
    }
 
    // Return the resultant count
    return res;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 3, 1, 2 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << CountPairs(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG {
   
      // Function to count pairs from an
    // array having GCD equal to
    // minimum element of that pair
    static int CountPairs(int arr[], int N)
    {
       
        // Stores the resultant count
        int res = 0;
 
        // Stores the frequency of
        // each array element
        Map mp = new HashMap<>();
 
        // Traverse the array arr[]
        for (int i = 0; i < N; i++) {
              Integer c = mp.get(arr[i]);
            mp.put(arr[i], (c == null) ? 1 : c + 1);
        }
        // Iterate over the Map mp
          Iterator> itr = mp.entrySet().iterator();
          
        while(itr.hasNext())
        {
             Map.Entry entry = itr.next();
          
            // Stores the array element
            int x = (int)entry.getKey();
 
            // Stores the count
            // of array element x
            int y = (int)entry.getValue();
 
            // If x is 1
            if (x == 1) {
 
                // Increment res by N-1
                res += N - 1;
                continue;
            }
 
            // Increment res by yC2
            res += (y * (y - 1)) / 2;
 
            // Iterate over the
            // range [2, sqrt(x)]
            for (int j = 2; j <= Math.sqrt(x); j++) {
 
                // If x is divisble by j
                if (x % j == 0) {
 
                    // Increment the value
                    // of res by mp[j]
                    res += mp.get(j);
 
                    // If j is not equal to x/j
                    if (j != x / j)
 
                        // Increment res
                        // by mp[x/j]
                        res += mp.get((int)x / j);
                }
            }
        }
 
        // Return the resultant count
        return res;
    }
 
    // Driver Code
    public static void main (String[] args) {
        int arr[] = { 2, 3, 1, 2 };
        int N = arr.length;
        System.out.println(CountPairs(arr, N));
    }
}
 
// This code is contributed by Dharanendra L V.


Python3
# Python3 program for the above approach
from math import sqrt
 
# Function to count pairs from an
# array having GCD equal to
# minimum element of that pair
def CountPairs(arr, N):
     
    # Stores the resultant count
    res = 0
 
    # Stores the frequency of
    # each array element
    mp = {}
 
    # Traverse the array arr[]
    for i in range(N):
        if (arr[i] in mp):
            mp[arr[i]] += 1
        else:
            mp[arr[i]] = 1
             
    # Iterate over the Map mp
    for key, value in mp.items():
         
        # Stores the array element
        x = key
 
        # Stores the count
        # of array element x
        y = value
 
        # If x is 1
        if (x == 1):
 
            # Increment res by N-1
            res += N - 1
            continue
 
        # Increment res by yC2
        res += (y * (y - 1)) // 2
 
        # Iterate over the
        # range [2, sqrt(x)]
        for j in range(2, int(sqrt(x)) + 1, 1):
 
            # If x is divisble by j
            if (x % j == 0):
 
                # Increment the value
                # of res by mp[j]
                res += mp[j]
 
                # If j is not equal to x/j
                if (j != x // j):
 
                    # Increment res
                    # by mp[x/j]
                    res += mp[x // j]
 
    # Return the resultant count
    return res
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 2, 3, 1, 2 ]
    N = len(arr)
     
    print(CountPairs(arr, N))
 
# This code is contributed by SURENDRA_GANGWAR


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to count pairs from an
// array having GCD equal to
// minimum element of that pair
static int CountPairs(int []arr, int N)
{
     
    // Stores the resultant count
    int res = 0;
 
    // Stores the frequency of
    // each array element
    Dictionary mp = new Dictionary();
 
    // Traverse the array arr[]
    for(int i = 0; i < N; i++)
    {
        if (mp.ContainsKey(arr[i]))
            mp[arr[i]]++;
        else
            mp.Add(arr[i], 1);
    }
     
    // Iterate over the Map mp
    foreach(KeyValuePair kvp in mp)
    {
 
        // Stores the array element
        int x = kvp.Key;
 
        // Stores the count
        // of array element x
        int y = kvp.Value;
 
        // If x is 1
        if (x == 1)
        {
             
            // Increment res by N-1
            res += N - 1;
            continue;
        }
 
        // Increment res by yC2
        res += (y * (y - 1)) / 2;
 
        // Iterate over the
        // range [2, sqrt(x)]
        for(int j = 2;
                j <= Math.Sqrt(x); j++)
        {
 
            // If x is divisble by j
            if (x % j == 0)
            {
 
                // Increment the value
                // of res by mp[j]
                res += mp[j];
 
                // If j is not equal to x/j
                if (j != x / j)
 
                    // Increment res
                    // by mp[x/j]
                    res += mp[x / j];
            }
        }
    }
 
    // Return the resultant count
    return res;
}
 
// Driver Code
public static void Main()
{
    int []arr = { 2, 3, 1, 2 };
    int N = arr.Length;
     
    Console.Write(CountPairs(arr, N));
}
}
 
// This code is contributed by bgangwar59


Javascript


输出:
4

时间复杂度: O(N 2 )
辅助空间: O(1)

高效的方法:上述方法可以基于以下观察进行优化:

  • 对的最小元素应该除以对的最大元素,可以观察到元素1总共可以形成(N-1)对
  • 每个元素都可以形成^YC_2         与自身配对,其中Y是数组元素的计数。
  • 这个想法是遍历每个数组元素的除数并增加可以由除数的频率形成的对的计数。

请按照以下步骤解决问题:

  • 初始化一个变量,比如res ,它存储结果计数。
  • 初始化一个映射,比如mp ,它存储每个数组元素的计数。
  • 遍历数组arr[]并增加mparr[i]的计数。
  • 迭代 map mp对并执行以下操作:
    • 将数组元素的值存储在变量中,比如X并将该数字的频率存储在变量Y 中
    • 如果X 的值为1 ,则将res的值增加(N – 1)并继续。
    • res的值增加(Y*(Y – 1))/2
    • 现在,使用变量j迭代整数X的除数,并将res增加mp[j]
  • 完成上述步骤后,打印res的值作为得到的总数。

下面是上述方法的实现:

C++

// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to count pairs from an
// array having GCD equal to
// minimum element of that pair
int CountPairs(int arr[], int N)
{
    // Stores the resultant count
    int res = 0;
 
    // Stores the frequency of
    // each array element
    map mp;
 
    // Traverse the array arr[]
    for (int i = 0; i < N; i++) {
        mp[arr[i]]++;
    }
    // Iterate over the Map mp
    for (auto p : mp) {
 
        // Stores the array element
        int x = p.first;
 
        // Stores the count
        // of array element x
        int y = p.second;
 
        // If x is 1
        if (x == 1) {
 
            // Increment res by N-1
            res += N - 1;
            continue;
        }
 
        // Increment res by yC2
        res += (y * (y - 1)) / 2;
 
        // Iterate over the
        // range [2, sqrt(x)]
        for (int j = 2;
             j <= sqrt(x); j++) {
 
            // If x is divisble by j
            if (x % j == 0) {
 
                // Increment the value
                // of res by mp[j]
                res += mp[j];
 
                // If j is not equal to x/j
                if (j != x / j)
 
                    // Increment res
                    // by mp[x/j]
                    res += mp[x / j];
            }
        }
    }
 
    // Return the resultant count
    return res;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 3, 1, 2 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << CountPairs(arr, N);
 
    return 0;
}

Java

// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG {
   
      // Function to count pairs from an
    // array having GCD equal to
    // minimum element of that pair
    static int CountPairs(int arr[], int N)
    {
       
        // Stores the resultant count
        int res = 0;
 
        // Stores the frequency of
        // each array element
        Map mp = new HashMap<>();
 
        // Traverse the array arr[]
        for (int i = 0; i < N; i++) {
              Integer c = mp.get(arr[i]);
            mp.put(arr[i], (c == null) ? 1 : c + 1);
        }
        // Iterate over the Map mp
          Iterator> itr = mp.entrySet().iterator();
          
        while(itr.hasNext())
        {
             Map.Entry entry = itr.next();
          
            // Stores the array element
            int x = (int)entry.getKey();
 
            // Stores the count
            // of array element x
            int y = (int)entry.getValue();
 
            // If x is 1
            if (x == 1) {
 
                // Increment res by N-1
                res += N - 1;
                continue;
            }
 
            // Increment res by yC2
            res += (y * (y - 1)) / 2;
 
            // Iterate over the
            // range [2, sqrt(x)]
            for (int j = 2; j <= Math.sqrt(x); j++) {
 
                // If x is divisble by j
                if (x % j == 0) {
 
                    // Increment the value
                    // of res by mp[j]
                    res += mp.get(j);
 
                    // If j is not equal to x/j
                    if (j != x / j)
 
                        // Increment res
                        // by mp[x/j]
                        res += mp.get((int)x / j);
                }
            }
        }
 
        // Return the resultant count
        return res;
    }
 
    // Driver Code
    public static void main (String[] args) {
        int arr[] = { 2, 3, 1, 2 };
        int N = arr.length;
        System.out.println(CountPairs(arr, N));
    }
}
 
// This code is contributed by Dharanendra L V.

蟒蛇3

# Python3 program for the above approach
from math import sqrt
 
# Function to count pairs from an
# array having GCD equal to
# minimum element of that pair
def CountPairs(arr, N):
     
    # Stores the resultant count
    res = 0
 
    # Stores the frequency of
    # each array element
    mp = {}
 
    # Traverse the array arr[]
    for i in range(N):
        if (arr[i] in mp):
            mp[arr[i]] += 1
        else:
            mp[arr[i]] = 1
             
    # Iterate over the Map mp
    for key, value in mp.items():
         
        # Stores the array element
        x = key
 
        # Stores the count
        # of array element x
        y = value
 
        # If x is 1
        if (x == 1):
 
            # Increment res by N-1
            res += N - 1
            continue
 
        # Increment res by yC2
        res += (y * (y - 1)) // 2
 
        # Iterate over the
        # range [2, sqrt(x)]
        for j in range(2, int(sqrt(x)) + 1, 1):
 
            # If x is divisble by j
            if (x % j == 0):
 
                # Increment the value
                # of res by mp[j]
                res += mp[j]
 
                # If j is not equal to x/j
                if (j != x // j):
 
                    # Increment res
                    # by mp[x/j]
                    res += mp[x // j]
 
    # Return the resultant count
    return res
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 2, 3, 1, 2 ]
    N = len(arr)
     
    print(CountPairs(arr, N))
 
# This code is contributed by SURENDRA_GANGWAR

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to count pairs from an
// array having GCD equal to
// minimum element of that pair
static int CountPairs(int []arr, int N)
{
     
    // Stores the resultant count
    int res = 0;
 
    // Stores the frequency of
    // each array element
    Dictionary mp = new Dictionary();
 
    // Traverse the array arr[]
    for(int i = 0; i < N; i++)
    {
        if (mp.ContainsKey(arr[i]))
            mp[arr[i]]++;
        else
            mp.Add(arr[i], 1);
    }
     
    // Iterate over the Map mp
    foreach(KeyValuePair kvp in mp)
    {
 
        // Stores the array element
        int x = kvp.Key;
 
        // Stores the count
        // of array element x
        int y = kvp.Value;
 
        // If x is 1
        if (x == 1)
        {
             
            // Increment res by N-1
            res += N - 1;
            continue;
        }
 
        // Increment res by yC2
        res += (y * (y - 1)) / 2;
 
        // Iterate over the
        // range [2, sqrt(x)]
        for(int j = 2;
                j <= Math.Sqrt(x); j++)
        {
 
            // If x is divisble by j
            if (x % j == 0)
            {
 
                // Increment the value
                // of res by mp[j]
                res += mp[j];
 
                // If j is not equal to x/j
                if (j != x / j)
 
                    // Increment res
                    // by mp[x/j]
                    res += mp[x / j];
            }
        }
    }
 
    // Return the resultant count
    return res;
}
 
// Driver Code
public static void Main()
{
    int []arr = { 2, 3, 1, 2 };
    int N = arr.Length;
     
    Console.Write(CountPairs(arr, N));
}
}
 
// This code is contributed by bgangwar59

Javascript


输出:
4

时间复杂度: O(N*√M),其中 M 是数组的最大元素。
辅助空间: O(1)

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