-
Notifications
You must be signed in to change notification settings - Fork 0
/
primes.lua
373 lines (334 loc) · 9.23 KB
/
primes.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
#!/usr/bin/env lua
local usage = #{} and --[[ code visible to Julia
"""
Usage:
julia primes.lua n
Exit with error code 0 if n is prime, or error code 1 if n is not prime.
julia /primes.lua command args...
Command can be one of:
- help show this text
- factor n the prime factorization of n
- isprime n "true" or "false" if n is prime
- nextprime n the next prime, not less than n
- prevprime n the previous prime, not greater than n
- prime n the n-th prime
- radical n the radical of n
Multiple commands can be issued, Commands can use Unix style flags.
\$ lua primes.lua isprime 9 10 11 prime 3 4 5 factor 99
false
false
true
5
7
11
3^2 * 11
\$ lua primes.lua --isprime=3 --factor=441
5
3^2 * 7^2
"""
using Primes
function main()
fn = exit ∘ Int ∘ (!) ∘ Primes.isprime
for arg in ARGS
n = tryparse(Int, arg)
if !isnothing(n)
show(stdout, MIME("text/plain"), fn(n))
println()
elseif arg == "help"
println(usage)
else
fn = if arg == "prime"
Primes.prime
elseif arg == "factor"
Primes.factor
elseif arg == "isprime"
Primes.isprime
elseif arg == "nextprime"
Primes.nextprime
elseif arg == "prevprime"
Primes.prevprime
elseif arg == "prime"
Primes.prime
elseif arg == "primes"
Primes.primes
elseif arg == "radical"
Primes.radical
else
error("Unrecognised argument: $(arg)")
end
end
end
end
main()
#= code visible to Lua ]]
[=[
Usage:
./primes.lua n
Exit with error code 0 if n is prime, or error code 1 if n is not prime.
./primes.lua command args...
Command can be one of:
- help show this text
- factor n the prime factorization of n
- isprime n "true" or "false" if n is prime
- nextprime n the next prime, not less than n
- prevprime n the previous prime, not greater than n
- prime n the n-th prime
- radical n the radical of n
Multiple commands can be issued, Commands can use Unix style flags.
$ lua primes.lua isprime 9 10 11 prime 3 4 5 factor 99
false
false
true
5
7
11
3^2 * 11
$ lua primes.lua --isprime=3 --factor=441
5
3^2 * 7^2
]=]
local mt = {
__name = "Primes",
export = function(self, scope)
scope = scope or _G
for key, value in pairs(self) do
if key:byte() ~= 95 then
scope[key] = scope[key] or value
end
end
end
}
mt.__index = mt
local Primes = setmetatable({}, mt)
local raw = { 0x40b6894d325a65b7 }
---@param n integer
---@return integer, integer
local function index(n)
n = (n - 2) // 2
return n // 64 + 1, 1 << n % 64
end
---@param n integer
local function getindex(n)
if n > 2 and n % 2 == 1 then
local i, mask = index(n)
return raw[i] & mask ~= 0
else
return n == 2
end
end
---@param n integer
---@param value boolean
local function setindex(n, value)
if n > 2 and n % 2 == 1 then
local i, mask = index(n)
raw[i] = value and raw[i]| mask or raw[i] & ~mask
end
end
--- Adds all primes up to at least n to the cache.
---@param n integer
local function generateprimes(n)
local minlen = 1 + (n - 3) // 128
if minlen > #raw then
for _ = #raw + 1, minlen do
table.insert(raw, -1)
end
local maxval = minlen * 128 + 1
for p = 3, maxval, 2 do
if getindex(p) then
for c = p * p, maxval, p + p do
setindex(c, false)
end
end
end
end
end
---@param n integer
---@return boolean -- true if `n` is a prime number
---@nodiscard
function Primes.isprime(n)
n = assert(math.tointeger(n), "n must be an integer.")
local rootn = math.floor(math.sqrt(n))
generateprimes(rootn)
if index(n) <= #raw then
return getindex(n)
end
for prime in Primes.eachprime(rootn) do
if n % prime == 0 then
return false
end
end
return true
end
---@param hi integer
---@param i integer
---@return integer, integer
---@overload fun(hi: integer, i: integer)
local function nextprime(hi, i)
while i < hi do
i = i + 1
if Primes.isprime(i) then return i end
end
end
--- Iterator over each prime (from `lo`, if specified) up to `hi`.
---@param lo integer
---@param hi integer?
function Primes.eachprime(lo, hi)
if not hi then lo, hi = 2, lo end
generateprimes(hi)
return nextprime, hi, lo - 1
end
local primelistmt = {
__tostring = function(self)
return table.concat(self, '\n')
end
}
--- Returns a collection of the prime numbers (from lo, if specified) up to hi.
---@param lo integer
---@param hi integer
---@overload fun(hi: integer): integer[]
---@return integer[]
function Primes.primes(lo, hi)
local result = {}
for prime in Primes.eachprime(lo, hi) do
table.insert(result, prime)
end
return setmetatable(result, primelistmt)
end
--- The `i`-th smallest prime not less than `n` (in particular, `nextprime(p) == p`
--- if `p` is prime). If `i < 0`, this is equivalent to `prevprime(n, -i)`.
---@param n integer
---@param i integer defaults to 1
---@return integer?
---@overload fun(n: integer): integer
function Primes.nextprime(n, i)
i = i and assert(math.tointeger(i), "expected an integer") or 1
n = math.max(2, (assert(math.tointeger(n), "expected an integer")))
assert(i ~= 0, "can't get the zeroth prime")
local step = i > 0 and 1 or -1
if Primes.isprime(n) then i = i - step end
while i ~= 0 do
i = i - step
n = n + step
while not Primes.isprime(n) do
n = n + step
if n < 2 then return end
end
end
return n
end
---@param n integer
---@param i integer? defaults to 1
function Primes.prevprime(n, i)
return Primes.nextprime(n, -(i or 1))
end
--- The i-th prime number.
---@param i integer
function Primes.prime(i)
i = assert(i and i > 0 and math.tointeger(i), "i must be an integer") --[[@as integer]]
if i == 1 then return 2 end
generateprimes(math.ceil(i * math.log(i, 2)))
local n = 1
for j, data in ipairs(raw) do
for k = 0, 63 do
if (data >> k) & 1 == 1 then
n = n + 1
if n == i then
return 128 * (j - 1) + 3 + 2 * k
end
end
end
end
end
---@param n integer
---@return integer
function Primes.radical(n)
local result = 1
for prime in pairs(Primes.factor(n)) do
result = result * prime
end
return result
end
---@class Primes.factor: table<integer,{ [1]: integer, [2]: integer }>
Primes.factor = require("ji/class")("Primes.factor")
---@param n integer
function Primes.factor:new(n)
n = assert(math.tointeger(n), "expected an integer")
local result = {}
if n <= 0 then
table.insert(result, { n == 0 and 0 or -1, 1 })
n = -n
end
for prime in Primes.eachprime(n) do
while n % prime == 0 do
local i
for j = 1, #result do
if result[j][1] >= prime then
i = j
break
end
end
if result[i] and result[i][1] == prime then
result[i][2] = result[i][2] + 1
else
table.insert(result, i or #result + 1, { prime, 1 })
end
n = n // prime
end
end
return result
end
---@return integer
function Primes.factor:tonumber()
local result = 1
for prime, exponent in pairs(self) do
result = result * prime ^ exponent
end
return result
end
function Primes.factor:__pairs()
local i = 0
---@return integer, integer
---@overload fun(self: Primes.factor, i: integer)
return function()
i = i + 1
if i <= #self then
return table.unpack(self[i])
end
end
end
function Primes.factor:__tostring()
local result = {}
for _, pair in ipairs(self) do
table.insert(result, pair[2] == 1 and pair[1] or table.concat(pair, "^"))
end
return table.concat(result, " * ")
end
local function main(args)
local fn = function(n) os.exit(Primes.isprime(n)) end
for _, arg in ipairs(args) do
local n = math.tointeger(arg)
arg = arg:gsub("^%-+", "")
if n then
print(fn(n))
elseif arg == "help" or arg == "h" then
print(usage)
elseif Primes[arg] then
fn = Primes[arg]
else
local cmd, param = arg:match("^(%w+)=(.+)$")
n = math.tointeger(param)
if type(rawget(Primes, cmd)) == "function" and n then
fn = rawget(Primes, cmd)
else
print(("Unrecognised argument: %s"):format(arg))
os.exit(1)
end
print(fn(n))
end
end
end
if pcall(debug.getlocal, 4, 1) then
return Primes
else
main(arg)
end --=#