如何在不导致堆栈溢出的情况下计算非常大的数字和很小的 HCF.我正在使用欧几里得算法
How to calculate HCF a very large number and a small number without causing stack overflow. I am using euclid algorithm
我正在使用Euclid算法,但由于堆栈溢出而导致运行时错误。 我无法计算非常大和小的HCF
我相信你正在编写这样的函数:
int hcf(int a, int b){
if (a == 0){
return b;
}
else if (b == 0){
return a;
}
else if (a > b){
return hcf(b, a - b); // this is subtraction
}
else if (a < b){
return hcf(a, a - b); // this is subtraction
}
}
。你用类似的东西来称呼它
int q = hcf(100000000, 1);
井。。。如果没有优化,将创建10 亿次递归调用。可以肯定的是,您的程序将耗尽堆栈容量。
我个人首选的解决方案是放弃递归方法并使用迭代方法。然后可以将代码简化为单个循环:
int hcf(int a, int b){
while(a != 0 && b != 0){
if (a > b){
a = a - b;
}
else{
b = b - a;
}
}
if (a == 0){
return b;
}
else{
return a;
}
}
如果您坚持使用递归方法,请将减法替换为模数。
else if (a > b){
-> return hcf(b, a % b); // this is modulus
}
else if (a < b){
-> return hcf(a, a % b); // this is modulus
}
正确实现的算法应在大多数log(数字(步骤中使用,因此不会导致堆栈溢出。我想你使用以下算法:
gcd(a, 0) = a
gcd(a, b) = gcd(a-b, b)
在C++中看起来像这样:
int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(std::max(a, b) - std::min(a, b), std::min(a, b));
}
}
这不是最佳的。相反,您应该使用以下关系
gcd(a, 0) = a
gcd(a, b) = gcd(b, a mod b)
在C++中看起来像这样:
int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
此代码实际上只执行 log(ab( 步骤,因此不会导致堆栈溢出
您也可以尝试启用优化:它应该允许将两个函数调用折叠为非递归版本(因为这是尾递归(。请注意,不确定它是否会提高速度。
请注意:小心负数,% 运算符对它们不起作用
相关文章:
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 基于ELO的团队匹配算法
- C++选择排序算法中的逻辑错误
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- C++A*算法并不总是在路径中具有目标节点
- 排序算法c++
- 构建可组合有向图(扫描仪生成器的汤普森构造算法)
- 算法问题:查找从堆栈中弹出的所有序列
- 下面是排序算法O(n)吗
- KMP算法和LPS表构造的运行时间
- 为什么我的排序算法会更改数组值
- 求最大元素位置的分治算法
- 具有非整数边容量的最大流量的Dinic算法
- 到连接组件算法的问题(递归)
- STL算法函数在多个一维容器上的使用
- 读取最后一行代码算法 - c++ 时出现问题
- 括号更改 O(n) 算法
- std::unordered_map 搜索算法是如何实现的?
- 如何实现高效的算法来计算大型数据集的多个不同值?
- 如何在不导致堆栈溢出的情况下计算非常大的数字和很小的 HCF.我正在使用欧几里得算法