Proper divisors: Difference between revisions
m
→Python: Functional: Slightly simpler definition
(→{{header|Haskell}}: Added a definition of properDivisors in terms of primeFactors) |
m (→Python: Functional: Slightly simpler definition) |
||
Line 3,939:
{{Works with|Python|3.7}}
<lang python>'''Proper divisors'''
from itertools import accumulate, chain, groupby, product
from functools import reduce
from math import floor, sqrt
# properDivisors :: Int -> [Int]
def properDivisors(n):
'''The ordered divisors of n, excluding n itself.
'''
def go(a,
return [a * b for a, b in product(
a,
accumulate(
chain([1],
lambda a,
)
)]
return sorted(
reduce(go, [
list(
], [1])
)[:-1] if 1 < n else []
# --------------------------TEST---------------------------
# main :: IO ()
def main():
'''Tests'''
print(
fTable('Proper divisors of [1..10]:')(str)(str)(
Line 3,976 ⟶ 3,974:
)(range(1, 1 + 10))
)
print('\nExample of maximum divisor count in the range [1..20000]:')
print(
Line 3,984 ⟶ 3,982:
)
)
# -------------------------DISPLAY-------------------------
# fTable :: String -> (a -> String) ->
# (b -> String) -> (a -> b) -> [a] -> String
Line 4,004 ⟶ 4,002:
xShow, fxShow, f, xs
)
# -------------------------GENERIC-------------------------
# primeFactors :: Int -> [Int]
def primeFactors(n):
Line 4,016 ⟶ 4,014:
r = qr[1]
return step(r), 1 + r
def step(x):
return 1 + (x << 2) - ((x >> 1) << 1)
def go(x):
root = floor(sqrt(x))
def p(qr):
q = qr[0]
return root < q or 0 == (x % q)
q = until(p)(f)(
(2 if 0 == x % 2 else 3, 1)
)[0]
return [x] if q > root else [q] + go(x // q)
return go(n)
# snd :: (a, b) -> b
def snd(tpl):
'''Second member of a pair.'''
return tpl[1]
# until :: (a -> Bool) -> (a -> a) -> a -> a
def until(p):
Line 4,052 ⟶ 4,050:
return v
return lambda f: lambda x: go(f, x)
# MAIN ---
if __name__ == '__main__':
|