
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
Minimum LCM and GCD Among All Possible Sub-Arrays in C++
Suppose we have an array arr of size N. it has N positive numbers. We have to find the minimum elements of all possible subarray. Suppose the array is {2, 66, 14, 521}, then minimum LCM is 2, and GCD is 1.
We will solve this problem using a greedy approach. If we decrease the number of elements, then LCM will be less, and if we increase the array size, GCD will be less. We need to find the smallest element from the array, which is a single element, which will be required LCM. For GCD, GCD will be GCD of all elements of the array.
Example
#include <iostream> #include <algorithm> using namespace std; int minimum_gcd(int arr[], int n) { int GCD = 0; for (int i = 0; i < n; i++) GCD = __gcd(GCD, arr[i]); return GCD; } int minimum_lcm(int arr[], int n) { int LCM = arr[0]; for (int i = 1; i < n; i++) LCM = min(LCM, arr[i]); return LCM; } int main() { int arr[] = { 2, 66, 14, 521 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "LCM: " << minimum_lcm(arr, n) << ", GCD: " << minimum_gcd(arr, n); }
Output
LCM: 2, GCD: 1
Advertisements