Here we look at the factors program in the Examples . To play with it, run !TaskW in the RiscLua/Utilities directory and drag factors onto its iconbar icon. The main program is:
-- Prime factors
print "Enter a positive integer"
local N
repeat N = io.read "*n" until N > 0
local bar = "-------------"
print (bar)
local p, m = factors (N) -- prime factors, multiplicities
local write in io
write (tostring (N), " = ")
local k = #p
for i = 1, k do
local e = m[i]
write (tostring (p[i]))
if e > 1 then write ("^", tostring (e)) end -- if
if i < k then write "*" end -- if
end -- for
print ""
print (bar)
The only missing part is the function factors which returns a pair
of lists, the first the prime divisors of its argument, the second their
multiplicities. It is a great convenience of Lua that functions are not
throttled to returning only one value at a time. The expression
local write in iois equivalent to
local write = io.write. The local variable write is used four times, so we save looking up the key write from the io table three times. It saves only microseconds, but it makes a point.
The factors function that does the work is:
local factors = \ (n)
local p, m = { }, { } -- prime factors, multiplicities
for t = 2,3,1 do -- deal with 2,3 separately
if n%t == 0 then
p[1 + #p] = t; m[1 + #m] = 1; n //= t
while n%t == 0 do
m[#m] += 1; n //= t
end -- while
end -- if
end -- for
local t = 3 -- test factor
while n > 1 do
t += 2
if n%t == 0 then
p[1 + #p] = t; m[1 + #m] = 1; n //= t
while n%t == 0 do
m[#m] += 1; n //= t
end
else
if t*t > n then -- too big, so n is a prime
p[1 + #p] = n; m[1 + #m] = 1; n = 1
end -- if
end -- if
end -- while
=> p, m
end -- function
The expression { } creates an empty table. There follows a
for var = startval, endval, stepval do ... endblock for dealing separately with possible factors of 2 and 3. Note that // denotes integer division and % denotes the remainder operation. Whereas = denotes assignment, == denotes comparison. The # denotes the length operator. Thus
p[1 + #p] = tmeans add t to the end of list p .