Recursion / backtracking · O(e) vs O(log e) calls

Recursion and the call stack

Frames push and pop for integer power, linear and by squaring, with a stack limit.

The full explanation, derivation and practice are in the lesson Recursion and the call stack: base cases, frames and depth limits.

Implementation

The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.

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