
- 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
Construct an array from GCDs of consecutive elements in given array in C++
Suppose we have an array A[], with n elements. We have to find another array B[], whose size is n+1, such that GCD of B[i] and B[i + 1] is A[i]. If there are multiple solutions, then print one of them whose array sum is minimum. So if A = [1, 2, 3], then output will be [1, 2, 6, 3]
When A has only one element say K, then B = [K, K]. So the B[0] will be A[0]. Now consider we are done up to index i, so we have already processed index i, and calculated B[i + 1]. Now the GCD of B[i + 1] and B[i + 2] = A[i + 1], then the GCD of B[i + 2] and B[i + 3] = A[i + 2]. So B[i + 2] >= LCM of A[i + 1], A[i + 2]. As we want the minimum sum, then we want to get the minimum value of B[i + 2], so B[i + 2] – LCM of A[i + 2] and A[i + 3]
Example
#include <iostream> #include <algorithm> using namespace std; int getLCM(int a, int b) { return (a * b) / __gcd(a, b); } void gcdArray(int A[], int n) { cout << A[0] << " "; for (int i = 0; i < n - 1; i++) cout << getLCM(A[i], A[i + 1]) << " "; cout << A[n - 1]; } int main() { int A[] = { 1, 2, 3 }; int n = sizeof(A) / sizeof(A[0]); cout << "Constructed array: "; gcdArray(A, n); }
Output
Constructed array: 1 2 6 3
- Related Questions & Answers
- Construct an array from XOR of all elements of array except element at same index in C++
- Construct sum-array with sum of elements in given range in C++
- Absolute Difference of all pairwise consecutive elements in an array (C++)?
- JavaScript construct an array with elements repeating from a string
- Find elements of array using XOR of consecutive elements in C++
- How do I recursively remove consecutive duplicate elements from an array?
- Python Pandas - Construct an IntervalArray from an array of splits
- Consecutive elements sum array in JavaScript
- Rearrange an array to minimize sum of product of consecutive pair elements in C++
- Find original array from encrypted array (An array of sums of other elements) using C++.
- Python Pandas - Construct an IntervalArray from an array-like of tuples
- How to access elements from an array in C#?
- Construct a complete binary tree from given array in level order fashion in C++
- Maximum sum of n consecutive elements of array in JavaScript
- Return an array formed from the elements of a masked array at the given indices in NumPy
Advertisements