= Solution
An infinite <iterator> can keep the current index and triangular value:
``
val triangular = new Iterator[BigInt] {
private var n = BigInt(0)
private var total = BigInt(0)
def hasNext: Boolean = true
def next(): BigInt = {
val result = total
n += 1
total += n
result
}
}
println(triangular.take(8).toList)
``
Before each call, `total` is the <triangular number> $T_n=n(n+1)/2$. Returning it and then using $T_{n+1}=T_n+n+1$ preserves this invariant. The prefix is \b[$0,1,3,6,10,15,21,28$]. Arbitrary-precision integers prevent wraparound as the indefinitely available iterator advances.
Back to article page