AlgoViz

Recursion: factorial

easy 16 min

Recursion is a function solving a problem by calling itself on a smaller copy of it.

Where it shows up

The same pattern appears across everyday software.

  • File system navigation

    Computing a folder's size or searching for a file is naturally recursive: a folder's total is its own files plus the totals of its subfolders. Tools like du, find and os.walk follow this shape.

  • Tree data structures

    Binary search trees, heaps, the DOM in a browser and JSON documents are all trees. Inserting, searching and printing them is written most naturally as a function that calls itself on each child.

  • Game AI with minimax

    Chess and tic-tac-toe engines score a move by recursively scoring every reply, alternating between the two players until a depth limit or the end of the game, which is the base case.

  • Parsing and compilers

    Recursive descent parsers read nested code such as expressions inside brackets inside function calls by calling one function per grammar rule, and those functions call each other (mutual recursion).

  • Mathematical sequences

    Factorials, Fibonacci numbers, binomial coefficients and combinatorics formulas are defined recursively, and libraries compute them with recursion plus caching or with equivalent loops.

  • Fractals and graphics

    Fractals such as the Koch snowflake and Sierpinski triangle draw a shape, then draw smaller copies of it inside, down to a minimum size. Ray tracers recurse on reflected and refracted rays up to a depth limit.