Java Reference
In-Depth Information
solutions use a termination test. In the recursive solution (Fig. 18.3), line 9 tests for the
base
case
. In the iterative solution, line 12 of Fig. 18.9 tests the loop-continuation condition—if
the test fails, the loop terminates. Finally, instead of producing smaller versions of the orig-
inal problem, the iterative solution uses a counter that is modified until the loop-continua-
tion condition becomes false.
1
// Fig. 18.9: FactorialCalculator.java
2
// Iterative factorial method.
3
4
public
class
FactorialCalculator
5
{
6
// recursive declaration of method factorial
7
public
long
factorial(
long
number)
8
{
9
long
result =
1
;
10
11
// iterative declaration of method factorial
12
for
(
long
i = number; i >=
1
; i--)
result *= i;
13
14
15
return
result;
16
}
17
18
// output factorials for values 0-10
19
public
static
void
main(String[] args)
20
{
21
// calculate the factorials of 0 through 10
22
for
(
int
counter =
0
; counter <=
10
; counter++)
23
System.out.printf(
"%d! = %d%n"
, counter, factorial(counter)
)
;
24
}
25
}
// end class FactorialCalculator
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
Fig. 18.9
|
Iterative factorial method.
Recursion has many
negatives
. It repeatedly invokes the mechanism, and consequently
the
overhead, of method calls
. This repetition can be
expensive
in terms of both processor
time and memory space. Each recursive call causes another
copy
of the method (actually,
only the method's variables, stored in the stack frame) to be created—this set of copies
can
consume considerable memory space
. Since iteration occurs within a method, repeated
method calls and extra memory assignment are avoided.