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?- A. 42 10584
- B. 42 252
- C. 21 252
- 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
- Problem: Count trailing zeros of n! (number of factors 5). python def tz(n): c = 0 while n: n //= 5; c += n return c print(tz(25)…
- Problem: Reverse the digits of a 32-bit signed integer, returning 0 if the result overflows. python def rev(x): s = -1 if x < 0 else 1 r =…
- Problem: Find the integer x (0 ≤ x < m) such that 3x ≡ 1 (mod 11) using the extended Euclidean algorithm. python def ext(a, b): if b == 0…
- Problem: Return the excel-style column title for a column number (1 → A, 26 → Z, 27 → AA). python def title(n): s = '' while n: n -= 1 s =…
- Problem: Return the number formed by the most significant digit of the sum of digits repeatedly added until one digit remains (digital…
- Problem: Count pairs (i < j) with a[i] > a[j] (inversions) in an array of n = 2 × 10⁵ values. Which approach runs within a 1-second limit?