Sorting in Lua, counting number of items

Posted by Josh on Stack Overflow See other posts from Stack Overflow or by Josh
Published on 2010-05-04T07:51:26Z Indexed on 2010/05/04 7:58 UTC
Read the original article Hit count: 173

Filed under:
|

Two quick questions (I hope...) with the following code. The script below checks if a number is prime, and if not, returns all the factors for that number, otherwise it just returns that the number prime. Pay no attention to the zs. stuff in the script, for that is client specific and has no bearing on script functionality.

The script itself works almost wonderfully, except for two minor details - the first being the factor list doesn't return itself sorted... that is, for 24, it'd return 1, 2, 12, 3, 8, 4, 6, and 24 instead of 1, 2, 3, 4, 6, 8, 12, and 24. I can't print it as a table, so it does need to be returned as a list. If it has to be sorted as a table first THEN turned into a list, I can deal with that. All that matters is the end result being the list.

The other detail is that I need to check if there are only two numbers in the list or more. If there are only two numbers, it's a prime (1 and the number). The current way I have it does not work. Is there a way to accomplish this? I appreciate all the help!

function get_all_factors(number)
local factors = 1
for possible_factor=2, math.sqrt(number), 1 do
    local remainder = number%possible_factor

    if remainder == 0 then
        local factor, factor_pair = possible_factor, number/possible_factor
        factors = factors .. ", " .. factor
        if factor ~= factor_pair then
            factors = factors .. ", " ..  factor_pair
          end
    end
end

factors = factors .. ", and " .. number
return factors
end
local allfactors = get_all_factors(zs.param(1))
if zs.func.numitems(allfactors)==2 then
return zs.param(1) .. " is prime."
else
return zs.param(1) .. " is not prime, and its factors are: " .. allfactors
end

© Stack Overflow or respective owner

Related posts about lua

Related posts about sorting