QUESTION
Given an array of numbers, find GCD of the array elements.
“TESTCASE_1”: “5\n1 4 6 9 12\n###—###SEPERATOR—###—\n1”, “TESTCASE_2”: “6\n2 4 64 86 4 8\n###—###SEPERATOR—###—\n2”, “TESTCASE_3”: “10\n56 45 78 32 5 4 9 8 10 23\n###—###SEPERATOR—###—\n1”, “TESTCASE_4”: “6\n45 55 65 70 85 95\n###—###SEPERATOR—###—\n5”, “TESTCASE_5”: “0\n###—###SEPERATOR—###—\n0
ANSWER
#include <iostream>
using namespace std;
// Function to return gcd of a and b
int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
// Function to find gcd of array of
// numbers
int findGCD(int arr[], int n)
{
int result = arr[0];
for (int i=1; i<n; i++)
result = gcd(arr[i], result);
return result;
}
int main()
{
int n,arr[20];
cin>>n;
int i;
for(i=0;i<n;i++)
cin>>arr[i];
cout << findGCD(arr, n) << endl;
return 0;
}