# Find GCD of factorial of elements of given array in C++

C++Server Side ProgrammingProgramming

Suppose we have an array A, with N elements. We have to find the GCD of factorials of all elements of the array. Suppose the elements are {3, 4, 8, 6}, then the GCD of factorials is 6. Here we will see the trick. As the GCD of two numbers, is the greatest number, which divides both of the numbers, then GCD of factorial of two numbers is the value of factorial of the smallest number itself. So gcd of 3! and 5! is 3! = 6.

## Example

Live Demo

#include <iostream>
using namespace std;
long fact(int n){
if(n <= 1)
return 1;
return n * fact(n-1);
}
int gcd(int arr[], int n) {
int min = arr[0];
for (int i = 1; i < n; i++) {
if(min > arr[i])
min = arr[i];
}
return fact(min);
}
int main() {
int arr[] = {3, 4, 8, 6};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "GCD: "<< gcd(arr, n);
}

## Output

GCD: 6
Published on 21-Oct-2019 11:07:29
Advertisements