为什么这个Ruby代码比同等的C++代码快得多?

eld*_*uth 20 c++ math

最近我经历了一些简单的项目Euler问题并用Ruby和C++解决它们.但是对于有关Collat​​z猜想的问题14,我的C++代码在我终止它之前持续了大约半个小时,但是当我将代码翻译成Ruby时,它在9秒内解决了它.

这种差异让我感到难以置信 - 我一直认为C++几乎总是比Ruby快,特别是对于数学过程.

我的代码如下.

C++:

#include <iostream>

using namespace std;

int main ()
{
    int a = 2;
    int b = 2;
    int c = 0;
    while (b < 1000000)
    {

        a = b;
        int d = 2;
        while (a != 4)
        {
            if (a % 2 == 0)
                a /= 2;
            else
                a = 3*a + 1;
            d++;
        }
        if (d > c)
        {
            cout << b << ' ' << d << endl;
            c=d;
        }
        b++;
    }
    cout << c;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

运行时间 - 老实说我不知道​​,但这真的是非常长的时间.

和Ruby:

#!/usr/bin/ruby -w

    a = 0
    b = 2
    c = 0
    while b < 1000000
        a = b;
        d = 2
        while a != 4
            if a % 2 == 0
                a /= 2
            else
                 a = 3*a + 1
            end
            d+=1
        end
        if d > c
            p b,d
            c=d
        end
        b+=1
    end
    p c
Run Code Online (Sandbox Code Playgroud)

运行时间 - 大约9秒.

知道这里发生了什么吗?

PS C++代码运行速度比Ruby代码快得多,直到它达到100,000.

hex*_*ist 33

你满溢int,所以它不会终止.使用int64_t而不是int在您的c ++代码中.你可能需要为此包括stdint.h..

  • 具体来说,`while(a!= 4)`将永远不会完成,当`a`足够大以溢出该循环中的数学时. (7认同)
  • 改善你的答案,解释他为什么会溢出int. (4认同)
  • 更具体地说,当b = 901118时,循环似乎达到了极限. (3认同)
  • buuuut,看起来像unsigned long做了伎俩,并在.539秒.我想我应该对数据类型做更多的研究. (2认同)