← 講座に戻る: Java from scratch

Recursion and week 5 review

動画は近日公開

A recursive method is a method that calls itself. It sounds odd at first, but it is a natural way to solve problems that contain smaller versions of themselves: computing a factorial, walking through folders inside folders, solving a maze. Every recursive problem has two essential parts: the base case, which is solved directly and stops the chain, and the recursive case, which reduces the problem and calls again. Without a base case, the method calls itself forever.

Your first recursion: the factorial

The factorial of n is n times the factorial of n - 1, and the factorial of 0 is 1. That sentence is already the algorithm: the base case is n equal to 0 and the recursive case is n * factorial(n - 1). Each call waits for the result of the next one, and the answers are multiplied on the way back. Java keeps every pending call in a memory area called the stack; if the chain is too long, the stack fills up and StackOverflowError appears. To understand it, trace factorial(3) by hand: 3 * (2 * (1 * 1)).

java
public class Main {
    static long factorial(int n) {
        if (n == 0) return 1;              // base case
        return n * factorial(n - 1);       // recursive case
    }

    static int sumDigits(int n) {
        if (n < 10) return n;              // base case: one digit
        return n % 10 + sumDigits(n / 10);
    }

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

    static long power(long base, int exp) {
        if (exp == 0) return 1;
        return base * power(base, exp - 1);
    }

    static int broken(int n) {
        return broken(n + 1);              // no base case!
    }

    public static void main(String[] args) {
        System.out.println(factorial(5));      // 120
        System.out.println(sumDigits(48213));  // 18
        System.out.println(fibonacci(10));     // 55
        System.out.println(power(2, 10));      // 1024
        try {
            broken(0);
        } catch (StackOverflowError e) {
            System.out.println("StackOverflowError: no base case");
        }
    }
}

When to use recursion and when not

Recursion shines in problems with tree structure or divide-and-conquer. But it is not always the best option: the recursive fibonacci above repeats a huge number of calculations (fibonacci(40) takes seconds because it recalculates the same values millions of times), while a loop solves it instantly. Every recursive method can be rewritten with a loop; choose the clearest version and check performance if the problem is large. A classic where recursion is much simpler is the Towers of Hanoi: to move n disks, you move n - 1 disks to the spare tower, move the largest one and move the n - 1 again on top.

java
public class Main {
    // Iterative fibonacci: fast and simple
    static long fibonacciLoop(int n) {
        long previous = 0, current = 1;
        for (int i = 0; i < n; i++) {
            long next = previous + current;
            previous = current;
            current = next;
        }
        return previous;
    }

    // Towers of Hanoi: print every move
    static int moves = 0;
    static void hanoi(int disks, char from, char to, char spare) {
        if (disks == 0) return;
        hanoi(disks - 1, from, spare, to);
        moves++;
        System.out.println("Move disk " + disks + " from " + from + " to " + to);
        hanoi(disks - 1, spare, to, from);
    }

    public static void main(String[] args) {
        System.out.println(fibonacciLoop(50));   // 12586269025
        hanoi(3, 'A', 'C', 'B');
        System.out.println("Total moves: " + moves);  // 7
    }
}

Week 5 review

  • A method has a return type, name, parameters and body; void if it returns nothing.
  • Arguments are passed by value; with objects and arrays the reference is copied.
  • Overloading: same name, different parameter list; varargs with int... values.
  • Scope: a local variable exists only in its block; static is shared by the whole class; static final for constants.
  • Recursion: base case + recursive case; beware of StackOverflowError and of repeated calculations.

理解度チェック

問題 1 / 6

Which two parts does every recursive method need?

✎ マイノート

このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字

← 前へ次へ →