Originally Posted by

**jflurrie** First of all, please move this thread if it is in totally wrong place.

Anyway, I took today in our university an exam in Discrete Mathematics. The question itself was easy and I know the answer too (by counting it with computer), but what is the formula to solve this? Here's the code as VBA code:

Code:

Sub forlooptask()
Dim i As Long, j As Long, k As Long, x As Long
For i = 1 To 200
For j = 1 To i - 1
For k = 1 To j
x = x + 1
Next k
Next j
Next i
Debug.Print x
End Sub

the result is 1333300. The question is:

**How does the equation for solving this go? Where does that 200 go to?** EDIT: Apparently, I am unable to read an entire thread before posting. I therefore appologise for reapeating, well, everything, but this took me a while to type up (I'm a slow typer) so I'm refusing that to be (entirely) wasted time! So behold! my post...

Code:

For i = 1 To 200
For j = 1 To i - 1
For k = 1 To j
x = x + 1
Next k
Next j
Next i

becomes

Code:

For i = 1 To 200
For j = 1 To i - 1
x=x+j
Next j
Next i

because adding 1 on j times is the same as adding on j. Now, in this bit you are just summing up all the numbers between 1 and (i-1). There is a well-known formula for this,

$\displaystyle \sum_a^na = \frac{a(a+1)}{2}$. Here, a = (i-1). Thus, your code becomes,

Code:

For i = 1 To 200
x = x + i(i-1)/2
Next i

and I suppose you can just write this as $\displaystyle \sum_i^{200} \frac{i(i-1)}{2}$. If you want to do it more, expand it so you will have,

$\displaystyle \frac{1}{2}\sum_i^{200} i^2 + \frac{1}{2}\sum_i^{200}i$

and then you can just plug in some formulas to evaluate these.