← Java from Scratch Lesson 27 of 88 · 10 XP

Recursion

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

Recursion is when a method calls itself. It needs a base case (when to stop) and a step that gets closer to it:

static int factorial(int n) {
    if (n <= 1) return 1;            // the base case
    return n * factorial(n - 1);     // the step
}

What's under the hood. Each call puts its own frame on the call stack (parameters, local variables, the return address). Without a base case the stack runs out: StackOverflowError. The depth is thousands of calls, not millions: for long chains a loop is more reliable.

Recursion is natural for tasks that split into smaller tasks of the same kind: walking through trees and folders, "divide and conquer".

Task. Write a recursive static long power(long a, int n) using the fast exponentiation rule (a^n = (a^(n/2))², and for an odd n multiply by a once more) and static int digitSum(int n) — the sum of the digits. Print both results separated by a space.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.