AcWing 869. 试除法求约数

给定 n 个正整数 ai,对于每个整数ai,请你按照从小到大的顺序输出它的所有约数。

输入格式

第一行包含整数 n。

接下来 n行,每行包含一个整数 ai。

输出格式

输出共 n 行,其中第 i 行输出第 i个整数 ai 的所有约数。

数据范围

1≤ n ≤100
2≤ ai ≤2×10^9

输入样例:

2
6
8

输出样例:

1 2 3 6 
1 2 4 8 

题解:本题采用试除法。

vector写法:

#include <bits/stdc++.h>
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define ll long long
#define endl '\n'
#define N  2000005
using namespace std;
const ll inf=0x3f3f3f3f;
const double ex=1e-7;
const ll mod=1e9+7;
ll gcd(ll a ,ll b){ return b ? gcd(b,a%b) : a ;}
int v[N],n;
bool st[N];
void solve()
{
    vector<int>v;
    cin >>n;
    //合数的约数是成对出现的,如i是n的约数,n/i也是x的约数
    for(int i=1;i<=n/i;i++)
    {
        if(n%i==0)
        {
            v.push_back(i);
            if(i!=n/i) v.push_back(n/i); //当n为完全平方数时会有重复约数,避免重复放入
        }
    }
    sort(v.begin(),v.end());
    for(auto x: v)
    {
        cout <<x<<" ";
    }
    cout <<endl;
}
int main()
{ios
    int t;
    cin >>t;
    while(t--)
    {
        solve();
    }
    return 0;
}

set写法:

#include <bits/stdc++.h>
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define ll long long
#define endl '\n'
#define N  2000005
using namespace std;
const ll inf=0x3f3f3f3f;
const double ex=1e-7;
const ll mod=1e9+7;
ll gcd(ll a ,ll b){ return b ? gcd(b,a%b) : a ;}
int v[N],n;
bool st[N];
void solve()
{
    set<int>v;
    cin >>n;
    for(int i=1;i<=n/i;i++)
    {
        if(n%i==0)
        {
            v.insert(i);
            v.insert(n/i);
        }
    }
    for(auto x: v)
    {
        cout <<x<<" ";
    }
    cout <<endl;
}
int main()
{ios
    int t;
    cin >>t;
    while(t--)
    {
        solve();
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值