[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Learning Lua
- From: Mike Pall <mikelu-1009@...>
- Date: Fri, 17 Sep 2010 00:19:02 +0200
Victor Poughon wrote:
> When running it until 1,000,000 it finishes in about 15 seconds. (I have a
> 1.83Ghz processor).
> I'm not really concerned about performance, and i'm sure there's a better
> algorithm for solving this problem. But an equivalent algorithm in
> C<http://pastebin.com/9MMzS4UA>finishes about 6 times faster.
> Is this what one should expect from Lua ?
It runs 8.5x faster with LuaJIT.
Obviously algorithmic improvements pay off a lot here. The
following code takes 60 milliseconds on my machine with LuaJIT:
local bit = require("bit")
local bnot, bor, band = bit.bnot, bit.bor, bit.band
local shl, shr = bit.lshift, bit.rshift
local N = tonumber(arg and arg[1]) or 1000000
local cache, m, n = { 1 }, 1, 1
for i=2,N do
local j = i
for len=1,1000000000 do
j = bor(band(shr(j,1), band(j,1)-1), band(shl(j,1)+j+1, bnot(band(j,1)-1)))
local x = cache[j]; if x then j = x+len; break end
end
cache[i] = j
if j > m then m, n = j, i end
end
io.write("Found ", n, " (chain length: ", m, ")\n")
--Mike