math - Why is this Ruby code far faster than the equivalent C++ code? -
recently i've been going through easy project euler problems , solving them in ruby , c++. problem 14 concerning collatz conjecture, c++ code went on half hour before terminated it, though when translated code ruby, solved in 9 seconds.
that difference quite unbelievable me - had been led believe c++ faster ruby, mathematical process.
my code follows.
c++:
#include <iostream> using namespace std; int main () { int = 2; int b = 2; int c = 0; while (b < 1000000) { = b; int d = 2; while (a != 4) { if (a % 2 == 0) /= 2; else = 3*a + 1; d++; } if (d > c) { cout << b << ' ' << d << endl; c=d; } b++; } cout << c; return 0; }
run time - don't know, it's really long time.
and ruby:
#!/usr/bin/ruby -w = 0 b = 2 c = 0 while b < 1000000 = b; d = 2 while != 4 if % 2 == 0 /= 2 else = 3*a + 1 end d+=1 end if d > c p b,d c=d end b+=1 end p c
run time - approximately 9 seconds.
any idea what's going on here?
p.s. c++ code runs deal faster ruby code until hits 100,000.
you're overflowing int
, it's not terminating. use int64_t
instead of int
in c++ code. you'll need include stdint.h
that..
Comments
Post a Comment