CCCPaste

Primes Lua

local nums = {}
local s; local n; local m; local lim
local yorn

print(os.date("Today is a %A, in %B"))
io.write("Enter limit for this search (empty for default): ")
lim = tonumber(io.read())
if lim == nil then lim = 100000000 end
s = math.sqrt(lim)
local tStart = os.time()

for n = 1, lim do
	nums[n] = false
end

for n = 2, s do
	if nums[n] == false then
		m = n * n
		while m <= lim do
			nums[m] = true
			m = m + n
		end
	end
end

print("It took " .. (os.time() - tStart) .. " seconds to complete.")
io.write("Do you want to list results (Y/N)? ")
yorn = io.read()
if yorn == "Y" or yorn == "y" then
	print("The primes up to " .. lim .. " are: ")
else
	print("(please wait for count...)")
end
m = 0
for n = 2, lim do
	if nums[n] == false then
		if yorn == "Y" or yorn == "y" then print(n) end
		m = m + 1
	end
end
print("")
print("Total primes = " .. m)