lua-users home
lua-l archive

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


Hi everyone! I was trying to implement the prime sieve by Xuedong Luo in the following article: https://dl.acm.org/doi/10.1145/62065.62072

There's my attempt (luo.lua):

--
local floor = math.floor
local sqrt = math.sqrt
function primesieve(N)
    local result = {2, 3}
    if N < 2 then return {} end
    if N < 3 then return {2} end
    if N < 4 then return {2, 3} end
    local c, k, t, q, M, S
    c = 0
    k = 1
    t = 2
    q = floor(sqrt(N)/3)
    M = N // 3
    S = {}
    local step = 2
    local first = 5
    while first <= N do
        S[#S+1] = first
        first = first + step
        step = step == 2 and 4 or 2
    end
    for i = 1, q, 1 do
        k = 3 - k
        c = c + 4*k*i
        j = c
        local ij = 2*i*(3-k)+1
        t = t + 4*k
        while j <= M do
            S[j] = 0
            j = j + ij
            ij = t - ij
        end
    end
    for _, v in next, S do
        if v > 0 then
            result[#result + 1] = v
        end
    end
    return result
end
--Just for testing
for i = 1, 100 do
    X = #primesieve(1000000)
end
--

My script takes 15~16 seconds to run, so I want to know if there's a better/faster way (or a better sieve) to code. I'm working with pure Lua solutions and I'm rather new to Lua and programming, so optimizing and co. are still alien to me. Sorry for the noobish question and thank you in advance.

Regards,

Jairo :)