AcWing 869. 试除法求约数

题目传送门

#include <bits/stdc++.h>

using namespace std;

//求所有约数
vector<int> get_divisors(int x) {
    vector<int> res;
    for (int i = 1; i <= x / i; i++) // 枚举到sqrt即可
        if (x % i == 0) {
            res.push_back(i);
            if (i != x / i) res.push_back(x / i); // 如果 i==x/i 只存储一个,比如 5*5=25
        }
    sort(res.begin(), res.end()); //排序输出
    return res;
}

int main() {
    //读入优化
    ios::sync_with_stdio(false);
    int n;
    cin >> n;
    while (n--) {
        int x;
        cin >> x;
        vector<int> res = get_divisors(x);
        for (int c: res) cout << c << ' ';
        cout << endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/littlehb/p/15341372.html