To optimize your code, we'll implement an efficient algorithm that avoids computing the GCD of every possible pair explicitly, which would be an O(n²) operation and inefficient for large inputs.
We'll use a frequency-based approach combined with the inclusion-exclusion principle to compute the frequency of each possible GCD among all pairs. This method reduces the time complexity significantly.
Here's the optimized code with explanations:
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
vector<int> gcdValues(vector<int>& nums, vector<long long>& queries) {
int n = nums.size();
int max_num = *max_element(nums.begin(), nums.end());
vector<int> cnt(max_num + 1, 0);
vector<long long> m(max_num + 1, 0);
vector<long long> freq(max_num + 1, 0);
// Step 1: Count frequency of each number in nums
for (int num : nums) {
cnt[num]++;
}
// Step 2: Compute m[g], the count of numbers divisible by g
for (int g = 1; g <= max_num; ++g) {
for (int multiple = g; multiple <= max_num; multiple += g) {
m[g] += cnt[multiple];
}
}
// Step 3: Use inclusion-exclusion principle to compute freq[g]
for (int g = max_num; g >= 1; --g) {
// Total pairs where both numbers are divisible by g
freq[g] = m[g] * (m[g] - 1) / 2;
// Subtract pairs counted with greater GCDs
for (int multiple = 2 * g; multiple <= max_num; multiple += g) {
freq[g] -= freq[multiple];
}
}
// Step 4: Build a list of GCD values with cumulative frequencies
vector<pair<long long, int>> gcd_freq_list;
long long cumulative_frequency = 0;
for (int g = 1; g <= max_num; ++g) {
if (freq[g] > 0) {
cumulative_frequency += freq[g];
gcd_freq_list.emplace_back(cumulative_frequency, g);
}
}
// Step 5: Answer queries using binary search
vector<int> result;
for (long long q : queries) {
auto it = lower_bound(gcd_freq_list.begin(), gcd_freq_list.end(), make_pair(q + 1, 0LL));
if (it != gcd_freq_list.end()) {
result.push_back(it->second);
} else {
// If query index is out of range, handle accordingly (e.g., return -1)
result.push_back(-1);
}
}
return result;
}
Explanation:
Advantages of the Optimized Code:
-
Time Complexity:
- The time complexity is reduced to approximately O(N log M + Q log M), where N is the number of elements in
nums, M is the maximum number in nums, and Q is the number of queries.
- This is significantly more efficient than the original O(N² log N) complexity.
-
Space Complexity:
- The space complexity is reasonable, utilizing arrays of size up to the maximum number in
nums.
This optimized approach effectively computes the required GCD values for the queries without the need to compute every possible pair explicitly, making it suitable for larger input sizes.