"5"怎么了?纸上一切都很好

What's wrong with "5"? Everything is just fine on the paper

本文关键字:很好 怎么了      更新时间:2023-10-16

这是我们应该用C 解决的问题:

GCD ( 2m , 2n )         =  2 * GCD( m , n )
GCD ( 2m , 2n+1 )       = GCD ( m , 2n+1 )
GCD ( 2m+1,  2n+1 ) = GCD ( n-m , 2m+1 )  (m<n)
GCD ( m , m )       = m

这是我写的功能:

int GCD(int n1, int n2)
{
    bool n1Zoj, n2Zoj;
    n1Zoj = (n1%2 == 0);
    n2Zoj = (n2%2 == 0);
    if(n1Zoj && n2Zoj)
        return 2 * GCD(n1/2, n2/2);
    if(n1Zoj && !n2Zoj)
        return GCD(n1/2, n2);
    if(!n1Zoj && !n2Zoj)
        return GCD((n2-n1)/2, n1);
    if(n1 == n2)
        return n1;
}

(*" zoj"表示我的语言(波斯语))

当我将5作为第二个参数传递时,程序崩溃并打印以下消息:

Segmentation fault (core dumped)

退出代码是139。我正在使用使用G 作为编译器的Ubuntu上的Code ::块。

更新:程序以5,10,15,20,25崩溃,...

更新:我认为函数的正确形式是:

int GCD(int n1, int n2)
{
    if (n1 > n2)
        std::swap(n1, n2);
    //std::cout<<"GCD is called with params: "<<n1<<" & "<<n2<<std::endl;
    bool n1Zoj, n2Zoj;
    n1Zoj = (n1%2 == 0);
    n2Zoj = (n2%2 == 0);
    if(n1 == n2)
        return n1;
    if(n1Zoj && n2Zoj)
        return 2 * GCD(n1/2, n2/2);
    if(n1Zoj && !n2Zoj)
        return GCD(n1/2, n2);
    if(!n1Zoj && n2Zoj)
        return GCD(n2/2, n1);
    if(!n1Zoj && !n2Zoj)
        return GCD((n2-n1)/2, n1);
}

(n1Zoj && n2Zoj)评估为true时,您该怎么办?您致电

return 2 * GCD(n1, n2);

使用调用函数>完全相同的参数,导致无限递归,吹出的堆栈和堆栈溢出(分割故障)。

protip-学会调试 - 我无法强调非常重要的这是如何。

相关文章: