试除法求约数算法总结

知识概览

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

例题展示

题目链接

活动 - 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算法基础课
相关推荐
开源Z10 分钟前
LeetCode 42 · 接雨水:从暴力到双指针的三步优化
算法·leetcode
旖-旎19 分钟前
《LeetCode 695 岛屿的最大面积 FloodFill DFS 解法》
c++·算法·力扣·深度优先遍历·floodfill
syagain_zsx1 小时前
STL 之 vector 讲练结合
c++·算法
MartinYeung52 小时前
[论文学习]DP2Unlearning:高效且具保证的大型语言模型遗忘框架(基于差分隐私的 LLM Unlearning 方法)
学习·算法·语言模型
Tian_Hang2 小时前
C++原型模式(Protype)
开发语言·c++·算法
bIo7lyA8v2 小时前
算法复杂度的渐进分析与实际运行时间的差异的技术8
算法
yuan199973 小时前
欧拉梁静力与屈曲计算的 MATLAB 实现(有限差分法 + 解析解)
开发语言·算法·matlab
Luhui Dev4 小时前
几何图,现在可以用 API 一句话生成
人工智能·数学·luhuidev
汉克老师4 小时前
GESP7级C++考试语法知识(二、指数函数(3、综合练习)
c++·算法·数学建模·指数函数·gesp7级·复利