Tarango

GCD of All Pairs

Oct 26th, 2015
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.00 KB | None | 0 0
  1. /*
  2.     Suppose you are given a array of N integers. (1<=N,A[i]<=10^5).
  3.     Now you have to find all the GCD of all pairs of numbers you cane
  4.     make from the array.For example if the array is {7,18,20,35} Then
  5.     you can make the pairs (7,18),(7,20),(7,35),(18,20),(18,35)&(20,35).
  6.     Now take the GCD of that pairs 1,1,7,2,1,5.Now you have to print like
  7.     this: (1 = 3),(7 = 1),(2 = 1),(5 = 1).
  8.  
  9. */
  10. #include <bits/stdc++.h>
  11. using namespace std;
  12. #define Size 1000005
  13. #define Max 100005
  14.  
  15. long long GCD(long long A, long long b) {
  16.     if (b == 0) return A;
  17.     return GCD(b, A % b);
  18. }
  19.  
  20. long long N;
  21. long long A[Size];
  22. long long divs[Size];
  23. long long freq[Size];
  24. long long resGCD[Size]; //Stores the actual result,resGCD[i] = for how many different pairs i is GCD of them.
  25.  
  26. void find_GCD_Of_All_Pairs(){
  27.     //divs[i] = total numbers for which i is a divisor;
  28.     for (int i = 1; i <= A[N]; i++) {
  29.         for (int j = 1; j * i <= A[N]; j++){
  30.             divs[i] += freq[j * i];
  31.         }
  32.     }
  33.  
  34.     for (int K = A[N]; K >= 1; K--) {
  35.         //resGCD[K] = How many pairs are there for
  36.         //which K is a common divisor.The given
  37.         //formula calculate all possible pairs;
  38.         //Remember,K is common divisor of all those
  39.         //pairs but K might not be the GCD of all of them.
  40.         //So we are over calculating for some pairs;
  41.         resGCD[K] = (divs[K] * (divs[K] - 1)) / 2;
  42.  
  43.         //Now we need to remove those pairs who have
  44.         //a GCD value which is multiple of K
  45.         //Because there multiple(K*x) values are the GCDs for
  46.         //those pairs and we have already calculated them
  47.         //before.So we need to subtract them now.
  48.         //We are using inclusion exclusion principal here;
  49.         for (int j = 2; K * j <= A[N]; j++) {
  50.             resGCD[K] -= resGCD[K * j];
  51.         }
  52.     }
  53.     for (int i = 1; i <= A[N]; i++){
  54.         if (resGCD[i] != 0) {
  55.             printf("i%d = %lld\n",i,resGCD[i]);
  56.         }
  57.     }
  58. }
  59.  
  60. int main() {
  61.     cin >> N;
  62.     //freq[i] = number of occurrences of i in Array;
  63.     for (int i = 1; i <= N; i++) {
  64.         cin >> A[i];
  65.         freq[A[i]]++;
  66.     }
  67.     sort(A + 1, A + N + 1);
  68.     find_GCD_Of_All_Pairs();
  69.     return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment