RosettaCodeData/Task/Attractive-numbers/Lua/attractive-numbers.lua

37 lines
889 B
Lua
Raw Permalink Normal View History

2023-07-01 11:58:00 -04:00
-- Returns true if x is prime, and false otherwise
function isPrime (x)
if x < 2 then return false end
if x < 4 then return true end
if x % 2 == 0 then return false end
for d = 3, math.sqrt(x), 2 do
if x % d == 0 then return false end
end
return true
end
-- Compute the prime factors of n
function factors (n)
2025-08-11 18:05:26 -07:00
local facList, divisor = {}, 1
2023-07-01 11:58:00 -04:00
if n < 2 then return facList end
while not isPrime(n) do
while not isPrime(divisor) do divisor = divisor + 1 end
while n % divisor == 0 do
n = n / divisor
table.insert(facList, divisor)
end
divisor = divisor + 1
if n == 1 then return facList end
end
table.insert(facList, n)
return facList
end
-- Main procedure
2025-08-11 18:05:26 -07:00
local count = 0
2023-07-01 11:58:00 -04:00
for i = 1, 120 do
2025-08-11 18:05:26 -07:00
if isPrime(#factors(i)) then
count = count - 1
io.write( string.format("%6d", i), ( count % 12 == 0 and "\n" or "" ))
end
2023-07-01 11:58:00 -04:00
end