Sweet Snippet 系列之 埃拉托斯特尼(Eratosthenes)筛法

埃拉托斯特尼(Eratosthenes)筛法的简单实现

遴选素数的埃拉托斯特尼(Eratosthenes)筛法想必大家都不陌生,不熟悉的朋友可以看看wiki,在此简单列出一份代码实现(Lua)

function Eratosthenes(n)
    local is_prime = {}
    
    -- init is_prime map
    for i = 2, n do
        is_prime[i] = true
    end
    
    -- eratosthenes filter
    local beg_val = 2
    local end_val = math.floor(math.sqrt(n))
    
    for i = beg_val, end_val do
        if is_prime[i] then
            for j = i + i, n, i do
                is_prime[j] = false
            end
        end
    end
    
    -- get primes
    local primes = {}
    for i = 2, n do
        if is_prime[i] then
            table.insert(primes, i)
        end
    end
    
    return primes
end

简单测试一下:

print(#Eratosthenes(100)) // output 25

100 以内的素数是 25 个,有兴趣的朋友可以试试到底是哪 25 个~

发布了142 篇原创文章 · 获赞 146 · 访问量 25万+

猜你喜欢

转载自blog.csdn.net/tkokof1/article/details/94657032