# Construct an array from GCDs of consecutive elements in given array in C++

C++Server Side ProgrammingProgramming

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

Live Demo

#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
Published on 30-Dec-2019 10:07:54