- 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
Minimum LCM and GCD possible 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
- Related Articles
- Maximize the maximum among minimum of K consecutive sub-arrays in C++
- All Possible Full Binary Trees in C++
- Find all possible coordinates of parallelogram in C++
- Find any pair with given GCD and LCM in C++
- Write a C# program to find GCD and LCM?
- Rectangle with minimum possible difference between the length and the width in C++
- Maximum trace possible for any sub-matrix of the given matrix in C++
- Count all possible paths between two vertices in C++
- Print all possible words from phone digits in C++
- Sum of XOR of all possible subsets in C++
- GCD and LCM of two numbers in Java
- Minimum Possible value of |ai + aj – k| for given array and k in C++
- C++ program to find minimum possible difference of largest and smallest of crackers
- Count of sub-strings of length n possible from the given string in C++
- Find minimum possible digit sum after adding a number d in C++

Advertisements