给定正整数不同的数组arr [] ,任务是查找通过对数组的元素执行以下操作而获得的最终数字:
运算:取两个不相等的数字,并用它们之间的差替换较大的数字,直到所有数字相等为止。
例子:
Input: arr[] = {5, 2, 3}
Output: 1
5 – 3 = 2, arr[] = {2, 2, 3}
3 – 2 = 1, arr[] = {2, 2, 1}
2 – 1 = 1, arr[] = {2, 1, 1}
2 – 1 = 1, arr[] = {1, 1, 1}
Input: arr[] = {3, 9, 6, 36}
Output: 3
天真的方法:由于最终答案始终是不同的,因此可以对数组进行排序,然后用两个最大元素的差值替换最大的项,然后重复该过程,直到所有数字相等为止。
高效的方法:从欧几里得算法中得知, gcd(a,b)= gcd(a – b,b) 。这可以扩展为gcd(A 1 ,A 2 ,A 3 ,…,A n )= gcd(A 1 -A 2 ,A 2 ,A 3 ,…,A n ) 。
同样,假设在应用了给定的运算之后,最终获得的数字为K。因此,从扩展算法中,可以说gcd(A 1 ,A 2 ,A 3 ,…,A n )= gcd(K ,K,…,n次) 。由于gcd(K,K,…,n次)= K ,可以找到给定问题的解决方案
通过查找数组所有元素的gcd。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the final number
// obtained after performing the
// given operation
int finalNum(int arr[], int n)
{
// Find the gcd of the array elements
int result = 0;
for (int i = 0; i < n; i++) {
result = __gcd(result, arr[i]);
}
return result;
}
// Driver code
int main()
{
int arr[] = { 3, 9, 6, 36 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << finalNum(arr, n);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to return the final number
// obtained after performing the
// given operation
static int finalNum(int arr[], int n)
{
// Find the gcd of the array elements
int result = 0;
for (int i = 0; i < n; i++)
{
result = __gcd(result, arr[i]);
}
return result;
}
static int __gcd(int a, int b)
{
return b == 0? a:__gcd(b, a % b);
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 3, 9, 6, 36 };
int n = arr.length;
System.out.print(finalNum(arr, n));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 implementation of the approach
from math import gcd as __gcd
# Function to return the final number
# obtained after performing the
# given operation
def finalNum(arr, n):
# Find the gcd of the array elements
result = arr[0]
for i in arr:
result = __gcd(result, i)
return result
# Driver code
arr = [3, 9, 6, 36]
n = len(arr)
print(finalNum(arr, n))
# This code is contributed by Mohit Kumar
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the readonly number
// obtained after performing the
// given operation
static int finalNum(int []arr, int n)
{
// Find the gcd of the array elements
int result = 0;
for (int i = 0; i < n; i++)
{
result = __gcd(result, arr[i]);
}
return result;
}
static int __gcd(int a, int b)
{
return b == 0 ? a : __gcd(b, a % b);
}
// Driver code
public static void Main(String[] args)
{
int []arr = { 3, 9, 6, 36 };
int n = arr.Length;
Console.Write(finalNum(arr, n));
}
}
// This code is contributed by 29AjayKumar
输出:
3