Recursion with Triangle Numbers

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.

Answer:

The base case is when a rock fragment is small enough. No more work needs to be done.

Recursion with Triangle Numbers

Here are the two parts to recursion:

  1. If the problem is easy, solve it immediately.
    • An easy problem is a base case.
  2. If the problem can't be solved immediately, divide it into smaller problems, then:
    • Solve the smaller problems by applying this procedure to each of them.

And here is how this applies to triangle numbers:

  1. Triangle( 1 ) = 1
  2. Triangle( N ) = N + Triangle( N-1 )

The problem "Triangle(N)" is divided into two problems: "add N to something" and "Triangle(N-1)". Sometimes the latter can be solved immediately (when it is the base case). Other times you need to re-apply the solution to the smaller problem.

QUESTION 6:

Using the above, what is Triangle(3)? (Fill in the boxes starting with the top row and work your way down.)

Triangle( 3 ) = + Triangle( )
Triangle( 2 ) = + Triangle( )
Triangle( 1 ) =    
Triangle( 2 ) = +
Triangle( 3 ) = +
Triangle( 3 ) =