Yes. The calculation gets rather tedious, but the definition works for all positive integers.
It might be nice to have a Java method that does the calculation for us.
Here is a math-like definition of Triangle(N)
:
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.
Is it OK to have Triangle( N-1 )
in the body of the method?