
试除法 复杂度 $ O(\sqrt{n})$
总体复杂度 $ 100 \times \sqrt{2^{31}} \approx 4.6 \times 10^{6} $
点击查看代码
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector<int> get_divisors(int n)
{
vector<int> res;
for (int i = 1; i <= n / i; i ++) {
if (n % i == 0) {
res.push_back(i);
if (i != n / i) res.push_back(n / i);
}
}
sort(res.begin(), res.end());
return res;
}
int main()
{
int n;
cin >> n;
while (n --) {
int x;
cin >> x;
auto res = get_divisors(x);
for (auto r : res) cout << r << ' ';
cout << endl;
}
return 0;
}
- 枚举 i 从 1 到 \(\sqrt{n}\) ,如果 x % i == 0,就把两个成对的约数都放到 res 中,需要特判:\(i^2 = n\) 时,只放入一个数;