Answer:
Yes. The calculation gets rather tedious, but the definition works for all positive integers.
Java Method
It might be nice to have a Java method that does the calculation for us.
Here is a math-like definition of Triangle(N):
- Triangle( 1 ) = 1
- Triangle( N ) = N + Triangle( N-1 )
And here is a Java method that does this calculation:
int Triangle( int N )
{
if ( N == 1 )
return 1;
else
return N + Triangle( N-1 );
}
The Java code is similar to the math-like definition of Triangle().
The if statement has been added so that the base case is selected
when it is needed.
QUESTION 8:
Is it OK to have Triangle( N-1 ) in the body of the method?