fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. const int MAX_VAL = 1e6; // Maximum possible value of elements in the array
  6.  
  7. // Function to calculate sum of GCD over all pairs
  8. long long gcd_sum_over_pairs(const vector<int>& arr) {
  9. // Step 1: Create a frequency array
  10. vector<int> freq(MAX_VAL + 1, 0);
  11. for (int num : arr) {
  12. freq[num]++;
  13. }
  14.  
  15. long long result = 0;
  16.  
  17. // Step 2: For each gcd value `g`, calculate how many multiples of `g` exist
  18. for (int g = 1; g <= MAX_VAL; g++) {
  19. // Count multiples of g
  20. long long count_g = 0;
  21. for (int multiple = g; multiple <= MAX_VAL; multiple += g) {
  22. count_g += freq[multiple];
  23. }
  24.  
  25. // If there are at least 2 numbers with GCD `g`, calculate the number of pairs
  26. if (count_g >= 2) {
  27. long long pairs_g = count_g * (count_g - 1) / 2; // Combinatorial formula nC2
  28. result += g * pairs_g; // Add contribution of these pairs to the result
  29. }
  30. }
  31.  
  32. return result;
  33. }
  34.  
  35. int main() {
  36. int n;
  37. cin >> n;
  38. vector<int> arr;
  39. int x;
  40. for(int i = 0; i < n; ++i){
  41. cin >> x;
  42. arr.push_back(x);
  43. }
  44. cout << gcd_sum_over_pairs(arr) << endl;
  45.  
  46. return 0;
  47. }
  48.  
Success #stdin #stdout 0.02s 7012KB
stdin
6
8 2 1 5 10 15
stdout
36