Factors of an integer: Difference between revisions
Content added Content deleted
(→{{Header|Haskell}}: upd the dead link to one via web.archive.org) |
|||
Line 248: | Line 248: | ||
factors 720 |
factors 720 |
||
1 2 3 4 5 6 8 9 10 12 15 16 18 20 24 30 36 40 45 48 60 72 80 90 120 144 180 240 360 720</lang> |
1 2 3 4 5 6 8 9 10 12 15 16 18 20 24 30 36 40 45 48 60 72 80 90 120 144 180 240 360 720</lang> |
||
=={{header|AppleScript}}== |
|||
<lang AppleScript>-- integerFactors :: Int -> [Int] |
|||
on integerFactors(n) |
|||
script mf |
|||
-- isFactor :: Int -> Bool |
|||
on isFactor(x) |
|||
(n of my closure) mod x = 0 |
|||
end isFactor |
|||
-- integerQuotient :: Int -> Int |
|||
on integerQuotient(x) |
|||
((n of my closure) / x) as integer |
|||
end integerQuotient |
|||
end script |
|||
set rRoot to n ^ (1 / 2) |
|||
set intRoot to rRoot as integer |
|||
set lows to filter(mClosure(isFactor of mf, {n:n}), range(1, intRoot)) |
|||
set highs to map(mClosure(integerQuotient of mf, {n:n}), lows) |
|||
-- For perfect squares, no need to consider the head of the 'highs' list |
|||
if rRoot = intRoot then |
|||
lows & reverse of items 2 thru -1 of highs |
|||
else |
|||
lows & reverse of highs |
|||
end if |
|||
end integerFactors |
|||
on run |
|||
integerFactors(120) |
|||
end run |
|||
-- GENERIC LIBRARY FUNCTIONS |
|||
-- map :: (a -> b) -> [a] -> [b] |
|||
on map(f, xs) |
|||
set mf to mReturn(f) |
|||
set lng to length of xs |
|||
set lst to {} |
|||
repeat with i from 1 to lng |
|||
set end of lst to mf's lambda(item i of xs, i, xs) |
|||
end repeat |
|||
return lst |
|||
end map |
|||
-- filter :: (a -> Bool) -> [a] -> [a] |
|||
on filter(f, xs) |
|||
set mf to mReturn(f) |
|||
set lst to {} |
|||
set lng to length of xs |
|||
repeat with i from 1 to lng |
|||
set v to item i of xs |
|||
if mf's lambda(v, i, xs) then |
|||
set end of lst to v |
|||
end if |
|||
end repeat |
|||
return lst |
|||
end filter |
|||
-- range :: Int -> Int -> [Int] |
|||
on range(m, n) |
|||
set d to 1 |
|||
if n < m then set d to -1 |
|||
set lst to {} |
|||
repeat with i from m to n by d |
|||
set end of lst to i |
|||
end repeat |
|||
return lst |
|||
end range |
|||
-- Lift 2nd class handler function into 1st class script wrapper |
|||
-- mReturn :: Handler -> Script |
|||
on mReturn(f) |
|||
if class of f is script then return f |
|||
script |
|||
property lambda : f |
|||
end script |
|||
end mReturn |
|||
-- mClosure :: Handler -> Record -> Script |
|||
on mClosure(f, recBindings) |
|||
script |
|||
property closure : recBindings |
|||
property lambda : f |
|||
end script |
|||
end mClosure |
|||
</lang> |
|||
{{Out}} |
|||
<lang AppleScript>{1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120}</lang> |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |