Object-Oriented Programming with Java · Lecture Notes
Chapter 3.5: Recursion
Some problems contain a smaller copy of themselves. 5! is 5 times 4!; the digit sum of 48729 is the digit sum of 4872 plus 9. Recursion turns this structure directly into code: a method hands a smaller piece of the work back to itself and builds its own answer from the reply. The chapter first introduces the base case, the recursive step and the call stack. It then writes factorial, sum, four number sequences, digit sum, palindrome testing, Euclid's algorithm and the Towers of Hanoi in Java and traces each call by call. The last sections deal with the price of recursion: stack overflow, recomputing the same value over and over, conversion to loops, tail recursion and memoization. Every program was run on JDK 21; the outputs, call counts and timings come from those runs.
Learning outcomes
- Concept
- Define recursion, the base case and the recursive step; reduce a problem to a smaller copy of itself.
- How it runs
- Trace, step by step, how frames pile up on the call stack and unwind again; draw a call tree.
- Writing
- Write recursive Java methods for factorial, sum, number sequences, digit sum, palindromes, the GCD and the Towers of Hanoi.
- Pitfalls
- Recognize and prevent infinite recursion,
StackOverflowErrorand missingreturnstatements. - Efficiency
- Compare recursive and iterative solutions; convert a recursive method into a loop when needed.
- Advanced techniques
- Explain tail recursion and memoization; eliminate repeated computation.
3.5.1The idea of recursion
A method names a piece of work and makes it callable in one line. main can call a method, and that method can call another. The method it calls may even be itself. Java does not forbid this, and the possibility lets some problems be written far more briefly and clearly than with loops.
3.5.1.1What is recursion?
Recursion is a method calling itself in order to split its task into smaller parts. Each call solves a smaller but otherwise identical copy of the problem; the smallest copy is solved directly. A method that calls itself is called a recursive method.
Java has no special keyword for recursion. The method body simply calls its own name, just like any other method call. To the compiler, factorial calling factorial is no different from main calling println. The difference shows up at run time: several calls of the same method wait in memory at once.
Recursion has three familiar counterparts in everyday life. In a set of matryoshka dolls every doll contains a smaller doll. The smallest doll is not opened; that is the base case of recursion. In a cinema, someone sitting in the dark wants to know which row they are in. They ask the person in front, who asks the person in front of them, and so on. The person in the first row says "1". As the answers come back, each person adds 1 to the number they hear and tells the person behind. The question travels forward and the answer travels back. This is exactly how a recursive method runs. Between two facing mirrors, an image contains an image, which contains yet another image, and the sequence never ends. That is a picture of recursion without a base case.
Recursion is not the right choice for every problem. For some kinds of problems, however, it gives a much clearer solution than a loop. Tree-shaped data, such as folders and subfolders, is one of them. Number sequences defined in terms of themselves are another. Divide-and-conquer algorithms, which split a problem in two and solve the parts separately, belong to the same group. Some puzzles, such as the Towers of Hanoi, are hard to write with loops but take only a few lines with recursion.
3.5.1.2Base case and recursive step
Every recursive method has two parts. One makes it stop, the other makes it progress.
The base case is the smallest problem, whose answer is known directly. In this case the method does not call itself and the recursion stops. The recursive step reduces the problem by one step, asks the method itself, and builds its own answer from the reply.
Factorial shows these two parts most clearly. 1! = 1 is known; no computation is needed. 4! is not known directly, but if 3! is known, then 4! = 4 × 3!. The inductive definition from mathematics corresponds one-to-one to the recursive method:
The first line is the base case and the second is the recursive step. The definition may look circular, but it is not: defining 4! uses 3!, and defining 3! uses 2!. At every step the argument shrinks, and in the end it reaches 1. Figure 3.5.1 shows this nesting with boxes.
factorial(4) shrinks by one at each level until it reaches the base case factorial(1). The innermost box does not call itself; its answer is simply 1.Both parts are mandatory. Without a base case the method calls itself forever. If the recursive step does not shrink the problem, the base case is never reached and the result is the same. The two basic rules every recursive method must obey follow from these two conditions.
3.5.1.3The call stack
To understand how recursion works, one must know how Java keeps method calls in memory.
For every method call, a stack frame is opened in memory. The frame holds the call's parameters, its local variables and the place to return to when the method finishes. Frames are piled on top of each other on the call stack; only the top frame runs, and the ones below wait.
A stack is like a pile of plates. A new plate goes on top, and the next plate to be taken also comes from the top. This discipline is called last in, first out (LIFO). When a method is called, its frame is added to the top of the stack. When the method finishes with return, its frame is removed and the value it returns is passed to the frame below. That frame resumes exactly where it left off.
In recursion, several frames of the same method live at the same time. When factorial(4) calls factorial(3), the first frame is not removed; it waits for the value coming up from below so that it can do its multiplication. Every frame has its own n. The stack can hold four separate ns: one is 4, one is 3, one is 2, one is 1. They are variables that share a name but are independent of each other. Changing n in one frame does not affect the others.
factorial(4). factorial(1) runs at the top of the stack; the three frames below it wait to complete their products, and at the very bottom main waits for the result. A frame is added on a call (left arrow) and removed on a return (right arrow).Figure 3.5.2 shows the deepest moment of a program in which main calls factorial(4). At that moment the stack holds five frames: main and four factorial frames. Only factorial(1) at the top is running. Each frame below is stopped halfway through a multiplication, waiting for the missing factor: 4 * ?, 3 * ?, 2 * ?.
The size of the stack is limited. In Java, each thread's stack is a fixed region of memory set when the program starts. A very deep recursion fills this region and the program stops with a StackOverflowError. This limit is the most important practical constraint of recursion.
Believing that the variable is "overwritten" in a recursive call. When factorial(3) is called, the n of factorial(4) does not become 3. A new n is created in the new frame, and the old frame's n = 4 waits unchanged. That is why the multiplication on the way back can be carried out as 4 * 6.
3.5.2Factorial and sum
Factorial and the sum from 1 to n are the two simplest examples of recursion. Both follow the same pattern: reduce the argument by one, call yourself, and add your own contribution to the result that comes back. Once this pattern is understood well, most of the later examples read as variations on it.
3.5.2.1The factorial method
The factorial of n is the product of the numbers from 1 to n: n! = 1 × 2 × … × n. By definition 0! = 1. The same product can also be written recursively as n! = n × (n − 1)!. In Java it looks like this:
int factorial(int n) {
if (n == 0 || n == 1) {
return 1; // base case
} else {
return n * factorial(n - 1); // recursion
}
}Line 1 is the method header: it takes an int parameter and returns an int value. Lines 2 and 3 are the base case. If n is 0 or 1, the answer is 1 and the method returns without calling itself. Line 5 is the recursive step: n! is n times (n − 1)!. The multiplication cannot be done before factorial(n - 1) has been evaluated, so the method first calls itself, waits for the answer, then multiplies and returns.
One can show that the method always terminates. On every call n decreases by 1. If n ≥ 0 at the start, this decrease eventually reaches 1 or 0 and the base case runs. This guarantee of progress is the property to look for in every recursive method. The call factorial(5) returns 120 and factorial(0) returns 1.
| n | factorial(n) | True n! | Correct? |
|---|---|---|---|
| 0 | 1 | 1 | yes |
| 5 | 120 | 120 | yes |
| 12 | 479001600 | 479,001,600 | yes |
| 13 | 1932053504 | 6,227,020,800 | no (overflow) |
| 17 | −288522240 | 355,687,428,096,000 | no (even negative) |
That the code is mathematically correct does not mean every result will be correct. An int can hold at most 2,147,483,647. 12! = 479,001,600 is below this limit, while 13! = 6,227,020,800 is above it. Java does not report overflow: the high bits of the product that do not fit are discarded, and a meaningless number is left (Table 3.5.1). factorial(13) returns 1932053504; for 17! the result is negative. If the return type is changed to long, results are correct up to 20! = 2,432,902,008,176,640,000; 21! does not fit in a long either. For larger factorials, java.math.BigInteger is used.
Expecting the compiler or the runtime to catch overflow. In int and long multiplication, Java produces no warning and no exception. The range of the result must be estimated in advance and a suitable type chosen. If overflow should be reported as an exception, use Math.multiplyExact; on overflow this method throws an ArithmeticException.
3.5.2.2Expanding factorial(4)
The shortest way to find the result of a recursive call by hand is to expand it by substitution. Wherever factorial(k) appears, put k * factorial(k - 1), and when the base case is reached, compute back:
factorial(4)
= 4 * factorial(3)
= 4 * (3 * factorial(2))
= 4 * (3 * (2 * factorial(1)))
= 4 * (3 * (2 * 1))
= 4 * (3 * 2)
= 4 * 6
= 24The expansion has three phases. The first four lines are the descent. Every call opens a new call and the multiplications are put on hold, because the value on the right is not yet known. In the fifth line the bottom, that is, the base case, is reached. factorial(1) returns 1 directly. Because the code stops at n == 1, factorial(0) is never called. The last three lines are the ascent. The pending multiplications are completed from the inside out: first 2 × 1 = 2, then 3 × 2 = 6, and finally 4 × 6 = 24.
The nesting of the parentheses is the call stack written out in text. The innermost parenthesis is the top of the stack and is completed first. Each closing parenthesis corresponds to a frame removed from the stack. Note that the multiplications are performed in reverse order, not in the order 4 × 3 × 2 × 1. For multiplication the order does not change the result; but for work where order matters, such as printing, the difference between the descent and the ascent is decisive.
3.5.2.3Tracing on the call stack
The same computation can also be traced as the run of a complete program. In the program below, main calls factorial(4) and prints the result:
static int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
public static void main(String[] args) {
System.out.println(factorial(4));
}24Table 3.5.2 gives the call stack at each step of the program, from bottom to top. The "Pending work" column is the computation the frame will carry out when it resumes.
| Step | Event | Stack (bottom to top) | Pending work |
|---|---|---|---|
| 1 | main calls factorial(4) | main | print the result |
| 2 | n = 4: condition false, calls factorial(3) | main, f(4) | 4 * ? |
| 3 | n = 3: condition false, calls factorial(2) | main, f(4), f(3) | 3 * ? |
| 4 | n = 2: condition false, calls factorial(1) | main, f(4), f(3), f(2) | 2 * ? |
| 5 | n = 1: base case, returns 1 | main, f(4), f(3), f(2), f(1) | — |
| 6 | f(2) receives 1: returns 2 * 1 = 2 | main, f(4), f(3), f(2) | — |
| 7 | f(3) receives 2: returns 3 * 2 = 6 | main, f(4), f(3) | — |
| 8 | f(4) receives 6: returns 4 * 6 = 24 | main, f(4) | — |
| 9 | main prints 24 | main | — |
Four calls of factorial are made. At the deepest moment, step 5, the stack holds five frames: main and four factorial frames. Figure 3.5.3 shows three moments of the same trace as a call chain. The top shows the bottom of the descent and the bottom shows the state after all the returns have completed.
factorial(4). Top: the base case has been reached; three frames wait for the products 4 * ?, 3 * ? and 2 * ?. Middle: factorial(2) has returned 2, and factorial(3) now computes 3 * 2 = 6. Bottom: all frames have returned a value; factorial(4) = 24.The time and memory cost of a recursive method can be read off this trace. factorial(n) makes exactly n calls, and each call has one comparison and one multiplication. The running time is proportional to n, that is, O(n). At most n frames are on the stack at once, so the memory is also O(n). A loop doing the same job also takes O(n) time, but it runs in a single frame and needs only O(1) memory. As the depth grows, this difference becomes important.
3.5.2.4The sum from 1 to n
The sum of the numbers from 1 to n is written with the same pattern: sum(n) = n + sum(n − 1) and sum(1) = 1. The only differences from factorial are that addition replaces multiplication and that the base case is just n == 1.
int sum(int n) {
if (n == 1) {
return 1;
} else {
return n + sum(n - 1);
}
}sum(5) = 5 + sum(4)
= 5 + (4 + (3 + (2 + sum(1))))
= 5 + (4 + (3 + (2 + 1)))
= 15In the expansion, each call leaves behind an addition that is waiting for its number. When the bottom is reached, 2 + 1 = 3 is computed, then 3 + 3 = 6, 4 + 6 = 10 and 5 + 10 = 15. In the same way sum(100) gives 5050. This result is confirmed by Gauss's formula n(n + 1)/2: 100 · 101 / 2 = 5050.
This method has a weak point. The base case is only n == 1. When it is called with sum(0) or a negative number, n never becomes 1: it decreases forever as 0, −1, −2, … The result is infinite recursion, and the program stops with a StackOverflowError. In the safe version the base case is if (n <= 0) return 0;. This version also catches invalid inputs, and for sum(1) it correctly gives 1 + 0 = 1.
The sum method with the safe base case expands as follows for sum(3):
sum(3): 3 ≤ 0 is false;3 + sum(2)is pending.sum(2):2 + sum(1)is pending.sum(1):1 + sum(0)is pending.sum(0): 0 ≤ 0 is true; base case, returns 0.- On the way back, 1 + 0 = 1, 2 + 1 = 3 and 3 + 3 = 6 are computed. The result is 6.
This is one call more than the old version (four calls), but it never falls into infinite recursion for any input. sum(-5) returns 0 directly.
3.5.3Sequences
Many number sequences are defined by a rule that computes each term from the earlier terms. Such a rule is called a recurrence relation. A recurrence translates almost word for word into a recursive method: the initial values become the base cases and the relation itself becomes the recursive step. This section treats four sequences. In the Fibonacci and Lucas sequences the method calls itself twice. In the Catalan and Bell sequences the calls are made inside a loop.
3.5.3.1The Fibonacci sequence
The Fibonacci sequence starts with 0, followed by 1: F(0) = 0, F(1) = 1. Every later term is the sum of the previous two: F(n) = F(n − 1) + F(n − 2).
The sequence is named after the Italian mathematician Leonardo Fibonacci. In his book Liber Abaci, written in 1202, he poses a problem about the breeding of rabbits. Every pair of rabbits bears a new pair each month once it is two months old; how many pairs are there at the end of a year? The number of pairs month by month follows this sequence. The first thirteen terms are given in Table 3.5.3.
| n | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| F(n) | 0 | 1 | 1 | 2 | 3 | 5 | 8 | 13 | 21 | 34 | 55 | 89 | 144 |
The ratio of two consecutive terms approaches the golden ratio (≈ 1.618) as n grows: 144 / 89 ≈ 1.6180. The definition is easy to translate into Java:
int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}The base case is n <= 1, which covers both initial values in one line: if n is 0 the method returns 0, and if it is 1 it returns 1. In other words, the answer is n itself. In the recursive step the method calls itself twice. In factorial the calls form a straight chain; here every call splits into two branches and the calls form a tree. This kind of recursion is called tree recursion.
3.5.3.2The call tree of fibonacci(4)
In tree recursion the order of the calls matters. Java evaluates an expression from left to right. In the expression fibonacci(n - 1) + fibonacci(n - 2), the left term is computed completely first. The call for the right term is made only after all the subcalls of the left term have finished. The tree is therefore traversed by going down to the bottom of the leftmost branch and then moving to the right.
| Order | Call | Depth | Event | Returns |
|---|---|---|---|---|
| 1 | fib(4) | 1 | fib(3) for the left term | 3 |
| 2 | fib(3) | 2 | fib(2) for the left term | 2 |
| 3 | fib(2) | 3 | fib(1) for the left term | 1 |
| 4 | fib(1) | 4 | base case | 1 |
| 5 | fib(0) | 4 | base case; fib(2) = 1 + 0 | 0 |
| 6 | fib(1) | 3 | base case; fib(3) = 1 + 1 | 1 |
| 7 | fib(2) | 2 | recomputed; fib(1) for the left term | 1 |
| 8 | fib(1) | 3 | base case | 1 |
| 9 | fib(0) | 3 | base case; fib(2) = 1 + 0, fib(4) = 2 + 1 | 0 |
Table 3.5.4 lists the nine calls in the order they are made. The stack never goes deeper than four fibonacci frames, because the longest branch is 4 → 3 → 2 → 1. But the total number of calls is 9, and fib(2) is computed twice, fib(1) three times and fib(0) twice. Figure 3.5.4 shows two moments of the tree: at the top the moment when the descent first reaches the bottom, and at the bottom the final state in which all calls have returned a value.
fibonacci(4). Top: the fourth call; the left arm has descended to fib(1), the three frames above it wait on the stack, and the nodes on the right have not been called yet. Bottom: the final state; all nine nodes have returned a value and fib(4) = 3.The repeated computation looks harmless for small n. But the size of the tree grows quickly with n. The number of calls T(n) made by fibonacci(n) satisfies the relation T(n) = 1 + T(n − 1) + T(n − 2), and T(n) = 2F(n + 1) − 1. fibonacci(5) makes 15 calls, fibonacci(10) makes 177 and fibonacci(40) makes 331,160,281. The tree widens by a factor of about 1.6 at every level, and the same subtrees are built again and again.
3.5.3.3The Lucas sequence
The Lucas sequence uses the same relation as Fibonacci with different initial values. It is named after the French mathematician Édouard Lucas.
The Lucas sequence starts with 2, followed by 1: L(0) = 2, L(1) = 1. Later terms are computed as in Fibonacci: L(n) = L(n − 1) + L(n − 2).
int lucas(int n) {
if (n == 0) {
return 2;
} else if (n == 1) {
return 1;
} else {
return lucas(n - 1) + lucas(n - 2);
}
}In Fibonacci the two initial values could be handled in one line with return n;, because F(0) = 0 and F(1) = 1. In Lucas, L(0) = 2, so this shortcut does not exist and two separate base cases are needed. The else if chain tests n == 0 first and then n == 1; if neither holds, the recursive step runs.
| n | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| L(n) | 2 | 1 | 3 | 4 | 7 | 11 | 18 | 29 | 47 | 76 | 123 |
The two sequences are linked: L(n) = F(n − 1) + F(n + 1). For example, L(5) = F(4) + F(6) = 3 + 8 = 11. The call tree of Lucas has the same shape as that of Fibonacci, because the base cases are again at n = 0 and n = 1. So lucas(5) also makes 15 calls.
3.5.3.4The Catalan sequence
Catalan numbers are the answer to many counting problems. The sequence is named after the Belgian mathematician Eugène Catalan.
The Catalan sequence starts with 1: C(0) = 1, C(1) = 1. Its closed formula is C(n) = (2n)! / ((n + 1)! · n!). Its recursive formula is C(n) = Σ C(i) · C(n − 1 − i), where the sum runs from i = 0 to n − 1.
In the recursive formula a term is built from all the smaller terms. The Java code computes this sum with a for loop and makes the recursive calls inside the loop:
long catalan(int n) {
if (n <= 1) {
return 1;
}
long result = 0;
for (int i = 0; i < n; i++) {
result += catalan(i) * catalan(n - i - 1);
}
return result;
}The return type is long, because Catalan numbers grow quickly. result starts at 0, the identity element of addition. The loop advances i from 0 to n - 1 and in each round adds the product catalan(i) * catalan(n - i - 1) to the sum. For example, C(3) is computed as follows:
The closed formula gives the same result: 6! / (4! · 3!) = 720 / 144 = 5. The first nine terms of the sequence are 1, 1, 2, 5, 14, 42, 132, 429, 1430; running the code produces these values.
What do Catalan numbers count? The best-known answer is the number of correct arrangements of n pairs of parentheses. In a correct arrangement every opening parenthesis is closed later, and at no point does the number of closing parentheses exceed the number of opening ones. For n = 3 there are five arrangements: ((())), (()()), (())(), ()(()), ()()(). The same number also gives the number of ways to parenthesize a product of n + 1 numbers and the number of distinct binary trees with n nodes.
The cost of this method grows even faster than Fibonacci's. Every catalan(n) calls all smaller terms twice and stores no result. The measured call counts for n = 2, 3, 4, 5, 6 are 5, 15, 45, 135, 405; whenever n increases by 1, the number of calls triples. A method like this is short and clear for small n, but for large n it needs memoization.
3.5.3.5The Bell sequence
The Bell sequence starts with 1: B(0) = 1, B(1) = 1. The general formula is B(n) = Σ C(n − 1, k) · B(k), where the sum runs from k = 0 to n − 1. Here C(n, k) is the number of ways to choose k elements out of n, that is, the binomial coefficient.
int bell(int n) {
if (n == 0) { return 1; }
int count = 0;
for (int k = 0; k < n; k++) {
count += choose(n - 1, k) * bell(k);
}
return count;
}
int choose(int n, int k) { // C(n, k)
return factorial(n) / (factorial(k) * factorial(n - k));
}The code consists of two methods. bell calls itself inside a loop as in Catalan, multiplying each term by the binomial coefficient and adding them up. choose computes the formula C(n, k) = n! / (k! · (n − k)!) with the factorial method. Here one method calls both itself and another recursive method.
Bell numbers count in how many different ways a set of n elements can be divided into groups. For the set {a, b, c} there are five ways: one group abc; three ways with one element alone and the other two together, a|bc, b|ac, c|ab; and every element alone, a|b|c. Indeed B(3) = 5. The first eight terms of the sequence are 1, 1, 2, 5, 15, 52, 203, 877.
In this code overflow comes from two separate places. choose uses the factorial that returns int, and 13! does not fit in an int. bell(14) goes wrong because it calls choose(13, k). bell(13) = 27,644,437 comes out correctly, but bell(14) gives 77,914,768; the correct value is 190,899,322. So the code is correct only for n ≤ 13. Even if factorial were fixed, B(16) = 10,480,142,147 would still not fit, because the result is an int.
Computing a binomial coefficient as a quotient of factorials. Even when C(n, k) is a small number, the intermediate n! is huge and overflows. A safer way is to use the relation C(n, k) = C(n − 1, k − 1) + C(n − 1, k) (Pascal's triangle) or a loop that multiplies and divides immediately.
3.5.4Writing a recursive method
Reading a recursive method is easier than writing one. Writing requires obeying two rules and approaching the problem from a particular point of view. This section covers the two rules first, then the error that arises when the rules are broken, and finally the steps of thinking about a problem recursively.
3.5.4.1Two basic rules
Rule 1, base case: the method has at least one base case that ends without calling itself. Rule 2, progress: every recursive call moves toward a base case; the parameter decreases (or increases) on each call, the string gets shorter, the range gets narrower. If both rules hold, the recursion stops after a finite number of calls for every input.
What progress means is made concrete by a measure called the "distance to the base case". In factorial this measure is n itself: it decreases by 1 on every call and the recursion stops when it reaches 1 (Figure 3.5.5). In digit sum the measure is the number of digits, in the palindrome test the length of the string, and in Euclid's algorithm the second parameter. If the measure is a natural number and strictly decreases on every call, it cannot decrease forever; eventually the base case is reached.
factorial(4) reduces n by one on each call: 4, 3, 2, 1. n = 1 is the base case and no new call is made.The two most frequent errors are violations of these rules. In infinite recursion the base case is either missing or can never be reached. In insufficient progress the parameter does not change; for example, return n * factorial(n); has been written. The result of both errors is the same: StackOverflowError.
Three habits can be added to the rules. First, every recursive call focuses on a smaller subset of the problem. Second, the base case is always tested before the recursive call; if the call is made first, the stack fills up before the test ever gets its turn. Third, all possible inputs are taken into account. Ask whether a negative number, 0, an empty string or Integer.MIN_VALUE reaches the base case.
3.5.4.2Infinite recursion
It is instructive to see what infinite recursion looks like in a complete program. The program below calls sum, whose base case is only n == 1, with 0:
public class Sum {
static int sum(int n) {
if (n == 1) {
return 1;
} else {
return n + sum(n - 1); // line 6
}
}
public static void main(String[] args) {
System.out.println(sum(0));
}
}The program compiles; the compiler gives no warning. When it is run, after a while it stops with this message:
Exception in thread "main" java.lang.StackOverflowError
at Sum.sum(Sum.java:6)
at Sum.sum(Sum.java:6)
at Sum.sum(Sum.java:6)
...Stack overflow is the call stack filling up in a very deep or infinite recursion. The Java Virtual Machine (JVM) then throws java.lang.StackOverflowError, and if it is not caught the program stops.
Let us follow what happens step by step. main calls sum(0). For n = 0, 0 == 1 is false, and a new call is made to compute 0 + sum(-1). n = -1 is not 1 either; -1 + sum(-2) is pending. On every call n moves a little further from the base case. Every call adds a new frame to the stack and none of them can return, because each waits for the result of the next. After a thousand calls the stack holds 1001 frames and there is still no error. Finally the memory reserved for the stack runs out (Figure 3.5.6).
sum(0). On the left two frames, in the middle 1001 frames, on the right the stack limit has been reached and overflow has occurred. In the measurement shown, the limit was exceeded at ≈ 10,200 calls; the number varies with the JVM settings.The number of calls after which overflow occurs is not fixed. It depends on the size of the stack, the size of the frame and whether the JVM is currently interpreting the code. In five measurements with JDK 21 on Windows with default settings, overflow occurred between 18,487 and 18,822 calls. When the stack was halved with the -Xss512k option, the depth dropped to 6,235. When the same test was repeated within the same JVM, as many as 41,480 calls were possible because the frames of compiled code are smaller. In conclusion, a depth of a few tens of thousands of calls with the default stack is beyond the safe limit.
This error has two important properties. First, the compiler does not catch it; the problem appears only at run time. The compiler sees that every path ends with a return and accepts the method as valid; it cannot know whether the values will ever reach the base case. Second, the stack trace below the error message gives a familiar picture: the same line (Sum.java:6) is repeated hundreds of times one below the other. The JVM prints at most 1024 lines of the stack trace. The same line appearing again and again is the sign of infinite recursion.
The fix is one of three. The base case is widened (n <= 1 or n <= 0). The input is checked at the start of the method and an exception is thrown if it is invalid. If the problem is inherently very deep, for example walking a list of a million items, a loop is used instead of recursion.
Catching StackOverflowError with try-catch and carrying on. StackOverflowError is not an Exception but an Error; it signals that the program has a bug that must be fixed. Catching it does not prevent the overflow, it only hides the symptom. The right fix is to correct the base case or the progress.
3.5.4.3Thinking recursively
Four steps are followed when writing a recursive method:
- Reduce: express the problem in terms of a smaller copy of itself.
- Base case: find the smallest input whose answer is known directly.
- Trust: assume the smaller copy is solved correctly; do not unfold the inside of the call in your head.
- Combine: build the larger answer from the smaller one.
The third step is the hardest and is known as the leap of faith. When beginners see a recursive call, they try to step into it and unfold the whole chain in their heads. In small examples this works, but in examples such as the Towers of Hanoi it quickly becomes unmanageable. The trust step says this: if, assuming the method works correctly for n − 1, one can show that it also works for n, then the method is correct for every n. This is exactly mathematical induction. The base case is the base step of the induction and the recursive step is the inductive step.
The number of digits of a number is found in four steps. Reduce: the number of digits of 48729 is 1 more than the number of digits of 4872. 4872 is obtained from 48729 by dropping the last digit, that is, by the integer division 48729 / 10. Base case: a one-digit number (n < 10) has 1 digit. Trust: assume that countDigits(4872) returns 4. Combine: the result is 1 + 4 = 5.
int countDigits(int n) {
if (n < 10) { // base case
return 1;
}
return 1 + countDigits(n / 10); // reduce + combine
}countDigits(48729) returns 5, and countDigits(7) returns 1 directly. The calls proceed as 48729 → 4872 → 487 → 48 → 4; the last of the five calls is the base case. The code has no else. Because the base case ends with return, the next line is reached only when n >= 10. This style is common in recursive methods: the base case is filtered out first and the remaining body handles the general case.
Note that the method gives wrong results for negative numbers. For −45, -45 < 10 is true and the result is 1, which is wrong. If negative inputs matter, a sign correction is added at the beginning of the method. How this correction is done can be seen in the digit sum example.
3.5.4.4Work done on the way down and on the way back
In a recursive method, work can be done in two places: before the method calls itself or after the call returns. The difference is especially clear when the order of the work is visible, as with printing. The two methods below differ only in the order of two lines:
static void write(int n) {
if (n == 0) return;
System.out.print(n + " ");
write(n - 1);
}
static void write2(int n) {
if (n == 0) return;
write2(n - 1);
System.out.print(n + " ");
}
static int mystery(int a, int b) {
if (b == 0) return 0;
return a + mystery(a, b - 1);
}write(3) prints the number and then calls itself. The printing happens on the way down and the output is 3 2 1. write2(3) calls itself first and leaves the printing for the way back. write2(3) calls write2(2), which calls write2(1), which calls write2(0). write2(0) returns without printing anything. Then the deepest frame, write2(1), prints 1, next write2(2) prints 2, and finally write2(3) prints 3. The output is 1 2 3.
| Moment | Top of stack | write screen | write2 screen |
|---|---|---|---|
| descent | n = 3 | 3 | |
| descent | n = 2 | 3 2 | |
| descent | n = 1 | 3 2 1 | |
| bottom | n = 0 | 3 2 1 | |
| ascent | n = 1 | 3 2 1 | 1 |
| ascent | n = 2 | 3 2 1 | 1 2 |
| ascent | n = 3 | 3 2 1 | 1 2 3 |
The same code contains a third method, mystery. mystery(4, 3) expands as follows: 4 + mystery(4, 2) = 4 + 4 + mystery(4, 1) = 4 + 4 + 4 + mystery(4, 0) = 4 + 4 + 4 + 0 = 12. The method computes a × b by adding a to itself b times. The base case is b == 0 and progress comes from b decreasing by 1. But in the call mystery(4, -1), b decreases as −1, −2, … and never becomes 0. The result is again a StackOverflowError. The second rule requires progress to be in the direction of the base case; merely "changing" is not enough.
Work done on the way back is one of the strongest features of recursion. Printing the binary representation of a number is a nice example. The remainders (n % 2) are found starting from the lowest digit, but they must be printed starting from the highest. A method that prints on the way back does this reversal by itself:
static void toBinary(int n) {
if (n > 1) {
toBinary(n / 2);
}
System.out.print(n % 2);
}toBinary(13) descends 13 → 6 → 3 → 1. At the bottom, toBinary(1) prints 1 % 2 = 1. On the way back, 3 % 2 = 1, 6 % 2 = 0 and 13 % 2 = 1 are printed in turn. The output is 1101: 13 = 8 + 4 + 1. To do the same job with a loop, one would have to collect the remainders in an array and print them in reverse order. Here the call stack does the work of that array.
3.5.5Examples
The four examples in this section show different faces of recursion. In the digit sum the problem shrinks by the digits of the number. In the palindrome test the string gets shorter from both ends and there are two separate base cases. In Euclid's algorithm no work is done on the way back. In the Towers of Hanoi the method calls itself twice, and a problem that is hard to write with a loop shrinks to a few lines.
3.5.5.1Digit sum
The sum of the digits of an integer, for example 4 + 8 + 7 + 2 + 9 = 30 for 48729, is found recursively as follows:
int digitSum(int n) {
if (n < 0) {
return digitSum(-n);
} else if (n < 10) {
return n;
} else {
return digitSum(n / 10) + (n % 10);
}
}The method has three branches. The second and third lines handle a negative number: the sign is flipped and the same method is called again with the positive number. The sum of the digits does not depend on the sign; the digits of −48729 are also 4, 8, 7, 2, 9. The fourth and fifth lines are the base case: the digit sum of a one-digit number is the number itself. The last branch is the general case: the last digit is added to the sum of the remaining digits.
n / 10 = 4872 is processed recursively, and n % 10 = 9 is the last digit.The split is done with two integer operations (Figure 3.5.7). Because n / 10 is a division between integers, it discards the fractional part and gives the number with its last digit removed: 48729 / 10 = 4872. n % 10 gives the remainder of the division by 10, that is, the last digit: 48729 % 10 = 9. On every call the number gets one digit shorter; progress is guaranteed. The expansion looks like this:
digitSum(-48729)
= digitSum(48729)
= digitSum(4872) + 9
= (digitSum(487) + 2) + 9
= ((digitSum(48) + 7) + 2) + 9
= (((digitSum(4) + 8) + 7) + 2) + 9
= (((4 + 8) + 7) + 2) + 9
= ((12 + 7) + 2) + 9
= (19 + 2) + 9
= 21 + 9
= 30The first call only corrects the sign. In each following step the last digit (9, 2, 7, 8) is left behind as a pending addition. The base case is digitSum(4) → 4. On the way back the sums are made from the inside out: 4 + 8 = 12, 12 + 7 = 19, 19 + 2 = 21, 21 + 9 = 30. Six calls are made in total: one sign correction and five digits. In general, a number with d digits takes d calls (d + 1 if it is negative); the time and memory are O(d).
A shorter example, digitSum(-357), is traced together with the call stack in Table 3.5.7. For brevity the method name is written as r.
static int digitSum(int n) {
if (n < 0) {
return digitSum(-n);
} else if (n < 10) {
return n;
} else {
return digitSum(n / 10) + (n % 10);
}
}
public static void main(String[] args) {
System.out.println(digitSum(-357));
}| Step | Call at the top | Branch taken | Pending work / returned value |
|---|---|---|---|
| 1 | r(-357) | n < 0 | calls r(357); will return its result unchanged |
| 2 | r(357) | general case | waits for r(35) + 7 |
| 3 | r(35) | general case | waits for r(3) + 5 |
| 4 | r(3) | n < 10 | base case, returns 3 |
| 5 | r(35) | return | returns 3 + 5 = 8 |
| 6 | r(357) | return | returns 8 + 7 = 15 |
| 7 | r(-357) | return | returns 15 unchanged |
| 8 | main | — | prints 15 |
digitSum(-357) call chain. r(3) is the base case; the frames above it wait for r(357), r(35) + 7 and r(3) + 5 respectively.Four calls are made: one sign correction and three digits. The result is 3 + 5 + 7 = 15 (Figure 3.5.8).
Assuming that negating a number always gives a positive number. The smallest int value, Integer.MIN_VALUE = −2,147,483,648, has no positive counterpart, because +2,147,483,648 does not fit in an int. In Java, -Integer.MIN_VALUE again gives −2,147,483,648. For this reason digitSum(Integer.MIN_VALUE) enters the first branch again and again and ends with a StackOverflowError. Math.abs(Integer.MIN_VALUE) likewise returns a negative number. This single value must be handled separately, or the computation must be done with long.
3.5.5.2Palindrome check
A palindrome is a string that reads the same backward as forward: "kayak", "abba", "ey edip adanada pide ye".
Whether a string is a palindrome can be decided by looking from the outside in. If the first and last characters are equal, then after removing these two characters the remaining string must also be a palindrome (Figure 3.5.9). This is a recursive definition:
static boolean isPalindrome(String s) {
if (s.length() <= 1) {
return true;
} else if (s.charAt(0) == s.charAt(s.length() - 1)) {
return isPalindrome(s.substring(1, s.length() - 1));
}
return false;
}The code uses two String methods. s.charAt(i) returns the character at index i of the string; indices start at 0 and the index of the last character is s.length() - 1. s.substring(1, s.length() - 1) returns the part that starts at index 1 and ends just before index s.length() - 1; that is, the string with its first and last letters removed. The second parameter of substring is not included in the part.
The method has two base cases. If the length is 1 or 0, the string is a palindrome and true is returned. The empty string occurs with even-length palindromes: "abba" → "bb" → "" shrinks that way. If the ends differ, the string is not a palindrome and false is returned; there is no need to look inside. This second base case is covered by the final line return false; when neither the if nor the else if holds.
| Input | Call chain | Result |
|---|---|---|
"kayak" | "kayak" → "aya" → "y" | true |
"abba" | "abba" → "bb" → "" | true |
"java" | "java": j ≠ a | false |
"Kayak" | "Kayak": K ≠ k | false |
The last row shows an important detail: the comparison is case-sensitive. 'K' and 'k' are different characters, and "Kayak" is not counted as a palindrome. "ey edip adanada pide ye", on the other hand, gives true because it is symmetric including its spaces. For sentences containing spaces and punctuation, these characters must first be removed and the letters lowercased.
The calls made for the word "racecar" are traced in Table 3.5.9.
| Call | s | Length | Ends | Next call / return |
|---|---|---|---|---|
| 1 | "racecar" | 7 | 'r' = 'r' | s.substring(1, 6) = "aceca" |
| 2 | "aceca" | 5 | 'a' = 'a' | s.substring(1, 4) = "cec" |
| 3 | "cec" | 3 | 'c' = 'c' | s.substring(1, 2) = "e" |
| 4 | "e" | 1 | — | base case: returns true |
The fourth call is the base case (Figure 3.5.10). On the way back each frame passes the true it receives upward unchanged; there is no other work to do on the way back. Result: "racecar" is a palindrome.
In terms of cost this method is more expensive than it first appears. For a string of length n about n/2 calls are made. But the substring in each call creates a new string object in Java and copies the characters. The total number of characters copied is (n − 2) + (n − 4) + … ≈ n²/4. So the time is O(n²), and the memory is also O(n²) because of the pending strings. A version that carries two indices instead of the string, for example isPalindrome(s, lo, hi), avoids this copying and runs in O(n) time.
The indexed version looks like this:
static boolean isPalindrome(String s, int lo, int hi) {
if (lo >= hi) {
return true;
} else if (s.charAt(lo) != s.charAt(hi)) {
return false;
}
return isPalindrome(s, lo + 1, hi - 1);
}The string never gets shorter; instead the bounds of the part being examined narrow. lo is the index of the first character of the part and hi the index of its last. The first call is made as isPalindrome(s, 0, s.length() - 1). The base cases follow the same logic. If lo >= hi, at most one character is left in the part and the result is true. If the ends differ, the result is false. Progress comes from the two indices approaching each other: the gap shrinks by 2 on every call. For "racecar" the calls are (0, 6), (1, 5), (2, 4), (3, 3), and the fourth call is the base case. For the empty string the first call is (0, −1) and it returns true immediately. This technique is common in recursive methods that work on strings and arrays: instead of copying the data, carry the bounds as parameters.
3.5.5.3Greatest common divisor
The greatest common divisor (GCD) of two positive integers is the largest number that divides both without a remainder. In the code the method is called gcd after its initials. Euclid's algorithm, about 2300 years old, finds the GCD with division remainders:
static int gcd(int x, int y) {
if (y == 0) {
return x;
}
return gcd(y, x % y);
}The base case is y == 0: the GCD of a number and 0 is the number itself. In the general case y takes the place of x and x % y takes the place of y. The correctness of the relation rests on this: every number that divides both x and y also divides x − k·y, and therefore also divides x mod y. The set of common divisors stays the same at every step; only the numbers get smaller.
Progress comes from the remainder getting smaller. x mod y is always smaller than y; the second parameter strictly decreases on every call and finally reaches 0. The order of the parameters does not matter either. In the call gcd(93, 444), since 93 % 444 = 93, the first step only swaps the two numbers and gives gcd(444, 93).
gcd(444, 93)
= gcd(93, 72) // 444 % 93 = 72
= gcd(72, 21) // 93 % 72 = 21
= gcd(21, 9) // 72 % 21 = 9
= gcd(9, 3) // 21 % 9 = 3
= gcd(3, 0) // 9 % 3 = 0
= 3| Call | x | y | x % y | Event |
|---|---|---|---|---|
gcd(444, 93) | 444 | 93 | 72 | 444 = 4 · 93 + 72 |
gcd(93, 72) | 93 | 72 | 21 | 93 = 1 · 72 + 21 |
gcd(72, 21) | 72 | 21 | 9 | 72 = 3 · 21 + 9 |
gcd(21, 9) | 21 | 9 | 3 | 21 = 2 · 9 + 3 |
gcd(9, 3) | 9 | 3 | 0 | 9 = 3 · 3 + 0 |
gcd(3, 0) | 3 | 0 | — | base case: returns 3 |
Six calls are made and gcd(444, 93) = 3 is found (Table 3.5.10). This method differs from the earlier ones on the way back. In the line return gcd(y, x % y); there is no work left to do after the call returns. The 3 found by the last call passes unchanged through every frame and reaches main. Such calls are called tail calls. Another example: gcd(48, 18) → gcd(18, 12) → gcd(12, 6) → gcd(6, 0) → 6.
Euclid's algorithm is very fast. In every two steps the first number at least halves; so the number of calls is proportional to the number of digits of the numbers, that is, O(log min(x, y)). The worst case occurs with two consecutive Fibonacci numbers; for example gcd(89, 55) makes ten calls.
3.5.5.4Towers of Hanoi
The Towers of Hanoi is a puzzle introduced by Édouard Lucas in 1883. There are three pegs (A, B, C), and peg A holds n disks stacked from largest to smallest. All the disks are to be moved to C. There are two rules: on each move only one disk, the topmost disk of a peg, is moved; and a larger disk is never placed on top of a smaller one.
The puzzle is hard when thought of with loops, but when thought of recursively the solution appears by itself. The largest disk can be moved to C only when the n − 1 disks above it have been moved somewhere else, that is, to the auxiliary peg B. So the solution has three steps: move the top n − 1 disks to the auxiliary peg, move the largest disk to the target, then move the n − 1 disks from the auxiliary peg to the target. The first and third steps are the same problem with one disk fewer. The base case is a single disk: it is moved directly.
public class TowersOfHanoi {
static void solve(int n, char from,
char to, char via) {
if (n == 1) { // one disk: move it
System.out.println(n + ": " + from + "->" + to);
} else {
solve(n - 1, from, via, to);
System.out.println(n + ": " + from + "->" + to);
solve(n - 1, via, to, from);
}
}
public static void main(String[] args) {
solve(3, 'A', 'C', 'B');
}
}1: A->C
2: A->B
1: C->B
3: A->C
1: B->A
2: B->C
1: A->CThe solve method takes four parameters: the number of disks and the names of the source, target and auxiliary pegs. The peg names are of type char. In the recursive calls the roles of the pegs change. In the first call, solve(n - 1, from, via, to) is written: n − 1 disks are moved from the source to the auxiliary peg, and during this the real target plays the role of the auxiliary. In the call on the third line, solve(n - 1, via, to, from) is written: n − 1 disks are moved from the auxiliary peg to the target, and this time the source, being empty, serves as the auxiliary. The number in the printed line is the number of the disk being moved; the smallest disk is 1.
solve(3, 'A', 'C', 'B'): the initial state and the state after each of the seven moves (left to right, top to bottom). After the third move the top two disks are on B; the fourth move carries the largest disk to C.| Move | Output | Printing call | Meaning |
|---|---|---|---|
| 1 | 1: A->C | solve(1, A, C, B) | base case |
| 2 | 2: A->B | solve(2, A, B, C) | disk 2 to the auxiliary peg |
| 3 | 1: C->B | solve(1, C, B, A) | the top 2 disks are now on B |
| 4 | 3: A->C | solve(3, A, C, B) | largest disk to the target |
| 5 | 1: B->A | solve(1, B, A, C) | the 2 disks start moving to C |
| 6 | 2: B->C | solve(2, B, C, A) | disk 2 onto disk 3 |
| 7 | 1: A->C | solve(1, A, C, B) | puzzle solved |
The moves are given in Table 3.5.11 together with the call that makes each. The first three moves are the work of solve(2, A, B, C); the fourth move is the middle line of solve(3, …); the last three moves are the work of solve(2, B, C, A) (Figure 3.5.11). The call stack never goes deeper than three solve frames; the stack depth equals the number of disks.
The Towers of Hanoi with n disks can be solved in at least 2n − 1 moves, and the solve method makes exactly that many moves.
The number of moves H(n) can be read off the structure of the method: two solutions for n − 1 disks and one move. H(n) = 2 · H(n − 1) + 1 and H(1) = 1. From this H(2) = 3, H(3) = 7, H(4) = 15, and in general H(n) = 2n − 1. This number grows very fast. For 10 disks 1023 moves are needed. For the 64 disks of the legend, 264 − 1 ≈ 1.8 × 1019 moves are needed; at one move per second this takes about 585 billion years. The running time of the method is also O(2n), but this time nothing is wasted: every move is necessary and no shorter solution exists.
An interesting property of the puzzle is that the first move depends on the number of disks. The measured first moves are 1: A->C when n is odd and 1: A->B when n is even. For example, for 4 disks 15 moves are made and the first move carries the smallest disk to the auxiliary peg. Solutions of Hanoi written with loops rely on observations of this kind and are much longer than the recursive version. The recursive version is only a few lines because it mirrors the structure of the problem as it is.
3.5.6Efficiency
A recursive solution can be short and clear, but that does not mean it is fast or light. This section gathers the price of recursion under three headings: the cost of each call, the stack depth and the repeated computation of the same values. It then shows how recursive methods are converted into loops.
3.5.6.1The cost of one call
On every method call the JVM does some work: a new frame is opened, the parameters are copied, and the return address is recorded. On return the frame is removed and the value is carried to the frame below. In a loop iteration, on the other hand, only a few variables are updated. For this reason a recursive method doing the same job is usually a little slower than a loop.
The more important difference is in memory. As the recursive calls are made, the pending partial results, that is, the half-finished work such as 4 * ? in each frame, accumulate on the call stack. Table 3.5.12 summarizes the three main costs.
| Cost | Description | Example |
|---|---|---|
| Memory | Every pending call holds a frame. | factorial(n): n frames, O(n) memory; O(1) with a loop. |
| Depth limit | When the stack is full, a StackOverflowError occurs. | After a depth of a few tens of thousands of calls with the default stack. |
| Repetition | Tree recursion may compute the same value many times. | fibonacci(40): 331,160,281 calls. |
An iterative solution is one that does the repetition with a loop instead of recursion. It does not pile up partial results on the stack; it keeps them in an accumulator variable and runs in a single frame.
In problematic cases the remedy is to switch to the iterative version. Factorial is the simplest example: factorial(100000) in the recursive version, overflow of the result aside, most likely ends with a StackOverflowError. In a trial with JDK 21 this is indeed what happened. The loop version finishes the same call in a single frame and in under a second; although its result is wrong, it never suffers a stack overflow.
3.5.6.2Repeated computation
The real problem of tree recursion is not memory but time. Figure 3.5.12 shows the call tree of fibonacci(5). The tree has 15 nodes. The red nodes are recomputations of values that were already computed: fib(3) is computed twice and fib(2) three times.
fibonacci(5): 15 calls. The red nodes are recomputations of values that were already computed.The repetition grows exponentially as n increases. The number of calls is given by the formula T(n) = 2F(n + 1) − 1 and increases by a factor of about 1.6 whenever n goes up by 1; this ratio is the golden ratio. Table 3.5.13 gives the call counts and times measured with JDK 21.
| n | Number of calls | F(n) | Measured time |
|---|---|---|---|
| 10 | 177 | 55 | < 0.1 ms |
| 20 | 21,891 | 6,765 | ≈ 0.3 ms |
| 30 | 2,692,537 | 832,040 | ≈ 5 ms |
| 40 | 331.160.281 | 102.334.155 | ≈ 0,5 s |
| 45 | 3.672.623.805 | 1.134.903.170 | ≈ 11 s |
In the table, every ten steps multiply the number of calls by about 120. fibonacci(40) takes half a second. At this rate fibonacci(50) reaches two minutes; that is, it takes minutes. One more Java-specific problem is added to this code: F(47) = 2,971,215,073 exceeds the limit of int. After running for two minutes, fibonacci(50) returning int returns a meaningless number such as −298632863. The correct value is 12,586,269,025.
The source of the problem is that the method forgets the values it has already computed. The number of distinct values fibonacci(40) needs is only 41 (from F(0) to F(40)). If each were computed once and stored, a few dozen operations would be enough. There are two ways to do this: converting to a loop and memoization.
3.5.6.3Converting to a loop
Linearly recursive methods, that is, methods that call themselves once, can usually be converted into loops easily. The method is this: the work done on the way back is done in the loop with an accumulator variable. The two versions of factorial side by side look like this:
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}int factorial(int n) {
int product = 1;
for (int i = 1; i <= n; i++) {
product *= i;
}
return product;
}In the loop version product starts at 1, the identity element of multiplication. The loop advances i from 1 to n and in each round multiplies product by i. For factorial(5) product takes the values 1, 1, 2, 6, 24, 120. For n = 0 the loop never runs and 1 is returned; 0! = 1 is covered without needing to be written separately. The two versions give the same result, but their memory use differs (Figure 3.5.13). Both versions assume n ≥ 0. For a negative n the recursive version never reaches the base case and throws StackOverflowError; the loop version never enters the loop and silently returns 1. Also, 13! = 6,227,020,800 does not fit in an int; the int versions are correct only up to 12!.
factorial(5) opens five frames; the loop version updates the variable product in a single frame.Digit sum and palindrome are converted into loops in the same way:
int digitSum(int n) {
int sum = 0;
int rest = Math.abs(n);
while (rest > 0) {
sum += rest % 10;
rest /= 10;
}
return sum;
}rest starts with the absolute value of the number. In each round the last digit is added to sum and removed from rest. For 48729 sum goes 9, 11, 18, 26, 30; rest goes 4872, 487, 48, 4, 0 and the loop ends. digitSum(-48729) returns 30, the same as the recursive version. The sign is removed with Math.abs, because the sum of digits cannot be negative. This version does not suffer a stack overflow for Integer.MIN_VALUE, but because Math.abs returns a negative value it never enters the loop and gives 0; the correct answer is 47.
boolean isPalindrome(String s) {
s = s.toLowerCase();
int len = s.length();
for (int i = 0; i < len / 2; i++) {
if (s.charAt(i) != s.charAt(len - 1 - i)) {
return false;
}
}
return true;
}The loop palindrome uses indices that move inward from both ends instead of shortening the string. i advances from the start and len - 1 - i from the end. The loop runs up to half the string; for an odd length the middle character matches itself and is not examined. It returns false at the first differing pair. If no differing pair is found, the loop ends and true is returned. Because this version calls toLowerCase() at the start, it counts "Kayak" as a palindrome too. In real programs toLowerCase(Locale.ROOT) should be preferred: if the default locale is tr, the letter I is converted not to i but to ı.
The trace for "Kepek" is given in Table 3.5.14.
static boolean isPalindrome(String s) {
s = s.toLowerCase();
int len = s.length();
for (int i = 0; i < len / 2; i++) {
if (s.charAt(i) != s.charAt(len - 1 - i)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
System.out.println(isPalindrome("Kepek"));
}| Step | s | len | i | Comparison | Result |
|---|---|---|---|---|---|
| 1 | "Kepek" | — | — | — | parameter |
| 2 | "kepek" | — | — | — | toLowerCase() returns a new string |
| 3 | "kepek" | 5 | — | — | loop bound 5 / 2 = 2 |
| 4 | "kepek" | 5 | 0 | s.charAt(0) 'k', s.charAt(4) 'k' | equal |
| 5 | "kepek" | 5 | 1 | s.charAt(1) 'e', s.charAt(3) 'e' | equal |
| 6 | "kepek" | 5 | 2 | 2 < 2 is false | loop ends |
| 7 | "kepek" | 5 | — | — | returns true and is printed |
i = 0: index 0 from the start, index 5 − 1 − 0 = 4 from the end. Both characters are 'k'.The 'p' in the middle is never compared; that it matches itself is certain anyway (Figure 3.5.14). A single frame is used, and, unlike the recursive version, a new string is not produced at every step. The time is O(n), and the extra memory is O(1) apart from the single copy produced by toLowerCase().
Tree recursion can also be converted into a loop, but this time the accumulator is not a single variable. In Fibonacci each term depends on the previous two terms; the loop carries those two terms:
static long fibonacci(int n) {
long a = 0, b = 1;
for (int i = 0; i < n; i++) {
long next = a + b;
a = b;
b = next;
}
return a;
}a and b are two consecutive Fibonacci numbers, starting with F(0) = 0 and F(1) = 1. In each round both advance one step: the new a becomes the old b, and the new b becomes the old sum. If written without the temporary variable next, the old a would be lost. After n rounds a = F(n). For fibonacci(10) the pair (a, b) goes (0, 1), (1, 1), (1, 2), (2, 3), (3, 5), (5, 8), (8, 13), (13, 21), (21, 34), (34, 55), (55, 89) and 55 is returned. This version runs n rounds: time O(n), memory O(1). It gives fibonacci(50) = 12586269025 and fibonacci(90) instantly. The work the recursive version does with 331 million calls, this loop does in 40 rounds.
Writing the loop bound as i <= len / 2 or i < len. The first form does not change the result but adds a needless round. With the second, every pair is compared twice. The real danger is writing the opposite index as len - i: at i = 0, s.charAt(5) is called and a StringIndexOutOfBoundsException is thrown. The index of the last character is len - 1.
3.5.6.4Recursion or a loop?
The two approaches are two ways of writing the same repetition. Table 3.5.15 summarizes the differences between them.
| Recursion | Loop (iterative) | |
|---|---|---|
| Stopping | Base case | Loop condition |
| Progress | Call with a smaller argument | Updating a counter or variable |
| Memory | One frame per call: O(depth) | Usually O(1) |
| Speed | Cost of calls; repetition in tree recursion | Usually faster |
| Failure | StackOverflowError if there is no base case | Infinite loop if the condition is broken (the program hangs) |
| Readability | Very natural for trees, divide and conquer, Hanoi, sequences | Natural for simple counting and accumulating jobs |
The difference in the failure row is interesting. A broken loop never ends and the program hangs; it has to be stopped from outside. A broken recursion, on the other hand, fills the stack quickly and stops with an error message. For finding the bug the second is easier, because the stack trace shows where the problem is.
Every recursive solution can be written with a loop, and the converse is also true. For linear recursion the conversion is easy with an accumulator. For tree recursions such as Hanoi, however, the loop version has to imitate the work of the call stack with a stack data structure that it maintains itself, and the code gets longer. The choice is made by three criteria. If clarity of the code favors recursion and the depth is small (the number of disks in Hanoi, the height of a balanced tree), recursion is appropriate. If the depth grows linearly with the input (a list of a million items), a loop is chosen. If performance is critical and the tree recursion contains repetition, a loop or memoization is needed.
3.5.7Tail recursion
In recursive methods the memory problem comes from work that waits on the stack to be done on the way back. If no work remains for the way back, the frames need not wait either. Tail recursion is based on this idea.
3.5.7.1The tail call and the accumulator
Tail recursion is recursion in which the last operation of the method is the recursive call itself; no work remains after the call returns. The result is carried in an extra accumulator parameter.
The distinction can be seen in one line. The recursive lines of ordinary factorial and of tail-recursive factorial are as follows:
return n * factorial(n - 1);
// multiply AFTER the call returnsreturn factorial(n - 1, n * acc);
// multiply first; the call is lastIn the left line factorial(n - 1) is called first, and after it returns the result is multiplied by n. The multiplication is pending work, and so the value of n has to be kept in the frame. In the right line the multiplication is done before the call, while the argument is being computed. The value n * acc is sent to the new call as a parameter. When the call returns, the value that comes back is returned as it is; there is no other work to do (Figure 3.5.15).
This form makes tail call optimization (TCO) possible for the compiler. Since there is no pending work, the new call can reuse the old frame; the call is handled like a loop and frames do not pile up. Memory drops from O(n) to O(1) and the depth limit disappears.
Java, however, does not perform this optimization. Neither the javac compiler nor the JVM turns tail calls into loops. Tail-recursive Java code still opens a frame for every call and uses O(n) stack; the depth limit applies as before. Tail call optimization is mandatory in Scheme. In Scala the compiler turns self-calling tail recursions into loops, and the @tailrec annotation checks this. In Kotlin, methods marked with the tailrec keyword are turned into loops. In Java the value of tail recursion is that it makes conversion to a loop easier: a tail recursion with an accumulator can be turned into a while loop almost mechanically.
Taking a call that sits at the end of a line to be a tail call. In the line return 1 + countDigits(n / 10); the call is at the far right, but 1 is added on the way back; it is not a tail call. In the line return reverse(s.substring(1)) + s.charAt(0); concatenation is also done on the way back. The criterion is not where the call is written but whether any work remains after the call.
3.5.7.2Examples and the wrapper method
A linearly recursive method is made tail-recursive by adding an accumulator parameter. For digit sum and factorial the result looks like this:
int digitSum(int num, int sum) {
if (num == 0) {
return sum;
} else {
return digitSum(num / 10,
sum + num % 10);
}
}The last digit is added to sum before the call. digitSum(48729, 0) proceeds as follows: (48729, 0) → (4872, 9) → (487, 11) → (48, 18) → (4, 26) → (0, 30). When num == 0, the 30 in the accumulator is returned. This version is correct only for n ≥ 0; digitSum(-357, 0) returns −15, because Java gives a negative remainder for negative numbers.
int factorial(int n, int acc) {
if (n == 0) {
return acc;
} else {
return factorial(n - 1, n * acc);
}
}In factorial the product is folded into acc before the call, and factorial(5, 1) returns 120. The base case is now n == 0; at that point the result is ready in the accumulator.
The initial value of the accumulator is the identity element of the operation: 0 for addition, 1 for multiplication. This detail should not be a burden on whoever uses the method. For this reason a one-parameter wrapper method that hides the accumulator is written:
static int factorial(int n) {
return factorial(n, 1);
}The two methods have the same name but different numbers of parameters. In this case Java looks at the number of arguments in the call to tell which one is meant; this feature is called method overloading. The user writes factorial(5) and never sees the accumulator.
Here is a counterexample: the reverse method reverses a string.
static String reverse(String s) {
if (s.isEmpty()) return "";
return reverse(s.substring(1)) + s.charAt(0);
}reverse("java") is computed as reverse("ava") + 'j'; that in turn needs reverse("va") + 'a', and so on. The result is "avaj". This method is not tail-recursive, because concatenation (+) is done after the call returns. gcd, on the other hand, is tail-recursive: its last action is the call itself.
The tail-recursive version of Fibonacci carries the two variables of the loop version as parameters:
static long fibAcc(int n, long a, long b) {
if (n == 0) {
return a;
}
return fibAcc(n - 1, b, a + b);
}a and b are again two consecutive terms, and the first call is fibAcc(n, 0, 1). Each call decreases n by 1 and shifts the pair by one step. When n has dropped to 0, a is the requested term. fibAcc(10, 0, 1) returns 55 and makes only 11 calls. Compared with the tree-recursive version the difference is striking: the same relation is computed with 177 calls or with 11, depending on how the result is carried. The loop version and the tail-recursive version match line by line. The loop variables correspond to the parameters, the loop condition to the opposite of the base case, and one round to one call.
3.5.7.3Tracing factorial(4, 1)
static int factorial(int n, int acc) {
if (n == 0) {
return acc;
} else {
return factorial(n - 1, n * acc);
}
}| Call | n | acc | Work before the call | Work on the way back |
|---|---|---|---|---|
| 1 | 4 | 1 | 4 * 1 = 4 → factorial(3, 4) | returns 24 unchanged |
| 2 | 3 | 4 | 3 * 4 = 12 → factorial(2, 12) | returns 24 unchanged |
| 3 | 2 | 12 | 2 * 12 = 24 → factorial(1, 24) | returns 24 unchanged |
| 4 | 1 | 24 | 1 * 24 = 24 → factorial(0, 24) | returns 24 unchanged |
| 5 | 0 | 24 | base case | returns 24 |
All the multiplications are done on the way down (Table 3.5.16). When the base case is reached, the result is already in acc. No computation is done on the way back; 24 is simply passed upward. Compared with ordinary factorial, the order of the multiplications is also reversed: here they are multiplied in the order 4, 3, 2, 1.
factorial(4, 1). Top: the base case; the result is ready in acc. Bottom: all frames have returned 24 unchanged.Figure 3.5.16 shows an important fact: because Java does not optimize tail calls, all five factorial frames still go onto the stack. In a language that performs tail call optimization, a single frame would be enough. The loop equivalent of the same method in Java is: while (n != 0) { acc = n * acc; n = n - 1; } return acc;. The parameters become variables, and the recursive call turns into updates of these variables.
3.5.8Memoization
One way to remove the repetition in tree recursion was to switch to a loop. The second way is to keep the recursive structure and give the method a memory. When the method computes a value for the first time, it writes it down somewhere; if the same value is requested again, it reads it instead of computing.
Memoization is a method storing the results it has computed and returning them without recomputation when the same argument comes again. The structure that holds the results is called a cache. In this way the method carries state between calls.
3.5.8.1Fibonacci with memoization
The easiest tool for a cache in Java is a Map. A Map is a data structure that maps keys to values; here the key is n and the value is F(n). The notation Map<Integer, Long> says that the keys are Integer and the values are Long. Because a Map cannot hold primitive types, their wrapper classes are used instead of int and long; Java does the conversion automatically.
import java.util.HashMap;
import java.util.Map;
static Map<Integer, Long> memo = new HashMap<>();
static long fibonacci(int n) {
if (memo.containsKey(n)) {
return memo.get(n); // computed before
}
if (n == 0 || n == 1) {
return n;
}
long result = fibonacci(n - 1) + fibonacci(n - 2);
memo.put(n, result); // store the result
return result;
}The body of the method has four steps. First the memory is consulted: memo.containsKey(n) returns true if the key n was written before, and the value is read with memo.get(n) and returned. If it is not in memory, the base case is tested. If neither applies, the value is computed as usual with two recursive calls. Finally memo.put(n, result) stores the result, and the result is returned.
memo is defined as a field, outside the method, and static. Were it a local variable, it would be created anew and empty on every call, and nothing would be remembered. For all calls to share the same memory it must be kept outside the method. The return type has also been changed to long. Because memoization makes large n quickly computable, int is no longer enough: fibonacci(90) instantly returns 2880067194370816120. The largest Fibonacci number that fits in a long is F(92) = 7540113804746346429.
Because the keys are consecutive integers starting from 0, an array can be used instead of a Map:
static long[] table = new long[93];
static long fibonacci(int n) {
if (n <= 1) {
return n;
}
if (table[n] != 0) {
return table[n];
}
table[n] = fibonacci(n - 1) + fibonacci(n - 2);
return table[n];
}The length of the array is 93, because the last term that fits in a long is F(92). Java fills all elements of a new long array with 0. In this version 0 means "not computed yet". This convention is safe, because for n ≥ 2 no Fibonacci number is 0. The array uses less memory than the Map and is faster. No wrapper objects are created, and the key lookup reduces to a single index access. The price is flexibility: the length of the array must be known in advance and the keys must be small, non-negative integers. fibonacci(90) also returns 2880067194370816120 in this version.
3.5.8.2Tracing the memoized fibonacci(4)
static Map<Integer, Long> memo = new HashMap<>();
static long fibonacci(int n) {
if (memo.containsKey(n)) {
return memo.get(n);
}
if (n == 0 || n == 1) {
return n;
}
long result = fibonacci(n - 1) + fibonacci(n - 2);
memo.put(n, result);
return result;
}| Call | Argument | Event | Returns | memo (after) |
|---|---|---|---|---|
| 1 | 4 | not in memo, not a base case → fibonacci(3) | 3 | {} |
| 2 | 3 | not in memo → fibonacci(2) | 2 | {} |
| 3 | 2 | not in memo → fibonacci(1) | 1 | {} |
| 4 | 1 | base case | 1 | {} |
| 5 | 0 | base case; fibonacci(2) = 1 + 0 is stored | 0 | {2=1} |
| 6 | 1 | base case; fibonacci(3) = 1 + 1 is stored | 1 | {2=1, 3=2} |
| 7 | 2 | in memo, returned without computation; fibonacci(4) = 2 + 1 is stored | 1 | {2=1, 3=2, 4=3} |
The first six calls are the same as in the version without memoization (Table 3.5.17). The difference appears in the seventh call. The right term of fibonacci(4) is fibonacci(2), and this value was written to memory at the end of the fifth call. The method finds it on its first line and immediately returns 1. The version without memoization would make two more calls below fib(2) here: fib(1) and fib(0). The total number of calls drops from 9 to 7. Base-case values are not written to memory; they need no computation anyway.
fib(2) = 1 has been computed and 2 → 1 has been written to the memo. Bottom: the second fib(2) call reads its value from the memo (dashed box); the memo holds 2 → 1 and 3 → 2.3.5.8.3The call tree and the gain
The effect of memoization becomes striking as n grows. Figure 3.5.18 shows the call tree of the memoized fibonacci(5). The left arm is computed once from 5 down to 0. The fib(2) and fib(3) on the right come from the memo, and no new branches open below them. Nine calls are made instead of 15.
fibonacci(5): 9 calls. The dashed nodes are values read from the memo; the tree turns into a chain with short side branches.In general, with an empty memo fibonacci(n) makes exactly 2n − 1 calls for n ≥ 1. While the left arm descends from n to 1, n calls are made. For each value from 2 to n the right term needs one more call; these are n − 1 calls. The total is n + (n − 1) = 2n − 1. Exponential growth has come down to linear. Table 3.5.18 compares the two versions with measurements.
| n | Calls without memo | Calls with memo | Time without memo | Time with memo |
|---|---|---|---|---|
| 5 | 15 | 9 | < 0.1 ms | < 0.1 ms |
| 20 | 21,891 | 39 | ≈ 0.3 ms | < 0.1 ms |
| 40 | 331,160,281 | 79 | ≈ 0.5 s | < 1 ms |
| 90 | ≈ 9 · 1018 | 179 | centuries | < 1 ms |
The times vary from machine to machine; the ratio does not. The number of calls without memoization in the last row is 2F(91) − 1; even at a billion calls per second it would take about 300 years. The memoized version gives the same result in 179 calls.
This gain has a price: memory. The stored results hold as many entries as the value of n, and every entry contains an Integer and a Long object. Memoization spends memory to buy speed. In Fibonacci this trade is clearly profitable; in some problems, however, the number of results to be stored may be too large to fit in memory. Another limit is the stack: the left arm of the memoized version still descends n frames deep. fibonacci(100000) gives a StackOverflowError even with memoization, and its result would not fit in a long anyway.
3.5.8.4Factorial with memoization
The same pattern can be applied to any recursive method: look in the memo first, otherwise compute, store, return.
static Map<Integer, Long> memo = new HashMap<>();
static long factorial(int n) {
if (memo.containsKey(n)) {
return memo.get(n);
}
if (n == 0 || n == 1) {
return 1;
}
long result = n * factorial(n - 1);
memo.put(n, result);
return result;
}Thanks to long, correct results are obtained up to 20!: factorial(20) = 2432902008176640000. factorial(21), however, overflows and returns −4249290049419214848; the overflowed value is also written to the memo.
There is an interesting situation here. Factorial is not tree recursion; in a single factorial(n) call no value is computed twice. For this reason the memo does not speed up a single call; because of the Map operations it even slows it down slightly. The gain appears when the program asks for factorials many times. Because memo is static, it is preserved between calls. After factorial(10) has been called, the values from 1! to 10! are in memory. If factorial(12) is then requested, only two new multiplications are made, 12 × 11! and 11 × 10!; 10! is read from the memo. In computations that use factorials many times, such as binomial coefficients, this gain is meaningful.
Forgetting to consult the memo or to write the result. If the memo.put line is not written, the memo stays empty and the method behaves like the version without memoization. If the containsKey check is written after the base case and after the recursive call, the memo is of no use either. The correct order: consult the memo, base case, compute, store, return.
3.5.9Common mistakes
Most errors in recursive code fall into a few patterns. Some appear at compile time and some at run time; the most insidious give no message at all. Table 3.5.19 collects these patterns with the real messages of JDK 21.
| Mistake | Example | Symptom | Fix |
|---|---|---|---|
| Missing or unreachable base case | sum(0), base case n == 1 | Exception in thread "main" java.lang.StackOverflowError | Widen the base case: n <= 0 |
| No progress | return n * factorial(n); | StackOverflowError | Shrink the argument: n - 1 |
| Progress skips the base case | if (n == 0) return 0; return f(n - 3);, f(7) | StackOverflowError (7, 4, 1, −2, …) | A base case that tests a range, such as n <= 0 |
Missing return | A method ending in if … else if | error: missing return statement | Make the last branch an else |
| Ignoring the result of the call | factorial(n - 1); on its own | No message; the value is lost | return n * factorial(n - 1); |
| Overflow | int factorial, Bell coefficient | No message; wrong result at 13! | long or BigInteger |
| Needless tree recursion | fibonacci(50) without memoization | A run lasting minutes | A loop or memoization |
The missing return error comes from the Java compiler not evaluating conditions. The following method is written to find the largest digit of a number:
static int maxDigit(int n) {
if (n < 10) {
return n;
} else if (n % 10 > maxDigit(n / 10)) {
return n % 10;
} else if (n % 10 <= maxDigit(n / 10)) {
return maxDigit(n / 10);
}
}error: missing return statement
}
^The two else if conditions are each other's opposite and one of them is certainly true. But the compiler does not see this; it does not compute the values of the conditions at compile time. What it sees is that all three conditions could be false, in which case the method would end without returning a value. When the last branch is made an else, the error disappears. The same method has a second problem: maxDigit(n / 10) may be computed three times in one call. This triples the number of calls at every digit. The correct way is to compute the subproblem's result once and keep it in a variable: int sub = maxDigit(n / 10); return Math.max(n % 10, sub);. This version returns 9 for 48729 and makes five calls.
Ignoring the result of a call is seen especially among beginners. The line factorial(n - 1); is a valid Java statement: the method is called, the value is computed and then discarded. The compiler gives no warning for this. The value returned by a recursive call must either be used inside a return expression or be written to a variable.
Overflow and needless tree recursion are the two most insidious errors, because neither gives a message. The program runs and produces a result. Overflow gives a wrong number. Tree recursion gives the right result very late. The way to prevent both is to think, while writing the method, about how large the input can grow and to test with boundary values.
3.5.10Summary
- Recursion: a method calls itself with a smaller input. Java needs no special keyword; the method body calls its own name.
- Base case and progress: the base case is the smallest case, solved directly, and it stops the recursion. Every call must approach the base case (
n - 1,n / 10,substring,x % y). If either of the two rules is broken, aStackOverflowErrorresults. - Call stack: a frame is opened for every call; a frame has its own parameters and local variables. Frames close in LIFO order. With the default stack the depth cannot exceed a few tens of thousands of calls; the limit varies with the JVM settings.
- Descent and ascent: work done before the call runs on the way down, work done after it on the way back. A method that prints on the way back reverses the order (
write2,toBinary). - Sequences: a recurrence relation translates directly into a recursive method. Fibonacci and Lucas call themselves twice; Catalan and Bell make their calls inside a loop. An
intis enough up to 12!, alongup to 20!; overflow is silent. - Examples: digit sum shrinks digit by digit, the palindrome test from both ends, and Euclid's algorithm by the remainder. The Towers of Hanoi makes 2n − 1 moves and takes a few lines with recursion.
- Tree recursion: multiple calls (Fibonacci, Hanoi) form a tree; when there is repetition the number of calls grows exponentially.
fibonacci(40)without memoization makes 331,160,281 calls. - Iterative solution: a loop with an accumulator variable runs in a single frame with constant memory and is usually faster. Every recursive solution can be written with a loop.
- Tail recursion: the last action is the call itself and the result is carried in an accumulator parameter. The accumulator's initial value is the identity element and is hidden by a wrapper method. Java does not perform tail call optimization.
- Memoization: computed results are stored in a
Mapand reused. Memoized Fibonacci makes 2n − 1 calls; its price is memory.
3.5.11Key terms
- recursion
- base case
- recursive step
- call stack
- stack frame
- stack overflow
- stack trace
- tree recursion
- recurrence relation
- leap of faith
- iterative solution
- tail recursion
- accumulator
- tail call optimization
- memoization
- Euclidean algorithm
- palindrome
3.5.12Test Yourself
For the following method, what is
f(6)? How many times is the method called (including the first call)? What does the method compute?static int f(int n) { if (n <= 0) return 0; return (n % 2 == 0 ? n : 0) + f(n - 1); }Answer
f(6)= 6 + 0 + 4 + 0 + 2 + 0 + 0 = 12. The arguments are 6, 5, 4, 3, 2, 1, 0; 7 calls are made. The method computes the sum of the even numbers from 1 to n. Because the base case isn <= 0, it also stops for negative input.What does
g(3)print?static void g(int n) { if (n == 0) return; System.out.print(n); g(n - 1); System.out.print(n); }Answer
321123. The firstprintruns on the way down and writes 3, 2, 1. The secondprintruns on the way back; because the deepest frame returns first, 1, 2, 3 is written.What value does the following exponentiation method return for
power(2, 10), and how many calls does it make? How many calls would a version that decreases the exponent by one,base * power(base, exp - 1), make?static long power(long base, int exp) { if (exp == 0) return 1; long y = power(base, exp / 2); return exp % 2 == 0 ? y * y : y * y * base; }Answer
It returns 1024; since the exponents are 10, 5, 2, 1, 0, 5 calls are made.
power(2, 5)= 32 (odd exponent: 4 · 4 · 2), then 32 · 32 = 1024. The version that decreases the exponent by one would make 11 calls. Halving the exponent reduces the number of calls from O(e) to O(log e). Keeping the subresult inyis important; hadpower(base, exp / 2) * power(base, exp / 2)been written, the gain would have been lost.How would the
countDigitsmethod be written as a tail-recursive methodcountDigitsAcc(int n, int k)that uses an accumulator? What shouldcountDigitsAcc(48729, 0)return?Answer
static int countDigitsAcc(int n, int k) { if (n < 10) return k + 1; return countDigitsAcc(n / 10, k + 1); }kcounts the digits dropped so far and starts at 0. (48729, 0) → (4872, 1) → (487, 2) → (48, 3) → (4, 4) → 4 + 1 = 5. Because its last action is the call, it is tail-recursive.For
static int h(int n) { if (n == 0) return 1; return h(n - 1) + h(n - 1); }, what ish(4)and how many calls are made? What happens to the number of calls if the last line is changed toreturn 2 * h(n - 1);?Answer
h(4)= 24 = 16. Since every call opens two calls, the tree has 1 + 2 + 4 + 8 + 16 = 31 calls. With2 * h(n - 1)the same result is found in 5 calls. Calling the same subproblem twice raises the cost to exponential without changing the result.How many calls does
gcd(89, 55)make and what is its result? How many frames are on the stack at the deepest moment, countingmain?Answer
The GCD is 1. The chain is (89, 55) → (55, 34) → (34, 21) → (21, 13) → (13, 8) → (8, 5) → (5, 3) → (3, 2) → (2, 1) → (1, 0); 10 calls are made. All of them are on the stack at the same time, because Java does not optimize tail calls: 11 frames with
main. Consecutive Fibonacci numbers are the case in which the remainder shrinks most slowly at each step.What does the following method return for
count("kelebek", 'e')? How many calls are made? Which is the base case?static int count(String s, char c) { if (s.length() == 0) return 0; int k = s.charAt(0) == c ? 1 : 0; return k + count(s.substring(1), c); }Answer
It returns 3: "kelebek" contains three 'e's. The string gets one character shorter on every call; 7 calls for the seven letters and 1 call for the empty string make 8 calls in total. The base case is the empty string, which returns 0.
The Towers of Hanoi with 5 disks is solved with
solve(5, 'A', 'C', 'B'). How many moves are printed and what is the first move? On which move is the largest disk moved?Answer
25 − 1 = 31 moves. Because the number of disks is odd, the first move is
1: A->C. The largest disk is moved from A to C on the 16th move, after the top 4 disks have been moved to B in 24 − 1 = 15 moves.
3.5.13Further reading
- A. B. Downey and C. Mayfield, Think Java (2nd ed., 2019), Chapter 8: recursive methods are explained with stack diagrams and the "leap of faith". The book can be read free online.
- R. Sedgewick and K. Wayne, Computer Science: An Interdisciplinary Approach, Section 2.3: the power of recursion through Euclid, Hanoi, Gray codes and recursive drawings; the exponential Fibonacci trap and its remedy with dynamic programming.
- P. Deitel and H. Deitel, Java: How to Program, Chapter 18: compares recursion with iteration and gives further examples such as fractal drawings, eight queens and mazes.
- H. Abelson and G. J. Sussman, Structure and Interpretation of Computer Programs (2nd ed., MIT Press, 1996), Section 1.2: the classic treatment of linear and tree recursion, iterative processes and the notion of tail calls.
3.5.14References
- P. Deitel, H. Deitel, Java: How to Program (Early Objects), 11th ed., Pearson, 2017 (Chapter 18: Recursion).
- A. B. Downey, C. Mayfield, Think Java, 2nd ed., O'Reilly, 2019 (Chapter 8: Recursive Methods).
- J. Gosling, B. Joy, G. Steele, G. Bracha, A. Buckley, D. Smith, G. Bierman, The Java Language Specification, Java SE 21 Edition, Oracle, 2023 (15.12: Method Invocation Expressions).
- C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed., Pearson, 2022.
- Oracle, The Java Tutorials: Defining Methods; Returning a Value from a Method, docs.oracle.com/javase/tutorial/java/javaOO/.
- R. Sedgewick, K. Wayne, Computer Science: An Interdisciplinary Approach, Addison-Wesley, 2016 (2.3: Recursion).
- H. Abelson, G. J. Sussman, J. Sussman, Structure and Interpretation of Computer Programs, 2nd ed., MIT Press, 1996.
Related pages: Chapter 3.5 slides · Study questions · Glossary · © Sercan Külcü. All rights reserved.