[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: comparing Lua with other languages
- From: Philippe Lhoste <PhiLho@...>
- Date: Sun, 02 Jan 2005 15:53:10 +0100
Here is my contribution to the prime numbers test case.
What is remaining?
Increment/Decrement Window - Needs GUI
Producer Consumer - Needs threading
Query Tool - To be done
Red Ball - Needs graphical output
Mini Spreadsheet - May need GUI, but
as described, can be done in pure console mode.
Actually, that's how the C implementation was done.
So, to be done.
--
Philippe Lhoste
-- (near) Paris -- France
-- http://Phi.Lho.free.fr
-- -- -- -- -- -- -- -- -- -- -- -- -- --
#!Lua-5.0.exe
-- APLC Prime Numbers.
-- http://www.kochandreas.com/home/language/tests/PRIMES.HTM
-- by Philippe Lhoste <PhiLho(a)GMX.net> http://Phi.Lho.free.fr
-- v. 1.0 -- 2005/01/02
-- Part 1: Manage prime list
local Primes
do -- Encapsulate Primes class
local Public, Private = {}, {}
Primes = Public
Private.primes = { 2, 3 }
Private.maxIndex = 2
function Private.CheckPrime(number)
local i, limit = 1, math.sqrt(number)
repeat
-- Is our number divisible by one of our known primes?
if math.mod(number, Private.primes[i]) == 0 then
return false -- Not a prime
end
-- Try next prime
i = i + 1
-- Stop if square of prime is greater than the number
until Private.primes[i] > limit
return true -- OK!
end
function Public.GetNextPrime()
-- Start from latest found prime number
local prime = Private.primes[Private.maxIndex]
repeat
-- Increment by twos
prime = prime + 2
-- And check if this number is a prime
until Private.CheckPrime(prime)
-- When OK, store the newfound prime in the list
Private.maxIndex = Private.maxIndex + 1
Private.primes[Private.maxIndex] = prime
return prime
end
function Public.GetAllPrimes()
return Private.primes, Private.maxIndex
end
end -- Of Primes class
-- Part 2: Display a list of primes
function DumpArray(a)
for i, v in ipairs(a) do
io.write(v .. ' ')
end
print''
end
-- Use the above
-- Get maximum prime number from program argument
local maxPrime = 1000
if arg[1] ~= nil then
maxPrime = tonumber(arg[1]) or maxPrime
end
-- Generate the primes
for i = 1, maxPrime do
Primes.GetNextPrime()
end
-- And display them
DumpArray(Primes.GetAllPrimes())