c++ - "5"有什么问题?纸上的一切都很好

标签 c++ math

<分区>

这是我们应该用 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”在我的语言(波斯语)中的意思是“Even”)

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

Segmentation fault (core dumped)

退出代码是 139。我在使用 g++ 作为编译器的 ubuntu 12.04 上使用 Code::Blocks。

更新:程序崩溃 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 - 学习调试 - 我无法强调这是多么极其重要

关于c++ - "5"有什么问题?纸上的一切都很好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13971973/

相关文章:

C++ RFC3339 时间戳与毫秒使用 std::chrono

Java塔防导弹计算

ruby-on-rails - 在 Ruby on Rails 中除以百分比

c++ - C++错误LNK2019 : unresolved external symbol _main referenced in function _tmainCRTStartup

C++如何仅在一定时间内读取输入?我可以在用户不按回车键的情况下这样做吗?

c++ - free(): invalid pointer error in C++

math - 链式哈希表查找的预期最坏情况时间复杂度?

c++ - 使用 Lucas-Lehmer 迭代查找梅森数

algorithm - 什么函数伪随机地重新排序 N 个项目?

c++ - make 中的 GAlib247 错误