Humble numbers: Difference between revisions

Content added Content deleted
(→‎{{header|Python}}: Defined humbles in terms of yield and set, rather than filter)
Line 1,755: Line 1,755:
<lang python>'''Humble numbers'''
<lang python>'''Humble numbers'''


from itertools import count, groupby, islice
from itertools import groupby, islice
from functools import reduce
from functools import reduce
from math import floor, sqrt




Line 1,765: Line 1,764:
OEIS A002473
OEIS A002473
'''
'''
def isHumble(x):
hs = set([1])
while True:
return all(8 > x for x in primeFactors(x))
nxt = min(hs)
return filter(isHumble, count(1))
hs.remove(nxt)
hs = hs.union(nxt * x for x in [2, 3, 5, 7])
yield nxt




Line 1,785: Line 1,787:


print('\nCounts of Humble numbers with n digits:\n')
print('\nCounts of Humble numbers with n digits:\n')
for tpl in take(5)(
for tpl in take(10)(
(k, len(list(g))) for k, g in
(k, len(list(g))) for k, g in
groupby(map(compose(len, str), humbles()))
groupby(len(str(x)) for x in humbles())
):
):
print(tpl)
print(tpl)
Line 1,804: Line 1,806:
range(0, len(xs), n), []
range(0, len(xs), n), []
) if 0 < n else []
) if 0 < n else []


# compose :: ((a -> a), ...) -> (a -> a)
def compose(*fs):
'''Composition, from right to left,
of a series of functions.
'''
return lambda x: reduce(
lambda a, f: f(a),
fs[::-1], x
)


# primeFactors :: Int -> [Int]
def primeFactors(n):
'''A list of the prime factors of n.
'''
def f(qr):
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)




Line 1,849: Line 1,814:
or xs itself if n > length xs.
or xs itself if n > length xs.
'''
'''
return lambda xs: list(islice(xs, n))
return lambda xs: (
list(islice(xs, n))

)

# until :: (a -> Bool) -> (a -> a) -> a -> a
def until(p):
'''The result of repeatedly applying f until p holds.
The initial seed value is x.
'''
def go(f, x):
v = x
while not p(v):
v = f(v)
return v
return lambda f: lambda x: go(f, x)




Line 1,883: Line 1,837:
(3, 95)
(3, 95)
(4, 197)
(4, 197)
(5, 356)</pre>
(5, 356)
(6, 579)
(7, 882)
(8, 1272)
(9, 1767)
(10, 2381)</pre>


=={{header|Racket}}==
=={{header|Racket}}==