Optimizing the inner loop that computes the gcd(g, i) for each element i in the array can significantly improve the performance of your algorithm, especially for large input sizes. The current implementation has a time complexity of (O(n^2)) in the worst case, which may not be efficient for large n.
To optimize this, you can leverage the Sieve of Eratosthenes and number theory concepts to reduce the time complexity of finding the minimum gcd(g, i) in each iteration. Here's how you can achieve this:
1. Understanding the Problem
Your goal is to find, in each iteration, the element i from the array a that minimizes gcd(g, i). The straightforward approach iterates through all elements of the array to find this minimum, resulting in (O(n)) time per iteration.
2. Leveraging Number Theory and Sieve
Instead of checking each element individually, you can:
-
Precompute Frequencies: Create a frequency array freq where freq[x] represents the number of times x appears in the array a.
-
Use Sieve to Count Multiples: For each possible divisor d, compute how many elements in a are divisible by d. This can be done efficiently using a sieve-like approach.
-
Iterate Over Divisors of g: Since gcd(g, i) must be a divisor of g, iterate over all divisors of g in increasing order. The smallest such divisor with a positive count in the sieve will give you the minimum gcd(g, i).
3. Implementing the Optimization
Here's a modified version of your code with the optimization applied:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
// Function to compute all divisors of a number in sorted order
vector<int> getDivisors(int x) {
vector<int> divisors;
for(int i =1; i*i <=x; ++i){
if(x % i ==0){
divisors.push_back(i);
if(x / i !=i){
divisors.push_back(x/i);
}
}
}
sort(divisors.begin(), divisors.end());
return divisors;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector<int> a(n);
// Assuming max value in a is <=1e6 for sieve
const int MAX = 1e6 +1;
vector<int> freq(MAX, 0);
for(int &x : a){
cin >> x;
freq[x]++;
}
sort(a.begin(), a.end());
// Precompute the count of multiples for each d
// Using sieve approach
vector<int> multiple_count(MAX, 0);
for(int d =1; d < MAX; ++d){
for(int multiple = d; multiple < MAX; multiple +=d){
multiple_count[d] += freq[multiple];
}
}
// Initialize
if(a.empty()){
cout << "0\n";
return 0;
}
// Initialize by taking the smallest element
int g = a[0];
int ans = a[0];
freq[a[0]]--;
multiple_count[a[0]]--; // Adjust the multiple count
vector<int> res = {a[0]};
// Iterate n-1 times
for(int i =1; i <n; ++i){
// Get all divisors of current g
vector<int> divisors = getDivisors(g);
int curr = INT32_MAX;
int chosen = -1;
// Iterate over divisors in sorted order
for(auto d : divisors){
if(multiple_count[d] >0){
if(d < curr){
// Find the smallest number with this gcd
// To get the actual number, iterate multiples of d
// Starting from d upwards
for(int multiple = d; multiple < MAX; multiple +=d){
if(freq[multiple] >0){
if(d < curr){
curr = d;
chosen = multiple;
break; // Found the smallest possible multiple for this d
}
}
}
}
if(curr == d){
break; // Found the smallest possible gcd
}
}
}
if(chosen == -1)
break;
ans += curr;
g = curr;
freq[chosen]--;
// Update multiple_count for chosen
for(int multiple = chosen; multiple < MAX; multiple += chosen){
multiple_count[chosen]--;
}
res.push_back(chosen);
}
// Output the results
// print(res); // Assuming a print function is defined
for(auto x : res) cout << x << ' ';
cout << '\n' << ans << '\n';
}
4. Explanation of the Optimized Code
-
Frequency Array (freq): Counts how many times each number appears in the input array a.
-
Sieve-like multiple_count Array:
- For each possible divisor
d, multiple_count[d] stores how many numbers in a are divisible by d.
- This is populated by iterating over each divisor and its multiples, similar to the Sieve of Eratosthenes.
-
Finding Divisors of g:
- The
getDivisors function computes all divisors of the current g in sorted order.
- Iterating over these divisors in increasing order ensures that the smallest possible
gcd(g, i) is found first.
-
Selecting the Optimal i:
- For each divisor
d of g, if multiple_count[d] > 0, there exists at least one number in a divisible by d.
- The first such
d encountered (smallest d) gives the minimum gcd(g, i).
- To find the actual number
i, iterate through the multiples of d and pick the smallest available one.
-
Updating Counts:
- After selecting
i = chosen, decrement its frequency in freq and update the multiple_count accordingly.
-
Time Complexity:
- Preprocessing: (O(n \cdot \log \text{MAX})) where
MAX is the maximum possible value in a.
- Each Iteration: (O(\sqrt{g})) to find all divisors of
g and then (O(\frac{\text{MAX}}{d})) in the worst case when searching for the smallest multiple.
- Overall, this approach is significantly faster than the naive (O(n^2)) approach, especially for large inputs.
5. Additional Optimizations
-
Limit MAX Appropriately: Ensure that MAX is set to the maximum value that a[i] can take to optimize space and time.
-
Early Termination: If the smallest possible gcd (1) is found, you can break early as you cannot find a smaller gcd.
-
Efficient Divisor Enumeration: The getDivisors function can be further optimized if necessary, but for most practical purposes, it's efficient enough.
6. Conclusion
By precomputing the frequency of multiples and iterating through the divisors of g, you can significantly reduce the number of computations needed to find the minimum gcd(g, i) in each iteration. This approach leverages fundamental number theory concepts and the sieve method to optimize the performance of your algorithm.