Algorithm · Recursion and backtracking · O(e) vs O(log e) calls

Recursion and the call stack

A function that calls itself on a smaller input, with a base case that stops it. Each call is a stack frame; depth decides memory and stack overflow.

The full derivation, edge cases and exercises are in the lesson Space complexity, the call stack and multiple inputs. Open it full width in the playground.

On this page
  1. The idea
  2. Steps
  3. Invariants
  4. Complexity
  5. When to use it
  6. Step through it
  7. Implementation
  8. Learn more
  9. References

The idea

Every active call keeps a frame with its parameters, locals and return address. Computing a power linearly needs e + 1 frames; by squaring it needs about log₂ e. The same answer, but a very different stack depth, and the difference is what decides whether a recursive solution overflows.

Steps

  1. Handle the base case without recursing.
  2. Reduce the problem to a strictly smaller one and call yourself.
  3. Combine the result on the way back.

Invariants

What holds at every step; the correctness argument rests on these.

  • Every call moves strictly toward the base case.
  • Stack depth equals the number of unfinished calls.

Complexity

Recursion and the call stack complexity
CaseTimeExtra space
Linear powerO(e) callsO(e) stack
Power by squaringO(log e) callsO(log e) stack

When to use it

Use it when

  • The problem is defined in terms of smaller copies of itself: trees, divide and conquer, backtracking.

Avoid it when

  • The depth can reach thousands or more (Python’s default limit is 1000): use a loop or an explicit stack.

Step through it

The interactive lab for recursion and the call stack: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.

Implementation in four languages

Both recursive powers in four languages, each checked against one shared fixture (zero exponent, zero and negative bases, results up to the 64-bit limit) and 2,000 random cases compared with an exact reference (BigInteger, Python ints or a checked loop); the C#, Java and C++ tests also confirm that a result past 64 bits throws instead of wrapping, and the Python and Java tests trigger a real RecursionError and StackOverflowError.

namespace Bekadan.Dsa.Examples.Recursion;
 
/// <summary>
/// Integer power b^e computed recursively, two ways. Both use 64-bit integers and
/// <c>checked</c> multiplication, so a result that does not fit throws
/// <see cref="OverflowException"/> instead of silently wrapping around.
/// </summary>
public static class RecursivePower
{
    /// <summary>Linear recursion: one call per unit of e, so e + 1 frames deep. Θ(e) time and stack.</summary>
    public static long Linear(long b, int e)
    {
        ArgumentOutOfRangeException.ThrowIfNegative(e);
        if (e == 0)
            return 1;
        long rest = Linear(b, e - 1);
        return checked(b * rest);
    }
 
    /// <summary>Recursion by squaring: the exponent halves on every call. Θ(log e) time and stack.</summary>
    public static long Squaring(long b, int e)
    {
        ArgumentOutOfRangeException.ThrowIfNegative(e);
        if (e == 0)
            return 1;
        long half = Squaring(b, e / 2);
        if (e % 2 == 0)
            return checked(half * half);
        return checked(half * half * b);
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Recursion/RecursivePower.cs

"""Integer power b**e computed recursively, two ways.
 
Python integers have arbitrary precision, so these never overflow; the other three
languages use 64-bit integers and check every multiplication. What Python does limit
is recursion depth: linear recursion needs e + 1 frames, and the interpreter raises
RecursionError past sys.getrecursionlimit() (1000 by default).
"""
 
 
def power_linear(b: int, e: int) -> int:
    """Linear recursion: one call per unit of e. Θ(e) time and stack."""
    if e < 0:
        raise ValueError("e must be non-negative")
    if e == 0:
        return 1
    rest = power_linear(b, e - 1)
    return b * rest
 
 
def power_squaring(b: int, e: int) -> int:
    """Recursion by squaring: the exponent halves on every call. Θ(log e) calls and stack."""
    if e < 0:
        raise ValueError("e must be non-negative")
    if e == 0:
        return 1
    half = power_squaring(b, e // 2)
    if e % 2 == 0:
        return half * half
    return half * half * b

Tested on CPython 3.14.0 · examples/python/dsa_examples/recursive_power.py

package dev.bekadan.dsa.recursion;
 
/**
 * Integer power b^e computed recursively, two ways. Both use 64-bit {@code long} and
 * {@link Math#multiplyExact(long, long)}, so a result that does not fit throws
 * {@link ArithmeticException} instead of silently wrapping around.
 */
public final class RecursivePower {
    private RecursivePower() {
    }
 
    /** Linear recursion: one call per unit of e, so e + 1 frames deep. Θ(e) time and stack. */
    public static long linear(long b, int e) {
        if (e < 0) {
            throw new IllegalArgumentException("e must be non-negative");
        }
        if (e == 0) {
            return 1;
        }
        long rest = linear(b, e - 1);
        return Math.multiplyExact(b, rest);
    }
 
    /** Recursion by squaring: the exponent halves on every call. Θ(log e) time and stack. */
    public static long squaring(long b, int e) {
        if (e < 0) {
            throw new IllegalArgumentException("e must be non-negative");
        }
        if (e == 0) {
            return 1;
        }
        long half = squaring(b, e / 2);
        if (e % 2 == 0) {
            return Math.multiplyExact(half, half);
        }
        return Math.multiplyExact(Math.multiplyExact(half, half), b);
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/recursion/RecursivePower.java

#pragma once
 
#include <cstdint>
#include <limits>
#include <stdexcept>
 
namespace bekadan::dsa {
 
// Signed overflow is undefined behaviour in C++, so check before multiplying
// (the bounds test from SEI CERT rule INT32-C).
inline std::int64_t checked_multiply(std::int64_t a, std::int64_t b) {
    constexpr auto max = std::numeric_limits<std::int64_t>::max();
    constexpr auto min = std::numeric_limits<std::int64_t>::min();
    const bool overflows = a > 0 ? (b > 0 ? a > max / b : b < min / a)
                                 : (b > 0 ? a < min / b : a != 0 && b < max / a);
    if (overflows) throw std::overflow_error("power does not fit in 64 bits");
    return a * b;
}
 
// Linear recursion: one call per unit of e, so e + 1 frames deep. Θ(e) time and stack.
inline std::int64_t power_linear(std::int64_t b, int e) {
    if (e < 0) throw std::invalid_argument("e must be non-negative");
    if (e == 0) return 1;
    const std::int64_t rest = power_linear(b, e - 1);
    return checked_multiply(b, rest);
}
 
// Recursion by squaring: the exponent halves on every call. Θ(log e) time and stack.
inline std::int64_t power_squaring(std::int64_t b, int e) {
    if (e < 0) throw std::invalid_argument("e must be non-negative");
    if (e == 0) return 1;
    const std::int64_t half = power_squaring(b, e / 2);
    if (e % 2 == 0) return checked_multiply(half, half);
    return checked_multiply(checked_multiply(half, half), b);
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/recursive_power.hpp

Learn more

Data structures it uses

Problems, patterns and exercises

References