Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code : 378QAQ and Mocha's Array

#include <bits/stdc++.h>
using namespace std;

bool solve(vector<int> &a) {
    int n = a.size();
    sort(a.begin(), a.end());

    // First candidate is the minimum element of the array.
    int f = a[0];

    vector<int> remain;
    for (int i = 0; i < n; i++) {
        if ((a[i] % f) != 0) {
            remain.push_back(a[i]);
        }
    }
    if (remain.empty()) {
        return true;
    }

    int s = remain[0];
    // The second candidate is the minimum of the residual set.
    for (int i = 0; i < (int)remain.size(); i++) {
        if ((remain[i] % s) != 0) {
            return false;
        }
    }

    return true;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int t;
    cin >> t;
    for (int zz = 0; zz < t; zz++) {
        int n;
        cin >> n;
        vector<int> a(n);
        for (int i = 0; i < n; i++) {
            cin >> a[i];
        }
        if (solve(a)) {
            cout << "Yes"
                 << "\n";
        } else {
            cout << "No"
                 << "\n";
        }
    }
    return 0;
}