
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- Construct an array from XOR of all elements of array except element at same index in C++
- JavaScript construct an array with elements repeating from a string
- Construct sum-array with sum of elements in given range in C++
- How do I recursively remove consecutive duplicate elements from an array?
- Consecutive elements sum array in JavaScript
- Absolute Difference of all pairwise consecutive elements in an array (C++)?
- Find elements of array using XOR of consecutive elements in C++
- Return an array formed from the elements of a masked array at the given indices in NumPy
- Return the sum of two consecutive elements from the original array in JavaScript
- Python Pandas - Construct an IntervalArray from an array of splits
- Check if three consecutive elements in an array is identical in JavaScript
- Maximum sum of n consecutive elements of array in JavaScript
- Rearrange an array to minimize sum of product of consecutive pair elements in C++
- Removing consecutive duplicates from strings in an array using JavaScript
- Check if array elements are consecutive in Python

Advertisements