📜  查找数组中所有对的最小GCD

📅  最后修改于: 2021-05-18 00:17:07             🧑  作者: Mango

给定一个正整数的数组arr ,任务是为给定数组中的任何一对找到可能的最小GCD。
例子:

方法:
如果我们观察清楚,我们将注意到任何两个数字的最小GCD将是数组中所有元素的GCD。该观察结果背后的原因是,如果在该对中存在使整个阵列的GCD最小化的元素,则任何一对的GCD都会最小。

下面的代码是上述方法的实现:

C++
// C++ program to find the
// minimum GCD of any pair
// in the array
#include 
using namespace std;
 
// Function returns the
// Minimum GCD of any pair
int MinimumGCD(int arr[], int n)
{
    int g = 0;
 
    // Finding GCD of all the
    // elements in the array.
    for (int i = 0; i < n; i++) {
        g = __gcd(g, arr[i]);
    }
    return g;
}
 
// Driver code
int main()
{
    int arr[] = { 2, 4, 6, 8, 3 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    cout << MinimumGCD(arr, N) << endl;
}


Java
// Java program to find the
// minimum GCD of any pair
// in the array
import java.util.*;
 
class GFG{
     
static int __gcd(int a, int b)
{
    if(b == 0)
        return a;
    else
        return __gcd(b, a % b);
}
 
// Function returns the
// minimum GCD of any pair
static int MinimumGCD(int arr[], int n)
{
    int g = 0;
 
    // Finding GCD of all the
    // elements in the array.
    for(int i = 0; i < n; i++)
    {
       g = __gcd(g, arr[i]);
    }
     
    return g;
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 2, 4, 6, 8, 3 };
    int N = arr.length;
 
    System.out.println(MinimumGCD(arr, N));
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program to find the
# minimum GCD of any pair
# in the array
 
from math import gcd
 
# Function returns the
# Minimum GCD of any pair
def MinimumGCD(arr, n):
    g = 0
 
    # Finding GCD of all the
    # elements in the array.
    for i in range(n):
        g = gcd(g, arr[i])
    return g
 
# Driver code
if __name__ == '__main__':
     
    arr = [ 2, 4, 6, 8, 3 ]
 
    N = len(arr)
    print(MinimumGCD(arr, N))
 
# This code is contributed by Samarth


C#
// C# program to find the
// minimum GCD of any pair
// in the array
using System;
 
class GFG{
     
static int __gcd(int a, int b)
{
    if(b == 0)
        return a;
    else
        return __gcd(b, a % b);
}
 
// Function returns the
// minimum GCD of any pair
static int MinimumGCD(int []arr, int n)
{
    int g = 0;
 
    // Finding GCD of all the
    // elements in the array.
    for(int i = 0; i < n; i++)
    {
       g = __gcd(g, arr[i]);
    }
     
    return g;
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = { 2, 4, 6, 8, 3 };
    int N = arr.Length;
 
    Console.WriteLine(MinimumGCD(arr, N));
}
}
 
// This code is contributed by sapnasingh4991


输出:
1

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