Junk

Junk Commit Details

Date:2018-11-26 12:02:53 (11 months 22 days ago)
Author:Nicola Fontana
Branch:master
Commit:6e14a2271251725782cc151f727f7687c144dacb
Parents: a15161a062ddfda58af270669242f6954f62345e
Message:primes: improve implementation

Changes:
Mlua/primes.lua (1 diff)

File differences

lua/primes.lua
11
22
33
4
45
5
6
7
8
9
10
611
7
8
12
13
14
15
16
17
18
19
20
921
10
11
12
22
23
24
25
1326
14
15
16
17
27
28
29
30
31
32
33
34
35
1836
19
2037
21
22
23
38
39
40
41
2442
25
43
44
45
46
#! /usr/bin/env lua
--- Prime numbers generator
--
-- Calculates the prime numbers by checking the modulo of the current
-- number against the previous prime numbers found
-- number against the previous prime numbers found.
--
-- The algorithm is quite efficient: on my machine the program is able
-- to crunch the first 10,000,000 numbers in less than 10 seconds with
-- PUC-Lua 5.3. With LuaJIT 2 it takes less than 1 second!
primes = {}
n = 1
-- For convenience the algorithm is implemented as an interator,
-- so it can be easily moved around or used interactively
function primes(max)
local tip = tonumber(max) or math.huge
local max_i = 0
local size = 0
local function check(factors, n)
if n >= tip then return end
n = n + 1
repeat
n = n + 1
prime = true
-- First of all, let's try to discard the obvious non-prime
for i = 1, max_i do
if n % factors[i] == 0 then return check(factors, n) end
end
for i, v in ipairs(primes) do
if n % v == 0 then
prime = false
break
-- Prime candidate: check against all valid factors
local max_factor = math.sqrt(n)
for i = max_i + 1, size do
local factor = factors[i]
if factor > max_factor then
break
end
max_i = i
if n % factor == 0 then return check(factors, n) end
end
end
if prime then
primes[#primes + 1] = n
print(n .. "\n")
-- Prime found: store it in the table
size = size + 1
factors[size] = n
return n
end
until false
return check, {}, 1
end
for n in primes(arg[1]) do print(n) end

Archive Download the corresponding diff file

Branches