Sum multiples of 3 and 5: Difference between revisions

→‎{{header|Perl 6}}: Add Python. (three ways).
(→‎{{header|REXX}}: changed to below :-) thanks)
(→‎{{header|Perl 6}}: Add Python. (three ways).)
Line 28:
{{out}}
<pre>233168</pre>
 
=={{header|Python}}==
Three ways of performing the calculation are shown including direct calculation of the value without having to do explicit sums in sum35c()
<lang python>def sum35a(n):
'Direct count'
# note: ranges go to n-1
return sum(x for x in range(n) if x%3==0 or x%5==0)
 
def sum35b(n):
"Count all the 3's; all the 5's; minus double-counted 3*5's"
# note: ranges go to n-1
return sum(range(3, n, 3)) + sum(range(5, n, 5)) - sum(range(15, n, 15))
def sum35c(n):
'Sum the arithmetic progressions: sum3 + sum5 - sum15'
consts = (3, 5, 15)
# Note: stop at n-1
divs = [(n-1) // c for c in consts]
sums = [d*c*(1+d)/2 for d,c in zip(divs, consts)]
return sum(sums[:-1]) - sums[-1]
 
#test
for n in range(1001):
sa, sb, sc = sum35a(n), sum35b(n), sum35c(n)
assert sa == sb and sa == sc
print('For n = %i -> %i' % (n, sc))</lang>
 
{{out}}
<pre>For n = 1000 -> 233168</pre>
 
=={{header|REXX}}==
Anonymous user