Chapter 3.5: Recursion

Chapter 3.5: Recursion · Study Questions
The call stackSum and factorialSequencesWriting methodsExamplesEfficiencyTail recursionMemoization
Sercan KÜLCÜ · Giresun University · Computer Engineering

Multiple Choice · The Concept of Recursion

Question 1: The Deepest Moment

main calls f(4) and prints the result. At its deepest moment, how many frames does the call stack contain, main included?

static int f(int n) {
    if (n <= 1) return 1;
    return n * f(n - 1);
}
// in main:
System.out.println(f(4));

B: main, f(4), f(3), f(2) and f(1) are on the stack at the same time: every call has its own frame and its own n. f(1) is the base case and opens no new call. The multiplications happen while the frames close in reverse order: 1, 2, 6, 24.

Output Question · Factorial and Sum

Question 2: Printing on the Way Down and Back

The method prints both before it calls itself and after the call returns. What is the output?

static int f(int n) {
    if (n == 0) return 0;
    System.out.print(n + " ");
    int s = n + f(n - 1);
    System.out.print("[" + s + "] ");
    return s;
}
// in main:
System.out.println(f(3));
Show answer

Output: 3 2 1 [1] [3] [6] 6

  • Going down: each call first prints its own n, then calls one smaller: 3 2 1. f(0) is the base case and prints nothing.
  • Coming back: the frames close in reverse order. f(1): s = 1 + 0; f(2): s = 2 + 1 = 3; f(3): s = 3 + 3 = 6.
  • Finally main prints the returned 6. The method computes the sum from 1 to n.

Multiple Choice · Factorial and Sum

Question 3: sum(0)

What happens when sum(0) is called?

static int sum(int n) {
    if (n == 1) return 1;
    return n + sum(n - 1);
}

A: n goes 0, −1, −2, … and never equals 1; every call opens a new frame and the stack fills up. The compiler cannot see this, because every path ends with a return. A safe base case: if (n <= 0) return 0;

Multiple Choice · Sequences

Question 4: Number of Fibonacci Calls

How many times in total does the call fibonacci(6) invoke fibonacci, counting the first call?

static int fibonacci(int n) {
    if (n <= 1) return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
}

D: The number of calls is C(n) = 1 + C(n − 1) + C(n − 2), C(0) = C(1) = 1: 1, 1, 3, 5, 9, 15, 25. The result itself is only F(6) = 8. Because the same values are computed over and over, the number of calls grows exponentially.

Output Question · Sequences

Question 5: Lucas and Catalan

What does the program print?

static int lucas(int n) {
    if (n == 0) return 2;
    if (n == 1) return 1;
    return lucas(n - 1) + lucas(n - 2);
}
static 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;
}
// in main:
for (int n = 0; n <= 6; n++)
    System.out.print(lucas(n) + " ");
System.out.println();
System.out.println(catalan(4));
Show answer
2 1 3 4 7 11 18
14
  • Lucas uses the same formula as Fibonacci; only the starting values (2 and 1) differ.
  • C(4) = C(0)C(3) + C(1)C(2) + C(2)C(1) + C(3)C(0) = 5 + 2 + 2 + 5 = 14. The recursion happens inside a loop.

Step-by-Step Trace · Sequences

Question 6: The Call Tree of lucas(3)

Tree recursion: the method calls itself twice. Follow the order of the calls and the returned values.

L(3)

n = 3 is not a base case. First the left term of the sum: lucas(2).

L(3)L(2)

n = 2: it again starts with the left term, calling lucas(1).

L(3)L(2)L(1)= 1

Base case: 1 is returned.

L(3)L(2)L(1)= 1L(0)= 2

The right term lucas(0): base case, 2 is returned.

L(3)L(2)= 3L(1)= 1L(0)= 2

lucas(2) = 1 + 2 = 3 is returned.

L(3)L(2)= 3L(1)= 1L(1)= 1L(0)= 2

The right term of lucas(3) is lucas(1): 1. This value was computed before; it is computed again.

L(3)= 4L(2)= 3L(1)= 1L(1)= 1L(0)= 2

lucas(3) = 3 + 1 = 4 is returned.

L(3)= 4L(2)= 3L(1)= 1L(1)= 1L(0)= 2

5 calls in total. The stack reached a depth of at most 4 frames.

static int lucas(int n) {
    if (n == 0) return 2;
    if (n == 1) return 1;
    return lucas(n - 1) + lucas(n - 2);
}
// in main:
System.out.println(lucas(3));

Multiple Choice · Writing Methods

Question 7: Which One Never Ends?

The bodies belong to the method static int f(int n). In which one does the call f(7) never end?

C: n goes 7, 4, 1, −2, −5, … and skips 0; the base case is never reached → StackOverflowError. In A, 7 is already a base case. In B, 7 → 8 → 4 → 2 → 1. In D, every call makes n smaller and it stops at n ≤ 1.

Spot the Bug · Writing Methods

Question 8: A Missing return

The method was written to find the largest digit of a number. Does it compile? Find the problems and fix them. What does the fixed method return for 48729 and for 3152?

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);
    }
}
Show answer
  • It does not compile: error: missing return statement. Even though the condition of the last else if is the opposite of the previous one, the compiler does not evaluate conditions; if no branch runs, the method ends without a value.
  • Also, the same maxDigit(n / 10) can be called three times: the number of calls can triple with every digit (121 calls for 54321).
static int maxDigit(int n) {
    if (n < 10) return n;
    int rest = maxDigit(n / 10);
    return Math.max(n % 10, rest);
}

Results: 48729 → 9, 3152 → 5. The result of the subproblem is computed once and kept in a variable.

Multiple Choice · Examples

Question 9: How Many Calls for a Palindrome?

After the call isPalindrome("abcdba"), what is counter, and what does the method return?

static int counter = 0;
static boolean isPalindrome(String s) {
    counter++;
    int n = s.length();
    if (n <= 1) return true;
    if (s.charAt(0) != s.charAt(n - 1))
        return false;
    return isPalindrome(s.substring(1, n - 1));
}

D: "abcdba": the ends a = a → "bcdb"; the ends b = b → "cd"; c ≠ d → false. The third call ends at the second base case (the ends differ), and false is carried up unchanged. Each call shortens the string by two characters.

Output Question · Examples

Question 10: The Euclid Chain

Each call prints its own arguments. What does the program print?

static int gcd(int x, int y) {
    System.out.print("(" + x + "," + y + ") ");
    if (y == 0) return x;
    return gcd(y, x % y);
}
// in main:
System.out.println(gcd(1071, 462));
System.out.println(gcd(17, 5));
System.out.println(gcd(6, 24));
Show answer
(1071,462) (462,147) (147,21) (21,0) 21
(17,5) (5,2) (2,1) (1,0) 1
(6,24) (24,6) (6,0) 6
  • 1071 % 462 = 147, 462 % 147 = 21, 147 % 21 = 0 → GCD 21.
  • 17 and 5 are coprime: GCD 1.
  • If x < y, the first step only swaps them: 6 % 24 = 6 → gcd(24, 6).
  • Since the last thing in the method is always the call itself, gcd is tail recursive; the value is carried back through the frames unchanged.

Step-by-Step Trace · Examples

Question 11: Tracing binary(13)

The method prints the binary representation of a number. The printing is done after the call. Trace the call stack and the output.

13 > 1: first binary(6). The printing waits until the call returns.

6 > 1 → binary(3).

3 > 1 → binary(1).

1 > 1 is false: base case. 1 % 2 = 1 is printed.

On the way back, the waiting print: 3 % 2 = 1.

6 % 2 = 0.

13 % 2 = 1.

The remainders were printed in reverse order: the highest digit came from the deepest call. 13 = 8 + 4 + 1 = 1101₂.

static void binary(int n) {
    if (n > 1) {
        binary(n / 2);
    }
    System.out.print(n % 2);
}
// in main:
binary(13);

Output Question · Examples

Question 12: Hanoi: Target B

The version whose base case is n = 0 (from: source, to: target, via: helper). The disks are moved from A to B, using C as the helper: solve(3, 'A', 'B', 'C'); Which moves are printed? How many lines would be printed for 5 disks?

static void solve(int n, char from,
                  char to, char via) {
    if (n == 0) return;
    solve(n - 1, from, via, to);
    System.out.println(n + ": " + from + "->" + to);
    solve(n - 1, via, to, from);
}
Show answer
1: A->B
2: A->C
1: B->C
3: A->B
1: C->A
2: C->B
1: A->B
  • The top 2 disks are first moved to the helper (C) (3 moves), the largest disk goes A → B, then the 2 disks go C → B (3 moves).
  • The number of moves is H(n) = 2 · H(n − 1) + 1 = 2n − 1: 7 for 3 disks, 31 for 5 disks.

Multiple Choice · Efficiency

Question 13: Very Deep Recursion

Overflow of the result aside, what most likely happens on the call factorial(100000) with the default JVM settings?

static long factorial(int n) {
    if (n <= 1) return 1;
    return n * factorial(n - 1);
}

B: Every call keeps a frame on the stack and the stack size is limited; when the depth exceeds tens of thousands, the JVM throws StackOverflowError. The compiler cannot know the run-time depth. The loop version runs with a single frame and constant memory.

Multiple Choice · Tail Recursion

Question 14: Which One Is Tail Recursive?

Which of the following return lines is a tail-recursive call?

A: In a tail call, the call is the last thing the method does; the addition is done before the call and the result is carried in the accumulator. In the others there is still work to do after the call returns (a multiplication, an addition, a concatenation). Java does not optimize tail calls; the depth still builds up on the stack.

Coding Question · Tail Recursion

Question 15: Tail-Recursive Power

Write the method long powerTail(int base, int exp, long acc), which computes a power with tail recursion, and a wrapper method power that spares the user from thinking about the accumulator. What are power(3, 4) and power(2, 40)?

Show answer
static long powerTail(int base, int exp,
                    long acc) {
    if (exp == 0) return acc;
    return powerTail(base, exp - 1,
                     acc * base);
}
static long power(int base, int exp) {
    return powerTail(base, exp, 1);
}
  • The multiplication is done before the call: powerTail(3, 4, 1) → powerTail(3, 3, 3) → powerTail(3, 2, 9) → powerTail(3, 1, 27) → powerTail(3, 0, 81) → 81.
  • The accumulator starts at 1, the identity element of multiplication. Thanks to long, power(2, 40) = 1099511627776 does not overflow.

Step-by-Step Trace · Memoization

Question 16: Tracing fib(5) with Memoization

The computed values are stored in a Map. Which calls do the computation, and which return from memory?

fib(5): not in memory, not a base case → the left term fib(4).

fib(4) → fib(3) → fib(2): none is in memory, the left branch goes down.

fib(1): base case, 1 is returned (it is not written to memory).

fib(0): base case, 0 is returned.

fib(2) = 1 + 0 = 1, written to memory.

The right term of fib(3), fib(1): 1.

fib(3) = 1 + 1 = 2, stored.

The right term of fib(4), fib(2), is in memory: 1 is returned without computing.

fib(4) = 2 + 1 = 3, stored.

The right term of fib(5), fib(3), comes from memory: 2.

fib(5) = 3 + 2 = 5.

9 calls in total (2 · 5 − 1); the version without memoization would have made 15 calls.

static Map<Integer, Long> memo = new HashMap<>();
static long fib(int n) {
    if (memo.containsKey(n)) return memo.get(n);
    if (n <= 1) return n;
    long result = fib(n - 1) + fib(n - 2);
    memo.put(n, result);
    return result;
}
// in main:
System.out.println(fib(5));

Multiple Choice · Memoization

Question 17: Number of Calls with Memoization

With an empty memo, how many calls does the following memoized fib method make for fib(10)?

static Map<Integer, Long> memo = new HashMap<>();
static long fib(int n) {
    if (memo.containsKey(n)) return memo.get(n);
    if (n <= 1) return n;
    long result = fib(n - 1) + fib(n - 2);
    memo.put(n, result);
    return result;
}

C: Every n (2…10) is computed once; the left branch goes down from 10 to 1 with 10 calls, and for n = 2…10 the right terms make 9 more calls: 2 · 10 − 1 = 19. 177 is the number of calls of the version without memoization, and 55 is the value of F(10).

The End

Chapter 3.5: Recursion: Study Questions
Lecture slides: Chapter 3.5: Recursion · Lecture notes
1 / 1 Sercan KÜLCÜ. All rights reserved.