Generalized Chinese remainder theorem: Examples & Code

Algorithm Visualizations November 16, 2026 javascript

Published by Dimitris Kougioumtzis · Updated

Merge congruences using their gcd, reject incompatible residues, and search a bounded set of offsets in the current period.

Maintain a solution modulo the lcm of processed moduli. For each new congruence, check agreement modulo the gcd, then test offsets of the existing period until the new residue is satisfied.

Open the 3D visualization

Generalized Chinese remainder theorem example state preview
Preview of the example's final state. Complete values are available in the worked example and interactive timeline.

When to use Generalized Chinese remainder theorem

Combining periodic constraints even when their periods share factors.

Choosing an alternative

The textbook coprime CRT formula assumes every pair of moduli is coprime. This generalized merge detects when shared factors make a system impossible.

Worked example: input and state changes

Example input

2,3,2 | 3,5,7

These checkpoints follow the actual example timeline. State details show the stored values and decisions; use the visualization to inspect every intervening step.

  1. Step 0: Rows: residue, modulus, merged solution, merged period.

    State at this checkpoint
    {
      "values": [
        2,
        3,
        "",
        "",
        3,
        5,
        "",
        "",
        2,
        7,
        "",
        ""
      ],
      "active": [],
      "kind": "matrix",
      "columns": 4,
      "result": 0,
      "output": [
        0,
        1
      ]
    }
  2. Step 3: Try offset 2 in the current period.

    State at this checkpoint
    {
      "values": [
        2,
        3,
        2,
        "",
        3,
        5,
        "",
        "",
        2,
        7,
        "",
        ""
      ],
      "active": [
        2
      ],
      "kind": "matrix",
      "columns": 4,
      "result": 0,
      "output": [
        0,
        1
      ]
    }
  3. Step 6: Try offset 1 in the current period.

    State at this checkpoint
    {
      "values": [
        2,
        3,
        2,
        3,
        3,
        5,
        5,
        "",
        2,
        7,
        "",
        ""
      ],
      "active": [
        6
      ],
      "kind": "matrix",
      "columns": 4,
      "result": 2,
      "output": [
        2,
        3
      ]
    }
  4. Step 9: Try offset 0 in the current period.

    State at this checkpoint
    {
      "values": [
        2,
        3,
        2,
        3,
        3,
        5,
        8,
        15,
        2,
        7,
        8,
        ""
      ],
      "active": [
        10
      ],
      "kind": "matrix",
      "columns": 4,
      "result": 8,
      "output": [
        8,
        15
      ]
    }
  5. Step 12: Smallest nonnegative solution 23, period 105.

    State at this checkpoint
    {
      "values": [
        2,
        3,
        2,
        3,
        3,
        5,
        8,
        15,
        2,
        7,
        23,
        105
      ],
      "active": [],
      "kind": "matrix",
      "columns": 4,
      "result": 23,
      "output": [
        23,
        105
      ]
    }

Expected final state

Smallest nonnegative solution 23, period 105.

Complexity and input bounds

Family: Number theory. Time complexity: O(k (max modulus + log period)) bounded merge.

Implementation detail: Up to four residues -12..12 with moduli 1..12 keep the bounded offset search and integer arithmetic small. Downloads return the smallest nonnegative solution, write solution/period on success and return -1 for incompatibility. The empty system has solution zero and period one. This version uses bounded search rather than modular-inverse acceleration.

Space complexity: O(1) merge scratch, plus input/output and saved frames.

Working-space bounds describe algorithm state and any explicitly noted output, excluding the visualization's saved timeline. Recording frames can use more memory than running the function alone. Here n is sequence length, V and E are vertex and edge counts, and other parameters refer to the named input dimensions.

residues -12..12 | matching moduli 1..12; 1..4 congruences. Moduli need not be coprime.

The playground validates these limits before starting. Downloaded functions are callable implementations, with parameter and output-buffer contracts in their comments; they do not all repeat the playground's input validation.

Common mistakes and limitations

Normalize negative residues. Shared factors do not always cause failure: only disagreeing residues modulo the gcd do. The combined period is an lcm rather than an unconditional product.

Further reading

For background on algorithm analysis and the JavaScript function interface:

Editorial and testing approach · Browse all algorithm guides

Complete JavaScript implementation

javascript
1
2
3
4
5
6
// Generalized CRT: n 0..4 residues -12..12 and moduli 1..12, not necessarily coprime. Returns smallest nonnegative solution x, or -1 if incompatible. On success writes [x, lcm of moduli]; output capacity at least 2. Empty system returns 0 with period 1. Uses gcd compatibility and a bounded offset search, not modular-inverse acceleration; O(n*(max modulus + log period)) time, O(1) scratch. Reference snippets assume validated playground inputs. Fixed scratch buffers have 256 slots. Sorting variants may use a different traversal strategy than the animation.
function algorithm(residues, moduli, n, output) {
    let x = 0; let period = 1; let a = 0; let b = 0; let remainder = 0; let residue = 0; let reduced = 0; let candidate = 0;
    for (let i = 0; i < n; i++) { a = period; b = moduli[i]; while (b != 0) { remainder = a%b; a = b; b = remainder; } residue = ((residues[i]%moduli[i])+moduli[i])%moduli[i]; if ((residue-x)%a != 0) { return -1; } reduced = 0; for (let t = 0; t < moduli[i]; t += a) { reduced++; } for (let t = 0; t < reduced; t++) { candidate = x+period*t; if (candidate%moduli[i] == residue) { x = candidate; break; } } period *= reduced; }
    output[0] = x; output[1] = period; return x;
}

Source

Authoritative arithmetic reference, not an asserted original CRT paper. The playground implements a bounded gcd-compatible offset merge for general moduli.