Sum multiples of 3 and 5: Difference between revisions

m
→‎{{header|Tcl}}: fix fencepost error
m (→‎{{header|Tcl}}: fix fencepost error)
Line 1,583:
 
=={{header|Tcl}}==
{{Incorrect|Tcl|Sum includes the limit if it is a multiple of 3 or 5 (in both versions).}}
<lang tcl># Fairly simple version; only counts by 3 and 5, skipping intermediates
proc mul35sum {n} {
for {set total [set threes [set fives 0]]} {$threes<=$n||$fives<=$n} {} {
if {$threes<$fives} {
incr total $threes
Line 1,601 ⟶ 1,600:
return $total
}</lang>
However, that's pretty dumb. We can do much better by observing that the sum of the multiples of <math>k</math> below some <math>n+1</math> is <math>k T_{n/k}</math>, where <math>T_i</math> is the <math>i</math>'th [[wp:Triangular number|triangular number]], for which there exists a trivial formula. Then we simply use an overall formula of <math>3T_{n/3} + 5T_{n/5} - 15T_{n/15}</math> (that is, summing the multiples of three and the multiples of five, and then subtracting the multiples of 15 which were double-counted).
<lang tcl># Smart version; no iteration so very scalable!
proc tcl::mathfunc::triangle {n} {expr {
Line 1,607 ⟶ 1,606:
}}
# Note that the rounding on integer division is exactly what we need here.
proc sum35 {n} {expr {
incr n -1
expr {3*triangle($n/3) + 5*triangle($n/5) - 15*triangle($n/15)}
}}</lang>
Demonstrating:
<lang tcl>puts [mul35sum 1000],[sum35 1000]
Anonymous user