RosettaCodeData/Task/Proper-divisors/Phix/proper-divisors-1.phix
2026-02-01 16:33:20 -08:00

31 lines
892 B
Text

global function factors(atom n, integer include1=0)
--
-- returns a list of all integer factors of n
-- if include1 is 0 (the default), result does not contain either 1 or n
-- if include1 is 1 the result contains 1 and n
-- if include1 is -1 the result contains 1 but not n
--
if n=0 then return {} end if
check_limits(n,"factors")
sequence lfactors = {}, hfactors = {}
atom hfactor
integer p = 2,
lim = floor(sqrt(n))
if include1!=0 then
lfactors = {1}
if n!=1 and include1=1 then
hfactors = {n}
end if
end if
while p<=lim do
if remainder(n,p)=0 then
lfactors = append(lfactors,p)
hfactor = n/p
if hfactor=p then exit end if
hfactors = prepend(hfactors,hfactor)
end if
p += 1
end while
return lfactors & hfactors
end function