It's probably easiest to think of this as the sum of two separate series, one for when i%3 = 1
and the other for when i%3=2
. Alternatively, you could figure it as the sum for all values of i
minus the sum for i%3=0
. For the sake of argument, let's look at the first half of the latter approach: summing all the values of width.
In this case, width
will start at some initial value, and each iteration its value will be reduced by 1. In the last iteration, its value will have been reduced by (end-start)
. Perhaps it's easiest to think of it as a triangle. Just to keep things simple, we'll use small numbers -- we'll start with width = 5, start = 1 and end = 5. Perhaps it's easiest to draw a diagram:
Values of width:
*
**
***
****
*****
What we're really looking for is the area of that triangle -- which is a pretty well-known formula from elementary geometry -- 1/2ab, where a and b are the lengths of the two sides (in this case, defined by the initial value of width
and end-start
). That assumes it really is a triangle though -- i.e. that it decrements down to 0. In reality, there's a good chance that we're dealing with a truncated triangle -- but the formula for that is also well known (1/2a1b + 1/2a2b, where the a's are the heights of the right and left sides, and b is the width.