public int Pyramid( int N ) { if ( N == 1 ) return 1; else return Pyramid ( N-1 ) + Triangle ( N ); }
Here is a complete program that computes Pyramidal numbers. The user specifies N, the number of balls in a side of the base, in the command line.
class Calculate { public int Triangle( int N ) { if ( N == 1 ) return 1; else return N + Triangle( N-1 ); } public int Pyramid( int N ) { if ( N == 1 ) return 1; else return Pyramid ( N-1 ) + Triangle ( N ); } } public class PyramidTester { public static void main ( String[] args) { int argument = Integer.parseInt( args[0] ); // Get argument from the command line Calculate calc = new Calculate(); int result = calc.Pyramid( argument ); System.out.println("Pyramid(" + argument + ") is " + result ); } }
The program must include a method
for Triangle()
.
Here is a run of the program:
C:\>java PyramidTester 12 Pyramid(12) is 364
Could the program (above) use an iterative method for Triangle()
and a recursive method for Pyramid()
?