【试除法求约数】——数论 + 容器基础使用练习&&栈

题目描述:
在这里插入图片描述

解题思路1:

本题使用vector,巧妙之处是什么?
答:便于找到新的元素后插入

本题中用到的vector基本操作有哪些?
vector<int> res开一个变长数组res
res.push_back(x)在尾部加新元素x
sort(res.begin(), res.end()); vector的排序操作
for(auto x : res) 遍历vector数组

注意点:
for(int i = 1; i <= x/i; i++)
遍历的是较小的约数,如果较小的约数!=较大的约数
需要把x/i也加到res中

AC代码1 (vector)版:

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

vector<int> get_divisors(int x) //注意这里返回值的类型
{
    vector<int> res; //开了一个变长数组vector
    //便于找到新的满足元素后的插入操作
    for(int i = 1; i <= x/i; i++)
    {
        if(x % i == 0)
        {
            res.push_back(i);
            if(i != x/i) 
            //只枚举到x/i,如果较大的约数!=较小的约数,把较大的约数也插入到res中。
                res.push_back(x/i);
        }
    }
    sort(res.begin(), res.end()); //vector的排序操作
    return res;
}

int main(void)
{
    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;
}

解题思路2:

可以直接用set存,不会重复
for(auto &x : s)快于for(auto x : s)

AC代码2 (set)版:

#include <bits/stdc++.h>
using namespace std;

void get_divisors(int x)
{
    set<int> s;
    for (int i = 1; i <= x / i; i++)
        if (x % i == 0)
            s.insert(i), s.insert(x / i);

    for (auto &i : s)
        cout << i << ' ';
    cout << endl;
}

int main()
{
    int n;
    cin >> n;
    while (n--)
    {
        int x;
        cin >> x;
        get_divisors(x);
    }
    return 0;
}

AC代码3 (栈):

#include<iostream>
#include<stack>
using namespace std;

void solve(int n)
{
    stack<int> st;
    for(int i = 1;i <= n/i;i++)
    if(n % i == 0)
    {
        cout << i << " ";
        if(i != n/i) 
        	st.push(n/i);
    }
    while(st.size())
    {
        cout << st.top() << " ";
        st.pop();
    }
}

int main()
{
    int n;
    scanf("%d",&n);
    while(n--)
    {
        int x;
        cin >> x;
        solve(x); 
        puts("");
    }
    return 0;
}

祝大家天天快乐AC~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qing小星星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值