Beingamanforever

Hackerrank Easy GCD

Nov 12th, 2024
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.59 KB | None | 0 0
  1. /**
  2.  *    author:  compounding
  3.  *    created: 2024-11-12 22:06:32
  4.  **/
  5. #include <bits/stdc++.h>
  6. using namespace std;
  7. mt19937_64 RNG(chrono::steady_clock::now().time_since_epoch().count());
  8. #define NeedForSpeed                  \
  9.     ios_base::sync_with_stdio(false); \
  10.     cin.tie(NULL);                    \
  11.     cout.tie(NULL);
  12. #define int long long
  13. #define all(x) (x).begin(), (x).end()
  14. typedef vector<int> vi;
  15. typedef vector<bool> vb;
  16. typedef vector<vi> vvi;
  17. typedef vector<pair<int, int>> vpi;
  18. #define f first
  19. #define s second
  20. #define yes cout << "YES" << endl
  21. #define no cout << "NO" << endl
  22. #define endl "\n"
  23. const int mod = 1000000007;
  24. int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
  25. int smallprime(int n)
  26. {
  27.     for (int i = 2; i * i <= n; i++)
  28.     {
  29.         if (n % i == 0)
  30.         {
  31.             return i;
  32.         }
  33.     }
  34.     return n;
  35. }
  36. void solve()
  37. {
  38.     int n, k;
  39.     cin >> n >> k;
  40.     vi v(n);
  41.     int commongcd = 0;
  42.     for (int i = 0; i < n; i++)
  43.     {
  44.         cin >> v[i];
  45.         commongcd = gcd(commongcd, v[i]);
  46.     }
  47.     // now we want largest l such that l divides all and l <= k
  48.     // TODO: idea is that, we find the smallest prime number which divides the gcd, and try to get close to l
  49.     // we choose the smallest prime divisor of GCD to get as close as possible to k
  50.     int smallestprime = smallprime(commongcd);
  51.     int l = smallestprime * (k / smallestprime);
  52.     cout << l << endl;
  53.     return;
  54. }
  55.  
  56. signed main()
  57. {
  58.     NeedForSpeed;
  59.     int t = 1;
  60.     // cin >> t;
  61.     while (t--)
  62.     {
  63.         solve();
  64.     }
  65.     return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment