lua-users home
lua-l archive

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


Hi!

For a presentation of lua for mathematicians I tried to come up with a
is_prime function.

This is what I got:

local function is_prime()
  local primes = { [2] = true, [3] = true }
  local max_prime = 3
  local floor = math.floor
  function add_primes()
    local t = {} -- list of candidates
    local N = max_prime * 2 + 1
    for i = max_prime + 2, N, 2 do
      t[ i ] = true
    end
    -- sieve candidates
    for x, _ in pairs( primes ) do
      for i = floor( max_prime / x ) * x, N, x do
        t[ i ] = nil
      end
    end
    -- append primes
    for x, _ in pairs( t ) do
      primes[ x ] = true
    end
    max_prime = table.maxn( t )
  end
  return function( n )
    while n > max_prime do
      add_primes()
    end
    return primes[ n ] == true
  end
end
is_prime = is_prime()

Now, if you like to tiker around with such things for recreational
purposes (like me), please comment. The result should be

* easy to understand
* concise
* performant

Regards,
Matthias