deepakl.2000
deepakl.2000

Reputation: 176

Java :: Triangle Problem

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

Answers (3)

Declan Cook
Declan Cook

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

Peter Lawrey
Peter Lawrey

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

jzd
jzd

Reputation: 23639

  1. Figure out how to solve the program on paper. (That is your algorithm)
  2. 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.

Upvotes: 5

Related Questions