lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 9/17/2010 6:58 AM, Luiz Henrique de Figueiredo wrote:

local cache={}
function mesure(x)
	local y=cache[x]
	if y==nil then
		if x==1 then
			y=0
		elseif x%2==0 then
			y=1+mesure(x/2)
		else
			y=1+mesure(3*x+1)
		end
		cache[x]=y
	end
	return y
end


As a metamethod....

local mesure = setmetatable({0}, {
  __index = function(t,n)
    local y
    if n%2==0 then
      y=1+t[n/2]
    else
      y=1+t[3*n+1]
    end
    t[n]=y
    return y
  end})
for i=1,1000000 do
  length = mesure[i]
  -- etc.
end

--
- tom
telliamed@whoopdedo.org