
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Advertisements