试除法求约数算法总结

知识概览

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

例题展示

题目链接

活动 - 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算法基础课
相关推荐
黑色的山岗在沉睡3 分钟前
LeetCode 494. 目标和
算法·leetcode·职场和发展
haoly19893 小时前
数据结构和算法篇-线性查找优化-移至开头策略
数据结构·算法·移至开头策略
学Linux的语莫6 小时前
机器学习数据处理
java·算法·机器学习
earthzhang20217 小时前
【1007】计算(a+b)×c的值
c语言·开发语言·数据结构·算法·青少年编程
小鱼_yu7 小时前
探索C#中LINQ的异步流处理使用`IAsyncEnumerable`提升数据查询效率
数学
2301_803554528 小时前
C++联合体(Union)详解:与结构体的区别、联系与深度解析
java·c++·算法
sali-tec9 小时前
C# 基于halcon的视觉工作流-章42-手动识别文本
开发语言·人工智能·算法·计算机视觉·c#·ocr
SandySY10 小时前
品三国谈人性
算法·架构
小欣加油10 小时前
leetcode 62 不同路径
c++·算法·leetcode·职场和发展
夏鹏今天学习了吗10 小时前
【LeetCode热题100(38/100)】翻转二叉树
算法·leetcode·职场和发展