V

Algorithm Visualizer

ZHEN
Share on WeiboShare on XGitHub repositoryAuthor website
Learning ToolsAlgorithm Complexity ReferenceAlgorithm Learning Paths
Data StructuresArrayLinked ListStackQueue and DequeBinary Search TreeBinary HeapHash TableGraphTrieDisjoint Set UnionLRU CacheSkip ListSegment TreeB+ TreeBloom FilterFenwick Tree
SortingBubble SortCocktail Shaker SortBitonic SortSelection SortInsertion SortBinary Insertion SortShell SortMerge SortTop-Down Merge SortQuick SortThree-Way Quick SortDual-Pivot Quick SortHeap SortCounting SortRadix SortBucket Sort
Graph AlgorithmsDijkstra's Shortest PathKruskal's Minimum Spanning TreePrim's Minimum Spanning TreeBellman-Ford Shortest PathsTopological SortFloyd-WarshallStrongly Connected Components2-SATMaximum FlowBipartite MatchingLowest Common AncestorEulerian Path
Dynamic ProgrammingEdit Distance0/1 KnapsackUnbounded KnapsackLongest Common SubsequenceLongest Increasing SubsequenceCoin ChangeStone MergingTraveling Salesperson DPTree Dynamic ProgrammingDigit DPRerooting DP
Backtracking and SearchN-QueensSubsetsPermutationsCombination SumMaze Solving with DFSNumber of IslandsWord SearchSudoku SolverA* Search
StringsKMP String MatchingRabin-Karp String MatchingBoyer-Moore String MatchingManacher's Longest Palindromic SubstringSuffix ArrayLCP ArrayAho-Corasick AutomatonZ Function
Math and Number TheorySieve of EratosthenesLinear SieveEuclidean AlgorithmBinary ExponentiationExtended Euclidean AlgorithmChinese Remainder TheoremEuler's Totient FunctionMiller-Rabin Primality TestFast Fourier TransformPollard's Rho Factorization
Computational GeometryConvex HullRotating CalipersClosest Pair of PointsLine Segment IntersectionBentley-Ottmann Sweep Line
SearchingBinary SearchLower and Upper BoundSearch in a Rotated Sorted ArrayBinary Search on the AnswerTernary Search

Chinese Remainder Theorem

Merge modular congruences with inverses to reconstruct the unique solution modulo the product.

Core idea

For pairwise coprime moduli, construct one basis term per congruence. That term is one under its own modulus and zero under all others, so weighted terms combine independently.

Read the visualization

Each table row builds its partial product, modular inverse, and residue term. The final row adds them and reduces the sum by the full modulus product.

rmMᵢtᵢterm
congruence ①23
congruence ②35
congruence ③27
total

Multiply the pairwise coprime moduli to obtain the combined period M.

1function crt(rs: number[], ms: number[]): number {
2 const M = ms.reduce((p, m) => p * m, 1); // init prime
3 let x = 0;
4 for (let i = 0; i < ms.length; i++) {
5 const Mi = M / ms[i]; // mi: mi down ≡ 0
6 const ti = modInverse(Mi, ms[i]); // expand inv compute inv: current inv down inv 1
7 x += rs[i] * Mi * ti; // term congruence term term
8 }
9 return x % M; // merge, mod M sum one
10}
congruence systemx≡2 (mod 3), x≡3 (mod 5), x≡2 (mod 7)
M3·5·7 = 105
1 / 12

Complexity and tradeoffs

Time: O(k log M). Space: O(k). The direct form assumes pairwise coprime moduli; generalized merging checks gcd compatibility.

Invariant: After a basis term is built, it contributes its requested residue to exactly one congruence and contributes zero to every other congruence.

Where it fits

CRT reconstructs values from modular channels, accelerates large-integer arithmetic, and schedules repeating cycles. Non-coprime moduli require compatibility checks and generalized merging.