如何在不导致堆栈溢出的情况下计算非常大的数字和很小的 HCF.我正在使用欧几里得算法

How to calculate HCF a very large number and a small number without causing stack overflow. I am using euclid algorithm

本文关键字:HCF 算法 几里 堆栈 栈溢出 情况下 数字 非常 计算      更新时间:2023-10-16

我正在使用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( 步骤,因此不会导致堆栈溢出

您也可以尝试启用优化:它应该允许将两个函数调用折叠为非递归版本(因为这是尾递归(。请注意,不确定它是否会提高速度。

请注意:小心负数,% 运算符对它们不起作用