- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find GCD of factorial of elements of given array in C++
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
#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
- Related Articles
- Array with GCD of any of its subset belongs to the given array?
- Program to find sum of elements in a given array in C++
- Find the GCD of N Fibonacci Numbers with given Indices in C++
- C/C++ Program to find the sum of elements in a given array
- Maximum GCD from Given Product of Unknowns in C++
- Find elements of array using XOR of consecutive elements in C++
- Count number of elements between two given elements in array in C++
- Find the last digit when factorial of A divides factorial of B in C++
- Maximum GCD of N integers with given product in C++
- GCD of an array of numbers in java
- Find minimum possible size of array with given rules for removing elements in C++
- Construct an array from GCDs of consecutive elements in given array in C++
- Find sum of digits in factorial of a number in C++
- C program to find trailing zero in given factorial
- How to find the sum of all elements of a given array in JavaScript?

Advertisements