给定一个正整数的数组arr ,任务是为给定数组中的任何一对找到可能的最小GCD。
例子:
Input: arr[] = {1, 2, 3, 4, 5}
Output: 1
Explanation:
GCD(1, 2) = 1.
Input: arr[] = {2, 4, 6, 8, 3}
Output: 1
方法:
如果我们观察清楚,我们将注意到任何两个数字的最小GCD将是数组中所有元素的GCD。该观察结果背后的原因是,如果在该对中存在使整个阵列的GCD最小化的元素,则任何一对的GCD都会最小。
Illustration:
Let us consider an array arr[] = {2,4,6,8,3}.
GCD of the all array elements excluding 3 is 2. On considering 3, the gcd minimizes to 1.
GCD of all the possible pairs are:
gcd(2,4) = 2
gcd(2,6) = 2
gcd(2,8) = 2
gcd(2,3) = 1
gcd(4,6) = 2
gcd(4,8) = 4
gcd(4,3) = 1
gcd(6,3) = 3
gcd(6,8) = 2
gcd(8,3) = 1
Thus, the minimum gcd for any pair is equal to 1, which is equal to gcd of the array and only appears for the pairs which contain 3 in it.
下面的代码是上述方法的实现:
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)