lua-users home
lua-l archive

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


Instead of Project Euler, you might want to look at Programming Praxis, which is similar but has more of an emphasis on programming and less of an emphasis on math (though there is some math content).

On Thu, Sep 16, 2010 at 4:08 PM, Victor Poughon <victor.poughon@gmail.com> wrote:
Hello !

This is my first post on this list, after lots of reading.

So i'm learning Lua. I find it great so far.
I'm trying to write code "thinking in Lua" not just "thinking in C, then translating to Lua".

So i'm going through Project Euler' problems. I recently solved this one :

http://projecteuler.net/index.php?section=problems&id=14

Using this code :

function mesure(n)
  local i = 0
  while n ~= 1 do
    if n % 2 == 0 then n = n / 2
    else n = 3*n + 1 end
    i = i + 1
  end
  return i
end

local begin = os.time()

local max = 0
local maxi = 0
for i = 1, arg[1] or 10 do
  local new = mesure(i)
  if new > max then
    max = new
    maxi = i
  end
end

io.write("Done. ", os.difftime(os.time(), begin), "s.\n")
io.write("i = ", maxi)

Also on pastebin here : http://pastebin.com/TDPeza7y

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 finishes about 6 times faster. 
Is this what one should expect from Lua ?

I'm also concerned about the style of my code. Is this making a good use of Lua ?
I don't get the reflex of using the beautiful things it provides yet, like the generic for, multiple assignments, function as prime values, etc.

How do you do that ? :D

Victor