58

A function that calls itself. Every recursion needs a base case (stop condition) and a recursive case that moves toward it. Each call uses stack memory; without a base case you get a stack overflow.

C++ 17 lines
int power(int a, int b) {        // a^b
    if (b == 0) return 1;        // base case
    return a * power(a, b - 1);  // recursive case
}

long long fastPower(long long a, int b) {   // O(log b)
    if (b == 0) return 1;
    long long half = fastPower(a, b / 2);
    return (b % 2) ? half * half * a : half * half;
}

void hanoi(int n, char from, char to, char via) {   // Tower of Hanoi: 2^n - 1 moves
    if (n == 0) return;
    hanoi(n - 1, from, via, to);
    cout << "Move disk " << n << " " << from << " -> " << to << "\n";
    hanoi(n - 1, via, to, from);
}