3 ms·
I was bored and curious to know how the Collatz conjecture works. Then, I implemented it in Lua and JS and compared their performance to C and Haskell. It's no
by killercup 13y ago
I was bored and curious to know how the Collatz conjecture works.
Then, I implemented it in Lua and JS and compared their performance to C and Haskell. It's not meant to be a (good) benchmark. Here you go: https://gist.github.com/killercup/7718804 https://gist.github.com/killercup/7718804
tl;dr
Implementation | Time
-------------- | -----
clang 3.3 | 0.40s
luajit 2.0.2 | 0.86s
GHC 7.6.3 | 0.49s
Node 0.10.22 | 2.43s
- xdenser 13y agomy 2 cents to defend NodeJs 329 837799 naive 3.06 sec 329 837799 decompozed 3.03 sec 329 837799 memoized decompozed 0.52 sec The program https://gist.github.com/xdenser/7722083 https://gist.github.com/xdenser/7722083
- dbaupp 13y agoPresumably the Lua, c and Haskell programs would also be 6× faster if you use the memoised algorithm, so that's a pretty meaningless comparison.
- xdenser 13y agoOk this intArithm variant (w/o memoization) for NodeJS is 6 times faster (0.54 sec) comparing to naive function intArithm(){ var max_a0 = +process.argv[2], longest = 0, max_len = 0, a0,len, a,z; for(a0=1;a0<=max_a0;++a0){ a = a0; len = 0; while( a != 1){ len++; z = a >>> 1; a = (!(a&1))?z:(a+z+1); } if(len>max_len){ max_len = len; longest = a0; } } console.log(max_len,longest); } the problem was with division by 2 operation which is not integer in js. So replacing it with shift >>> makes the trick. Formula optimization gives additional 200 ms. And I doubt memoized c or lua variant will be 6 times faster than non-memoized. As it is not that linear.