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.
- Figure out how to solve the program on paper. (That is your algorithm)
- Then translate that to code.
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.
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;
}
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; }
精彩评论