Constant-time Approach
As
Realigning the previous solution will reveal a pattern that emerges:
The components of the above are the arithmetic sum, in steps of
Another way to look at this is to separate out the common parts of each column and row in the above grid, resulting in one part that increases vertically and another part that is the same for every row.
This is in terms of
n := limit - 1
k := n / 15 // number of rows (except partial final row)
rowcount := 5 /*3s*/ + 3 /*5s*/ - 1 /*common*/
rowsum := 0 + 3 + 5 + 6 + 9 + 10 + 12
sum := rowcount * 15 * k * (k - 1) / 2
sum += k * rowsum
The last row may be partial, a few values remaining between
// Add remaining multiples of 3 and 5 (excluding n).
delta := n - k*15
div3, div5 := delta/3, delta/5
sum += k*15*(div3+div5+1) +
div3*(div3+1)*3/2 +
div5*(div5+1)*5/2
To understand the last three lines, it helps to think of the last (partial) row as its own
arithmetic series for the threes and fives separately, offset by the div3
and div5
are the limits on these smaller series, arrived at by counting the numbers between rowsum
, and this can be generalized as well.