The n-th triangle number is the sum of all integers from 1 to n:
tri(n) = 1 + 2 + 3 + ... + n
Notice that this is the number of bricks it takes to build a triangular staircase of height n:
Here's a nice shortcut to compute tri(n) that doesn't require iteration or recursion:
tri(n)
= 1 + 2 + 3 + ... + n
= (n + 1) + (n – 1 + 2) + ... (n – (n/2 – 1) + n/2)
= (n + 1) + (n + 1) + ... + (n + 1)
= (n + 1) * n/2
Here's an implementation in Java:
class Triangle {
public int tri(int n) {
return (n + 1) * n/2;
}
}
A test harness can be found in TestTriangle.java.
Translate the definition of class Triangle into Jasmin. Save your definition in a file called Triangle.j. Assemble it and test it using TestTriangle.