Efficiently getting all divisors of a given number(有效地获得给定数字的所有除数)
问题描述
根据这个帖子,我们可以通过以下代码得到一个数的所有约数.
According to this post, we can get all divisors of a number through the following codes.
for (int i = 1; i <= num; ++i){
if (num % i == 0)
cout << i << endl;
}
例如24的除数是1 2 3 4 6 8 12 24.
搜索了一些相关的帖子,没有找到好的解决办法.有什么有效的方法可以做到这一点吗?
After searching some related posts, I did not find any good solutions. Is there any efficient way to accomplish this?
我的解决方案:
- 通过这个解决方案.
- 获取这些质因数的所有可能组合.
然而,这似乎不是一个好方法.
However, it doesn't seem to be a good one.
推荐答案
因素是成对的.1 and 24, 2 and 12, 3 and 8、4 和 6.
Factors are paired. 1 and 24, 2 and 12, 3 and 8, 4 and 6.
算法的改进可能是迭代到 num 的平方根,而不是一直到 num,然后使用 计算配对因子num/i.
An improvement of your algorithm could be to iterate to the square root of num instead of all the way to num, and then calculate the paired factors using num / i.
这篇关于有效地获得给定数字的所有除数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:有效地获得给定数字的所有除数
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
