GCD of Pairwise LCMs

You are given an array nums of n positive integers.

For every pair of indices (i, j) such that i < j, compute the LCM of nums[i] and nums[j].

Form a multiset containing all these pairwise LCM values.

Your task is to return the GCD of all values in this multiset.

Notes:

  • The multiset contains one value for every pair (i, j) where i < j.
  • Since n >= 2, there is always at least one pair.

Example 1:

Input: nums = [2, 6, 8]

Output: 2

Explanation:

The pairwise LCMs are:

  • lcm(2, 6) = 6
  • lcm(2, 8) = 8
  • lcm(6, 8) = 24

So the multiset is {6, 8, 24}.

The GCD of these values is 2.

Example 2:

Input: nums = [3, 9, 15, 30]

Output: 3

Explanation:

The pairwise LCMs are:

  • lcm(3, 9) = 9
  • lcm(3, 15) = 15
  • lcm(3, 30) = 30
  • lcm(9, 15) = 45
  • lcm(9, 30) = 90
  • lcm(15, 30) = 30

So the multiset is {9, 15, 30, 45, 90, 30}.

The GCD of all these values is 3.

Now Your Turn!

Pick the correct output for the given input

Input: nums = [4, 10, 20]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 2 <= n <= 100000
  • 1 <= nums[i] <= 200000

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
long long gcdOfLCMs(vector<long long>& a) {
// Your code goes here
}
};
Test Case

Input:

Nums