
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 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
Advertisements