

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 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 Questions & Answers
- Maximize the maximum among minimum of K consecutive sub-arrays in C++
- GCD and LCM of two numbers in Java
- Write a C# program to find GCD and LCM?
- Find any pair with given GCD and LCM in C++
- All possible odd length subarrays JavaScript
- All Possible Full Binary Trees in C++
- C++ Program to Find the GCD and LCM of n Numbers
- Find all possible coordinates of parallelogram in C++
- All possible permutations of N lists in Python
- Generating all possible permutations of array in JavaScript
- Rectangle with minimum possible difference between the length and the width in C++
- Python - Split list into all possible tuple pairs
- Print all possible words from phone digits in C++
- Count all possible paths between two vertices in C++
- Sum of XOR of all possible subsets in C++
Advertisements