coffeebeforecode

kgcd-try1

May 16th, 2021
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.90 KB | None | 0 0
  1. /*
  2. // Sample code to perform I/O:
  3.  
  4. cin >> name;                            // Reading input from STDIN
  5. cout << "Hi, " << name << ".\n";        // Writing output to STDOUT
  6.  
  7. // Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
  8. */
  9.  
  10. // Write your code here
  11. #include <bits/stdc++.h>
  12. #define ll long long int
  13. using namespace std;
  14.  
  15. ll kgcd(ll a, ll b, map<string, ll> &memo);
  16. ll gcd(ll a, ll b, map<string, ll> &memo);
  17.  
  18. int main(){
  19.     int t;
  20.     scanf("%d", &t);
  21.     //cin >> t;
  22.     //t = 1;
  23.     map<string, ll> memo_gcd;
  24.     map<string, ll> memo_kgcd;
  25.     for(int j = 1; j <= t; j++){
  26.         ll n, count=0;
  27.         ll a, b;
  28.         scanf("%lld", &n);
  29.         //cin >> n;
  30.         //n = 4;
  31.        
  32.         for(a = 1; a <= n; a++){
  33.             for(b = 1; b <= n; b++){
  34.                 //cout << "kgcd(" << a << ", " << b << ") : " << kgcd(a,b) << " | ";
  35.                 //cout << "gcd(" << a << ", " << b << ") : " << gcd(a,b, memo) << endl;
  36.                 if (kgcd(a,b, memo_kgcd) == gcd(a,b, memo_gcd)){
  37.                     count++;
  38.                 }
  39.             }
  40.         }
  41.         //cout << count;
  42.         printf("%lld\n", count);
  43.         /*
  44.         if (j!=t){
  45.             cout << endl;
  46.         }
  47.         */
  48.     }
  49.     return 0;
  50. }
  51.  
  52. ll kgcd(ll a, ll b, map<string, ll> &memo)
  53. {
  54.     string p = to_string(a) + "," + to_string(b);
  55.     if (memo.find(p) != memo.end()){
  56.         return memo[p];
  57.     }
  58.    
  59.     while (a > 0 && b > 0)
  60.     {
  61.         a -= b;
  62.         swap(a , b);
  63.     }
  64.     return a + b;
  65. }
  66.  
  67. ll gcd(ll a, ll b, map<string, ll> &memo){
  68.     if (a > b){
  69.         swap(a, b);
  70.     }
  71.     //pair<ll,ll> p = make_pair(a,b);
  72.     string p = to_string(a) + "," + to_string(b);
  73.     if (memo.find(p) != memo.end()){
  74.         return memo[p];
  75.     }
  76.     while(b){
  77.         a %= b;
  78.         swap(a, b);
  79.     }
  80.     memo[p] = a;
  81.     return a;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment