Advertisement
OgreVorbis

Primes Lua

Nov 5th, 2021 (edited)
1,441
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.88 KB | None | 0 0
  1. local nums = {}
  2. local s; local n; local m; local lim
  3. local yorn
  4.  
  5. print(os.date("Today is a %A, in %B"))
  6. io.write("Enter limit for this search (empty for default): ")
  7. lim = tonumber(io.read())
  8. if lim == nil then lim = 100000000 end
  9. s = math.sqrt(lim)
  10. local tStart = os.time()
  11.  
  12. for n = 1, lim do
  13.     nums[n] = false
  14. end
  15.  
  16. for n = 2, s do
  17.     if nums[n] == false then
  18.         m = n * n
  19.         while m <= lim do
  20.             nums[m] = true
  21.             m = m + n
  22.         end
  23.     end
  24. end
  25.  
  26. print("It took " .. (os.time() - tStart) .. " seconds to complete.")
  27. io.write("Do you want to list results (Y/N)? ")
  28. yorn = io.read()
  29. if yorn == "Y" or yorn == "y" then
  30.     print("The primes up to " .. lim .. " are: ")
  31. else
  32.     print("(please wait for count...)")
  33. end
  34. m = 0
  35. for n = 2, lim do
  36.     if nums[n] == false then
  37.         if yorn == "Y" or yorn == "y" then print(n) end
  38.         m = m + 1
  39.     end
  40. end
  41. print("")
  42. print("Total primes = " .. m)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement