60 lines
1.3 KiB
Markdown
60 lines
1.3 KiB
Markdown
##[$AcWing$ $869$. 试除法求约数](https://www.acwing.com/problem/content/description/871/)
|
||
|
||
### 一、题目描述
|
||
给定 $$ 个正整数 $a_i$,对于每个整数 $a_i$,请你按照从小到大的顺序输出它的所有约数。
|
||
|
||
**输入格式**
|
||
第一行包含整数 $n$。
|
||
|
||
接下来 $n$ 行,每行包含一个整数 $a_i$。
|
||
|
||
**输出格式**
|
||
输出共 $n$ 行,其中第 $i$ 行输出第 $i$ 个整数 $a_i$ 的所有约数。
|
||
|
||
**数据范围**
|
||
$1≤n≤100,1≤a_i≤2×10^9$
|
||
|
||
**输入样例:**
|
||
```cpp {.line-numbers}
|
||
2
|
||
6
|
||
8
|
||
```
|
||
**输出样例:**
|
||
```cpp {.line-numbers}
|
||
|
||
1 2 3 6
|
||
1 2 4 8
|
||
```
|
||
|
||
### 二、实现代码
|
||
```cpp {.line-numbers}
|
||
#include <bits/stdc++.h>
|
||
|
||
using namespace std;
|
||
|
||
vector<int> nums;
|
||
// 求所有约数
|
||
void get_divisors(int x) {
|
||
for (int i = 1; i <= x / i; i++) // 枚举到sqrt即可
|
||
if (x % i == 0) {
|
||
nums.push_back(i);
|
||
if (i != x / i) nums.push_back(x / i); // 如果 i==x/i 只存储一个,比如 5*5=25
|
||
}
|
||
sort(nums.begin(), nums.end()); // 排序输出
|
||
}
|
||
|
||
int main() {
|
||
int n;
|
||
cin >> n;
|
||
while (n--) {
|
||
int x;
|
||
cin >> x;
|
||
nums.clear();
|
||
get_divisors(x);
|
||
for (auto c : nums) printf("%d ", c);
|
||
puts("");
|
||
}
|
||
return 0;
|
||
}
|
||
``` |