Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

In phần tử mảng chia hết cho ít nhất một phần tử khác C++

Cho mảng số nguyên. In các phần tử chia hết cho ít nhất một phần tử khác trong mảng. Ví dụ: [3,12,16,21] → 12,21 (12 chia hết 3, 21 chia hết 3).

Sieve + Hash

Đưa tất cả phần tử vào unordered_set. Tìm max. Với mỗi phần tử x, duyệt các bội 2x, 3x... ≤ max. Nếu bội có trong set → bội đó chia hết cho x. Lưu kết quả.

Ví dụ minh họa

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

void printDivisible(int arr[], int n) {
    unordered_set s;
    int mx = INT_MIN;
    for (int i=0; i divisible;
    for (int i=0; i freq;
    for (int i=0; i ans;
    for (auto& p : freq) {
        if (p.second >= 2) {
            if (!divisible.count(p.first))
                while (p.second--) ans.push_back(p.first);
        }
        if (divisible.count(p.first))
            while (p.second--) ans.push_back(p.first);
    }
    
    for (int x : ans) cout << x << '\t';
}

int main() {
    int arr[] = {2, 4, 7, 12, 14};
    int n = sizeof(arr)/sizeof(arr[0]);
    printDivisible(arr, n);
    return 0;
}

Kết quả

12 14 4