Sum multiples of 3 and 5: Difference between revisions
→{{header|Python}}: Pylinted for Python 3, updated output
(Added Q solution.) |
(→{{header|Python}}: Pylinted for Python 3, updated output) |
||
Line 2,607:
Or, more generally – taking the area under the straight line between the first multiple and the last:
{{Works with|Python|3.7}}
<lang python>'''Summed multiples of 3 and 5 up to n'''
def sum35(n):
'''Sum of all positive multiples
f = sumMults(n)
return f(3) + f(5) - f(15)
# TEST ----------------------------------------------------▼
def main():▼
for x in enumFromTo(1)(5) + enumFromTo(18)(25):▼
print(▼
'1e' + str(x) + '\t' + str(▼
sum35(10 ** x)▼
▲ )
▲ )
# sumMults :: Int -> Int -> Int
def sumMults(n):
the first multiple and the last
'''
def go(n, m):
n1 = (n - 1) // m
return (m * n1 * (n1 + 1)) // 2
return lambda x: go(n, x)
▲# TEST ----------------------------------------------------
▲def main():
'''Tests for [10^1 .. 10^5], and [10^8 .. 10^25]
'''
fTable(__doc__ + ':\n')(lambda x: '10E' + str(x))(
str
)(compose(sum35)(lambda x: 10**x))(
)
)
# GENERIC -------------------------------------------------
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
'''Right to left function composition.'''
return lambda f: lambda x: g(f(x))
# enumFromTo :: (Int
def enumFromTo(m):
'''Integer enumeration from m to n.'''
return lambda n: list(range(m, 1 + n))
# fTable :: String -> (a -> String) ->
# (a -> b) -> [a] -> String
def fTable(s):
'''Heading -> x display function -> fx display function ->
f -> value list -> tabular string.'''
def go(xShow, fxShow, f, xs):
w = max(map(compose(len)(xShow), xs))
xShow(x).rjust(w, ' ') + ' -> ' + fxShow(f(x)) for x in xs
])
return lambda xShow: lambda fxShow: (
lambda f: lambda xs: go(
xShow, fxShow, f, xs
)
)
# MAIN ---
if __name__ == '__main__':
main()</lang>
{{Out}}
<pre>
1e2 2318▼
10E1 -> 23
1e3 233168▼
1e4 23331668▼
1e5 2333316668▼
1e18 233333333333333333166666666666666668▼
1e19 23333333333333333331666666666666666668▼
1e20 2333333333333333333316666666666666666668▼
1e21 233333333333333333333166666666666666666668▼
1e22 23333333333333333333331666666666666666666668▼
1e23 2333333333333333333333316666666666666666666668▼
1e24 233333333333333333333333166666666666666666666668▼
1e25 23333333333333333333333331666666666666666666666668</pre>▼
=={{header|Q}}==
|