题目链接 :点击查看
题目描述 :
给定 n 个正整数 ai,对于每个整数 ai,请你按照从小到大的顺序输出它的所有约数。
输入输出格式 :
输入
第一行包含整数 n。
接下来 n 行,每行包含一个整数 ai。
输出
输出共 n 行,其中第 i 行输出第 i 个整数 ai 的所有约数。
输入输出样例 :
输入
2
6
8
输出
1 2 3 6
1 2 4 8
题目分析 :
与之前在求质数时用到的试除法相同,本题在get_divisors(int x)函数中,通过枚举从1到sqrt(x)的所有整数,并判断是否x % i == 0,若等式成立,则说明i是x的约数,要注意这里枚举的整数范围是从1到sqrt(x),而约数都是成对出现,若是x % i != i,我们再将x % i也储存到结果数组中。在此函数中我们用动态数组vector < int > res来对约数进行存储,在求完所有约数后,还要用sort对res进行排序。详见如下代码。
代码 :
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<vector>
using namespace std;
vector <int> get_divisors(int x) {
vector <int> res;
for (int i = 1; i <= x/i; i ++ ) {
if (x % i == 0) {
res.push_back(i);
if (i != x / i) res.push_back(x / 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 x : res) cout << x << ' ';
cout << endl;
}
return 0;
}
以下我们给出试探法求约数的模板
vector<int> get_divisors(int x)
{
vector<int> res;
for (int i = 1; i <= x / i; i ++ )
if (x % i == 0)
{
res.push_back(i);
if (i != x / i) res.push_back(x / i);
}
sort(res.begin(), res.end());
return res;
}