Easy to understand | Prefix sums + Binary Search | [C++] | Clean code |
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time 
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nconst int N = 5e4+2;\nclass Solution {\npublic:\n    vector<int> gcdValues(vector<int>& nums, vector<long long>& queries) {\n        vector<long long>pre(N,0);\n        vector<long long>cnt(N,0);\n        vector<long long>pref(N,0);\n        int n = (int)nums.size();\n        for(auto &x : nums) {\n            pre[x]++;\n            cnt[x]++;\n        }\n        for(int i = 2 ; i < N ; i++) {          \n            for(int j = 2 * i ; j < N ; j += i) {\n                pre[i] += cnt[j];\n            }\n        }\n        long long total = 0;\n        for(int i = 2 ; i < N ; i++) {\n            pref[i] = (pre[i] * (pre[i]-1))/2LL;\n        }\n        for(int i = N-1 ; i >= 2 ; i--) {\n            for(int j = 2 * i ; j < N ; j += i) {\n                pref[i] -= pref[j];\n            }\n            total += pref[i];\n        }\n        long long all = (n *1LL* (n - 1))/2LL;\n        pref[1] = all - total;\n        for(int i = 1 ; i < N ; i++) {\n            pref[i] += pref[i-1];\n        }\n        vector<int>ans;\n        int mx = *max_element(nums.begin(),nums.end());\n        for(auto &x : queries) {\n            ++x;\n            int l = 0;\n            int r = mx;\n            while(r > l + 1) {\n                int m = (l+r) >> 1;\n                if(pref[m] >= x) {\n                    r = m;\n                }  else {\n                    l = m;\n                }\n            }\n            ans.push_back(r);\n        }\n        return ans;\n    }\n};\n```
['C++']