Reputation: 176
We have triangle made of blocks. The topmost row has 1 block, the next row down has 2 blocks, the next row has 3 blocks, and so on. Compute the total number of blocks in such a triangle with the given number of rows.
triangle(0) => 0
triangle(1) => 1
triangle(2) => 3
The function signature is public int triangle(int rows) { }
I'm unable to proceed with this problem and struggling to solve it.
Upvotes: 1
Views: 1105
Reputation: 6126
What you are doing is computing triangular numbers:
http://en.wikipedia.org/wiki/Triangular_number
public int triangle(int rows) {
return rows * (rows + 1) / 2;
}
Upvotes: 1
Reputation: 533790
You want to calculate the sum of N, N-1, ... to 1. This is the same as N * (N + 1) / 2
public int triangle(int rows) { return rows * (rows + 1) / 2; }
Upvotes: 1
Reputation: 23639
Looks like you are trying to do step 2 without doing step 1 first. That will alway make you struggle with what to do next.
Upvotes: 5