Full Example — Sequence to Compute n * n
The square can be computed using the following sequence:
$$ n^2 = n + 2 \sum_{i=0}^{n-1} i$$
In scala:
def square(x: Int): Int = {
def sq(y: Int): Int = y match {
case 0 => 0
case 1 => 1
case _ => val y2 = ((1 to (y - 1)).reduceLeft( _ + _ ))
y + y2 + y2
}
val z = Math.abs(x)
sq(z)
}
for (i < - -20 to 20) {
println(square(i))
}