Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: Find the GCD of all array elements and the LCM of a pair.

Problem: Find the GCD of all array elements and the LCM of a pair.
long long g(long long a, long long b) { return b == 0 ? a : g(b, a % b); }
// vector<long long> v = {84, 126, 210};
// long long G = 0; for (auto x : v) G = g(G, x);
// long long L = 84 / g(84, 126) * 126;
// cout << G << " " << L;
What is printed?
  1. A. 42 10584
  2. B. 42 252
  3. C. 21 252
  4. D. 14 252

Correct answer: B. 42 252

gcd(0, x) = x, so starting from G = 0 works. gcd(84, 126) = 42 and gcd(42, 210) = 42. lcm(84, 126) = 84 / 42 × 126 = 252; dividing before multiplying avoids overflow, and 84 × 126 = 10584 is just the product. Euclid runs in O(log min(a, b)).

More Coding Interview Problems questions

Exams that ask this topic