给定 n 个正整数 ai,对于每个整数 ai,请你按照从小到大的顺序输出它的所有约数。
输入格式
第一行包含整数 n。
接下来 n 行,每行包含一个整数 ai。
输出格式
输出共 n 行,其中第 i 行输出第 i 个整数 ai的所有约数。
数据范围
1≤n≤100
2≤ai≤2×109输入样例:
2 6 8
输出样例:
1 2 3 6 1 2 4 8
时间复杂度O(根号n)。试除法求约数,进行了一个优化,因为约数是成对出现的,所以我们每次只枚举小的那个。不过要注意判断一下边界情况就是当i和x/i 是同一个数的时候,只需要放入一个就可以了。最后sort排序一下输出。🍣
#include<bits/stdc++.h>
using namespace std;
const int N=1001;
vector<int> get(int x)//时间复杂度是根号下n
{
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(x);
for(auto t:res)cout<<t<<" ";
cout<<endl;
}
return 0;
}