Lua: Calculate a prime number list
Lua is an extension language.
This script calculates a prime number list starting with smaller ones.
To run this script you need to install lua language: (e.g: in Debian or Ubuntu)
$ sudo aptitude install lua
Current version(when this article was written) is 5.1:
$ sudo aptitude install lua5.1
After installing it, lua interpreter could be found in /usr/bin/lua.
Then you copy this script in a file, e.g: primes.lua and exec:
$ lua primes.lua 20
# it will calculate first twenty prime numbers.
or give execution permissions to the file:
$ chmod a+x primes.lua
$ ./primes.lua 20
#! /usr/bin/lua local top = tonumber(arg[1]) -- number of primes to calculate local primes = {2} -- prime list local i=3 -- we start with number 3 local total = 1 local sqrt sqrt = math.sqrt while(total<top) do local is_prime = true local max = sqrt(i) -- we do not need to try with every prime divisor. for j=1, total do local div = primes[j] if(div>max) then break end if(i%div==0) then is_prime = false -- currrent number is not prime break end end if(is_prime) then table.insert(primes,i) -- a prime found. total = total + 1 end i = i + 2 end -- show prime number list. for i=1,# primes do print(primes[i]) end
REFERENCE
Lua Tutorial Directory
0 comentarios:
Post a Comment