Problem solution · C++

Sorted GCD Pair Queries

Sorted GCD Pair Queries: a C++ solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Direct simulation
Source
walkccc LeetCode Solutions
Length
57 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Direct simulation

For Sorted GCD Pair Queries, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. Return the accumulated state once all relevant input has been handled.

Code notes

  • 57 lines of C++ from the credited upstream file 3312.cpp.
  • The implementation visibly relies on sequence storage.
  • 7 loop blocks detected.

Complexity

Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeSorted GCD Pair Queries · C++C++
Use this to learn the idea, then write your own version.
class Solution { public:  vector<int> gcdValues(vector<int>& nums, vector<long long>& queries) {    const int maxNum = ranges::max(nums);    vector<int> ans;    // countDivisor[d] := the number of `nums` having `num % d == 0`    vector<int> countDivisor(maxNum + 1);    // countGcdPair[g] := the number of pairs having gcd == g    vector<long> countGcdPair(maxNum + 1);    // prefixCountGcdPair[g] := the number of pairs having gcd <= g    vector<long> prefixCountGcdPair{0};     for (const int num : nums)      for (int i = 1; i * i <= num; ++i)        if (num % i == 0) {          ++countDivisor[i];          if (i != num / i)            ++countDivisor[num / i];        }     for (int gcd = maxNum; gcd >= 1; --gcd) {      // There are C(countDivisor[gcd], 2) pairs that have a common divisor      // that's a multiple of `gcd` (including the one that equals to `gcd`).      // So, substract the multiples of `gcd` to have the number of pairs with a      // gcd that's exactly `gcd`.      countGcdPair[gcd] =          countDivisor[gcd] * static_cast<long>(countDivisor[gcd] - 1) / 2;      for (int largerGcd = 2 * gcd; largerGcd <= maxNum; largerGcd += gcd)        countGcdPair[gcd] -= countGcdPair[largerGcd];    }     for (int gcd = 1; gcd <= maxNum; ++gcd)      prefixCountGcdPair.push_back(prefixCountGcdPair.back() +                                   countGcdPair[gcd]);     for (const long query : queries)      ans.push_back(getNthGcdPair(query, prefixCountGcdPair));     return ans;  }  private:  // Returns the `query`-th gcd pair.  int getNthGcdPair(long query, const vector<long>& prefixCountGcdPair) {    int l = 1;    int r = prefixCountGcdPair.size() - 1;    while (l < r) {      const int m = (l + r) / 2;      if (prefixCountGcdPair[m] < query + 1)        l = m + 1;      else        r = m;    }    return l;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗