试除法求约数算法总结

知识概览

  • 试除法求一个数的约数的时间复杂度是

例题展示

题目链接

活动 - AcWing 系统讲解常用算法与数据结构,给出相应代码模板,并会布置、讲解相应的基础算法题目。https://www.acwing.com/problem/content/871/

题解

用试除法求约数,总的时间复杂度是,也就是400万~500万之间。

代码

cpp 复制代码
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

vector<int> get_divisors(int n)
{
    vector<int> res;
    
    for (int i = 1; i <= n / i; i++)
        if (n % i == 0)
        {
            res.push_back(i);
            if (i != n / i) res.push_back(n / 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 t : res) cout << t << ' ';
        cout << endl;
    }
    return 0;
}

参考资料

  1. AcWing算法基础课
相关推荐
土司大王6 小时前
LeetCode hot100——两数之和
数据结构·算法·leetcode
luj_17686 小时前
大航海时代:沉浸式财商实战沙盒
c语言·开发语言·网络·经验分享·算法
Navigator_Z7 小时前
LeetCode //C - 1200. Minimum Absolute Difference
c语言·算法·leetcode
wabs6667 小时前
关于字符串【力扣344.反转字符串的思考】
数据结构·算法·leetcode
民乐团扒谱机8 小时前
【微实验】谐波乘积谱(HPS)算法深度解析:原理、数学与代码实现
开发语言·人工智能·python·算法·语音识别·音乐
Nil2088 小时前
leetcode 73矩阵置0
算法·leetcode·矩阵
忍冬k9 小时前
DeepSeek harness安装指南
java·开发语言·数据结构·c++·算法
何以解忧,唯有..9 小时前
预订酒店问题
算法
No8g攻城狮10 小时前
【算法】什么是 DFS 与 BFS 及他们的区别
算法·深度优先·宽度优先
旖旎夜光10 小时前
LeetCode 1658:将 x 减到 0 的最小操作数(滑动窗口) —— 题解
数据结构·c++·算法·leetcode·滑动窗口