The Wayback Machine - https://web.archive.org/web/20240926231207/https://www.geeksforgeeks.org/introduction-to-chinese-remainder-theorem/
Open In App

Introduction to Chinese Remainder Theorem

Last Updated : 24 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

We are given two arrays num[0..k-1] and rem[0..k-1]. In num[0..k-1], every pair is coprime (gcd for every pair is 1). We need to find minimum positive number x such that: 

     x % num[0]    =  rem[0], 
x % num[1] = rem[1],
.......................
x % num[k-1] = rem[k-1]


Basically, we are given k numbers which are pairwise coprime, and given remainders of these numbers when an unknown number x is divided by them. We need to find the minimum possible value of x that produces given remainders.
Examples : 
 

Input:  num[] = {5, 7}, rem[] = {1, 3}
Output: 31
Explanation:
31 is the smallest number such that:
(1) When we divide it by 5, we get remainder 1.
(2) When we divide it by 7, we get remainder 3.

Input: num[] = {3, 4, 5}, rem[] = {2, 3, 1}
Output: 11
Explanation:
11 is the smallest number such that:
(1) When we divide it by 3, we get remainder 2.
(2) When we divide it by 4, we get remainder 3.
(3) When we divide it by 5, we get remainder 1.


Chinese Remainder Theorem states that there always exists an x that satisfies given congruences.
Let num[0], num[1], …num[k-1] be positive integers that are pairwise coprime. Then, for any given sequence of integers rem[0], rem[1], … rem[k-1], there exists an integer x solving the following system of simultaneous congruences.
 

chineseremainder


The first part is clear that there exists an x. The second part basically states that all solutions (including the minimum one) produce the same remainder when divided by-product of num[0], num[1], .. num[k-1]. In the above example, the product is 3*4*5 = 60. And 11 is one solution, other solutions are 71, 131, .. etc. All these solutions produce the same remainder when divided by 60, i.e., they are of form 11 + m*60 where m >= 0.
A Naive Approach to find x is to start with 1 and one by one increment it and check if dividing it with given elements in num[] produces corresponding remainders in rem[]. Once we find such an x, we return it. 
Below is the implementation of Naive Approach.
 

C++
// A C++ program to demonstrate working of Chinese remainder
// Theorem
#include<bits/stdc++.h>
using namespace std;

// k is size of num[] and rem[].  Returns the smallest
// number x such that:
//  x % num[0] = rem[0], 
//  x % num[1] = rem[1], 
//  ..................
//  x % num[k-2] = rem[k-1]
// Assumption: Numbers in num[] are pairwise coprime 
// (gcd for every pair is 1)
int findMinX(int num[], int rem[], int k)
{
    int x = 1; // Initialize result

    // As per the Chinese remainder theorem,
    // this loop will always break.
    while (true)
    {
        // Check if remainder of x % num[j] is 
        // rem[j] or not (for all j from 0 to k-1)
        int j;
        for (j=0; j<k; j++ )
            if (x%num[j] != rem[j])
               break;

        // If all remainders matched, we found x
        if (j == k)
            return x;

        // Else try next number
        x++;
    }

    return x;
}

// Driver method
int main(void)
{
    int num[] = {3, 4, 5};
    int rem[] = {2, 3, 1};
    int k = sizeof(num)/sizeof(num[0]);
    cout << "x is " << findMinX(num, rem, k);
    return 0;
}
Java
// A Java program to demonstrate the working of Chinese remainder
// Theorem
import java.io.*;

class GFG {
    
    // k is size of num[] and rem[].  Returns the smallest
    // number x such that:
    //  x % num[0] = rem[0], 
    //  x % num[1] = rem[1], 
    //  ..................
    //  x % num[k-2] = rem[k-1]
    // Assumption: Numbers in num[] are pairwise coprime 
    // (gcd for every pair is 1)
    static int findMinX(int num[], int rem[], int k)
    {
        int x = 1; // Initialize result
     
        // As per the Chinese remainder theorem,
        // this loop will always break.
        while (true)
        {
            // Check if remainder of x % num[j] is 
            // rem[j] or not (for all j from 0 to k-1)
            int j;
            for (j=0; j<k; j++ )
                if (x%num[j] != rem[j])
                   break;
     
            // If all remainders matched, we found x
            if (j == k)
                return x;
     
            // Else try next number
            x++;
        }
     
    }
     
    // Driver method
    public static void main(String args[])
    {
        int num[] = {3, 4, 5};
        int rem[] = {2, 3, 1};
        int k = num.length;
        System.out.println("x is " + findMinX(num, rem, k));
    }
}

/*This code is contributed by Nikita Tiwari.*/
Python3
# A Python3 program to demonstrate 
# working of Chinise remainder Theorem

# k is size of num[] and rem[]. 
# Returns the smallest number x 
# such that:
# x % num[0] = rem[0], 
# x % num[1] = rem[1], 
# ..................
# x % num[k-2] = rem[k-1]
# Assumption: Numbers in num[] 
# are pairwise coprime (gcd for
# every pair is 1)
def findMinX(num, rem, k):
    x = 1; # Initialize result

    # As per the Chinise remainder
    # theorem, this loop will
    # always break.
    while(True):
        
        # Check if remainder of 
        # x % num[j] is rem[j] 
        # or not (for all j from 
        # 0 to k-1)
        j = 0;
        while(j < k):
            if (x % num[j] != rem[j]):
                break;
            j += 1;

        # If all remainders 
        # matched, we found x
        if (j == k):
            return x;

        # Else try next number
        x += 1;

# Driver Code
num = [3, 4, 5];
rem = [2, 3, 1];
k = len(num);
print("x is", findMinX(num, rem, k));

# This code is contributed by mits
C#
// C# program to demonstrate working
// of Chinise remainder Theorem
using System;

class GFG
{
    
    // k is size of num[] and rem[]. 
    // Returns the smallest
    // number x such that:
    // x % num[0] = rem[0], 
    // x % num[1] = rem[1], 
    // ..................
    // x % num[k-2] = rem[k-1]
    // Assumption: Numbers in num[] 
    // are pairwise coprime 
    // (gcd for every pair is 1)
    static int findMinX(int []num, int []rem,
                        int k)
    {
        
        // Initialize result
        int x = 1; 
    
        // As per the Chinese remainder theorem,
        // this loop will always break.
        while (true)
        {
            // Check if remainder of x % num[j] is 
            // rem[j] or not (for all j from 0 to k-1)
            int j;
            for (j = 0; j < k; j++ )
                if (x % num[j] != rem[j])
                break;
    
            // If all remainders matched, we found x
            if (j == k)
                return x;
    
            // Else try next number
            x++;
        }
    
    }
    
    // Driver code
    public static void Main()
    {
        int []num = {3, 4, 5};
        int []rem = {2, 3, 1};
        int k = num.Length;
        Console.WriteLine("x is " + findMinX(num, 
                                        rem, k));
    }
}

// This code is contributed by Sam007.
JavaScript
<script>

// A javascript program to demonstrate the working of Chinese remainder
// Theorem
   
// k is size of num and rem.  Returns the smallest
// number x such that:
//  x % num[0] = rem[0], 
//  x % num[1] = rem[1], 
//  ..................
//  x % num[k-2] = rem[k-1]
// Assumption: Numbers in num are pairwise coprime 
// (gcd for every pair is 1)
function findMinX(num , rem , k)
{
    var x = 1; // Initialize result
 
    // As per the Chinese remainder theorem,
    // this loop will always break.
    while (true)
    {
        // Check if remainder of x % num[j] is 
        // rem[j] or not (for all j from 0 to k-1)
        var j;
        for (j=0; j<k; j++ )
            if (x%num[j] != rem[j])
               break;
 
        // If all remainders matched, we found x
        if (j == k)
            return x;
 
        // Else try next number
        x++;
    }
 
}
 
// Driver method
var num = [3, 4, 5];
var rem = [2, 3, 1];
var k = num.length;
document.write("x is " + findMinX(num, rem, k));

// This code is contributed by 29AjayKumar 

</script>
PHP
<?php
// A PHP program to demonstrate 
// working of Chinise remainder Theorem

// k is size of num[] and rem[]. 
// Returns the smallest number x 
// such that:
// x % num[0] = rem[0], 
// x % num[1] = rem[1], 
// ..................
// x % num[k-2] = rem[k-1]
// Assumption: Numbers in num[] 
// are pairwise coprime (gcd for
// every pair is 1)
function findMinX($num, $rem, $k)
{
    $x = 1; // Initialize result

    // As per the Chinise remainder
    // theorem, this loop will
    // always break.
    while (true)
    {
        // Check if remainder of 
        // x % num[j] is  rem[j] 
        // or not (for all j from 
        // 0 to k-1)
        $j;
        for ($j = 0; $j < $k; $j++ )
            if ($x % $num[$j] != $rem[$j])
            break;

        // If all remainders 
        // matched, we found x
        if ($j == $k)
            return $x;

        // Else try next number
        $x++;
    }

    return $x;
}

// Driver Code
$num = array(3, 4, 5);
$rem = array(2, 3, 1);
$k = sizeof($num);
echo "x is " , 
    findMinX($num, $rem, $k);

// This code is contributed by ajit
?>

Output : 

x is 11

Time Complexity  : O(M), M is the product of all elements of num[] array.

Auxiliary Space : O(1)


See below link for an efficient method to find x.
Chinese Remainder Theorem | Set 2 (Inverse Modulo based Implementation)
 



Previous Article
Next Article

Similar Reads

Compute nCr % p | Set 4 (Chinese Remainder theorem with Lucas Theorem)
Given three numbers n, r and p, the task is to compute the value of nCr % p. Note: p is a square-free number and the largest prime factor of p ≤ 50. Examples: Input: n = 10, r = 2, p = 13Output: 6Explanation: 10C2 is 45 and 45 % 13= 6 Input: n = 6, r = 2, p = 13Output: 2 Approach: We have already discussed several other approaches of this problem.
10 min read
Implementation of Chinese Remainder theorem (Inverse Modulo based implementation)
We are given two arrays num[0..k-1] and rem[0..k-1]. In num[0..k-1], every pair is coprime (gcd for every pair is 1). We need to find minimum positive number x such that: x % num[0] = rem[0], x % num[1] = rem[1], ....................... x % num[k-1] = rem[k-1] Example: Input: num[] = {3, 4, 5}, rem[] = {2, 3, 1} Output: 11 Explanation: 11 is the sm
11 min read
Using Chinese Remainder Theorem to Combine Modular equations
Given N modular equations: A ? x1mod(m1) . . A ? xnmod(mn) Find x in the equation A ? xmod(m1*m2*m3..*mn) where mi is prime, or a power of a prime, and i takes values from 1 to n. The input is given as two arrays, the first being an array containing values of each xi, and the second array containing the set of values of each prime. mi Output an int
12 min read
Chinese Remainder Theorem in Python
Consider two arrays "num[0..k-1]" and "rem[0..k-1]", where every pair of numbers in num is coprime (i.e., the greatest common divisor (gcd) of every pair is 1). The goal is to find the minimum positive number "x" such that: x % num[0] = rem[0] x % num[1] = rem[1] ..... x % num[k-1] = rem[k-1] In simpler terms, given "k" numbers that are pairwise co
4 min read
Chinese Postman or Route Inspection | Set 1 (introduction)
Chinese Postman Problem is a variation of Eulerian circuit problem for undirected graphs. An Euler Circuit is a closed walk that covers every edge once starting and ending position is same. Chinese Postman problem is defined for connected and undirected graph. The problem is to find shortest path or circuity that visits every edge of the graph at l
3 min read
Cook–Levin theorem or Cook's theorem
In computational complexity theory, the Cook–Levin theorem, also known as Cook's theorem, states that the Boolean satisfiability problem is NP-complete. That is, it is in NP, and any problem in NP can be reduced in polynomial time by a deterministic Turing machine to the Boolean satisfiability problem. Stephen Arthur Cook and L.A. Levin in 1973 ind
4 min read
Largest number by which given 3 numbers should be divided such that they leaves same remainder
Given three numbers, our task is to find the largest number by which when given 3 numbers are divided leads to same remainder. It may be assumed that all given numbers are given in increasing order. Examples: Input : a = 62, b = 132, c = 237 Output : 35 35 leads to same remainder 27 when divides 62, 132 and 237. Input : a = 74, b = 272, c = 584 Out
9 min read
Generate Array whose sum of all K-size subarrays divided by N leaves remainder X
Given three integer N, K and X, the task is to create an array of length N such that sum of all its K-length subarrays modulo N is X.Examples: Input: N = 6, K = 3, X = 3 Output: 9 6 6 9 6 6 Explanation: All subarrays of length 3 and their respective sum%N values are as follows: [9, 6, 6] Sum = 21 % 6 = 3 [6, 6, 9] sum = 21 % 6 = 3 [6, 9, 6] sum = 2
4 min read
Program to find remainder when large number is divided by r
Given a number N, the task is to find the remainder when N is divided by R (a two-digit Number). The input of the Number may be very large. Examples: Input: N = 13589234356546756, R = 13 Output: 11 Input: N = 3435346456547566345436457867978, R = 17 Output: 13Get the digit of N one by one from left to right.For each digit, combine with next digit if
9 min read
Quotient - Remainder Sort
Quotient - Remainder Sort is a non-comparison based sorting algorithm. Steps to perform Quotient - Remainder sort as described below : Find MIN and MAX of the array.Create an ROW*COL matrix consisting of 0s, where ROW = MAX/MIN+1 and COL = MIN.For each element in the input array, calculate quotient and remainder and store in the matrix[quotient][re
7 min read
Minimum integer such that it leaves a remainder 1 on dividing with any element from the range [2, N]
Given an integer N, the task is to find the minimum possible integer X such that X % M = 1 for all M from the range [2, N]Examples: Input: N = 5 Output: 61 61 % 2 = 1 61 % 3 = 1 61 % 4 = 1 61 % 5 = 1Input: N = 2 Output: 3 Approach: Find the lcm of all the integers from the range [2, N] and store it in a variable lcm. Now we know that lcm is the sma
5 min read
Minimum number of operations on a binary string such that it gives 10^A as remainder when divided by 10^B
Given a binary string str of length N and two integers A and B such that 0 ? A &lt; B &lt; n. The task is to count the minimum number of operations on the string such that it gives 10A as remainder when divided by 10B. An operation means changing 1 to 0 or 0 to 1. Examples: Input: str = "1001011001", A = 3, B = 6 Output: 2 The string after 2 operat
5 min read
Find the remainder when First digit of a number is divided by its Last digit
Given a number N, find the remainder when the first digit of N is divided by its last digit.Examples: Input: N = 1234 Output: 1 First digit = 1 Last digit = 4 Remainder = 1 % 4 = 1 Input: N = 5223 Output: 2 First digit = 5 Last digit = 3 Remainder = 5 % 3 = 2 Approach: Find the first digit and the last digit of the number. Find then the remainder w
5 min read
Find permutation with maximum remainder Sum
Given an integer N, the task is to find a permutation of the integers from 1 to N such that [Tex]\sum_{i=1}^{N}P_i\mod i [/Tex]is maximum. Examples: Input: N = 3 Output: 3 1 2 Sum of the remainder values is (0 + 1 + 2) = 3 which is the maximum possible.Input: N = 5 Output: 5 1 2 3 4 Approach: As it is known that the maximum value of a number X afte
4 min read
Count of integers obtained by replacing ? in the given string that give remainder 5 when divided by 13
Given string str of length N. The task is to find the number of integers obtained by replacing '?' with any digit such that the formed integer gives remainder 5 when it is divided by 13. Numbers can also begin with zero. The answer can be very large, so, output answer modulo 109 + 7. Examples: Input: str = "?44" Output: 1 Only possible number is 04
12 min read
Maximum possible remainder when an element is divided by other element in the array
Given an array arr[] of N integers, the task is to find the maximum mod value for any pair (arr[i], arr[j]) from the array.Examples: Input: arr[] = {2, 4, 1, 5, 3, 6} Output: 5 (5 % 6) = 5 is the maximum possible mod value.Input: arr[] = {6, 6, 6, 6} Output: 0 Approach: It is known that when an integer is divided by some other integer X, the remain
4 min read
Count subarrays such that remainder after dividing sum of elements by K gives count of elements
Given an array arr[] of size N and an element K. The task is to find the number of sub-arrays of the given array such that the remainder when dividing the sum of its elements by K is equal to the number of elements in the subarray. Examples: Input: arr[] = {1, 4, 2, 3, 5}, K = 4 Output: 4 {1}, {1, 4, 2}, {4, 2} and {5} are the only valid subarrays.
9 min read
Find numbers that divide X and Y to produce the same remainder
Given two integers X and Y, the task is to find and print the numbers that divide X and Y to produce the same remainder.Examples: Input: X = 1, Y = 5 Output: 1, 2, 4 Explanation: Let the number be M. It can be any value in the range [1, 5]: If M = 1, 1 % 1 = 0 and 5 % 1 = 0 If M = 2, 1 % 2 = 1 and 5 % 2 = 1 If M = 3, 1 % 3 = 1 and 5 % 3 = 2 If M =
9 min read
Largest number less than or equal to Z that leaves a remainder X when divided by Y
Given three integers x, y, z, the task is to find the largest non-negative number less than or equal to z that leaves a remainder x when divided by y (Given x &lt; y). If no such number exists then the output will be -1. Examples: Input: x = 1, y = 5, z = 8 Output: 6 Explanation: 6 is the largest number less than 8 which when divided by 5 leaves a
5 min read
Find Quotient and Remainder of two integer without using division operators
Given two positive integers dividend and divisor, our task is to find quotient and remainder. The use of division or mod operator is not allowed. Examples: Input : dividend = 10, divisor = 3 Output : 3, 1 Explanation: The quotient when 10 is divided by 3 is 3 and the remainder is 1. Input : dividend = 11, divisor = 5 Output : 2, 1 Explanation: The
10 min read
Check if the remainder of N-1 factorial when divided by N is N-1 or not
Given an integer N where 1 ? N ? 105, the task is to find whether (N-1)! % N = N - 1 or not.Examples: Input: N = 3 Output: Yes Explanation: Here, n = 3 so (3 - 1)! = 2! = 2 =&gt; 2 % 3 = 2 which is N - 1 itself Input: N = 4 Output: No Explanation: Here, n = 4 so (4 - 1)! = 3! = 6 =&gt; 6 % 3 = 0 which is not N - 1. Naive approach: To solve the ques
6 min read
First number to leave an odd remainder after repetitive division by 2
Given two integers A and B, the task is to print the integer among the two, which will be converted to an odd integer by a smaller number of divisions by 2. If both the numbers get converted to an odd integer after the same number of operations, print -1. Examples: Input: A = 10 and B = 8 Output: 10 Explanation: Step 1: A/2 = 5, B/2 = 4 Hence, A is
9 min read
Smallest subarray whose product leaves remainder K when divided by size of the array
Given an array arr[] of N integers and an integer K, the task is to find the length of the smallest subarray whose product when divided by N gives remainder K. If no such subarray exists the print "-1". Examples: Input: N = 3, arr = {2, 2, 6}, K = 1 Output: 2 Explanation: All possible subarrays are: {2} -&gt; 2(mod 3) = 2 {2} -&gt; 2(mod 3) = 2 {6}
6 min read
Count of Nodes whose children gives same remainder when divided by K
Given a binary tree and an integer K. The task is to count the number of nodes having children that give the same remainder when divided by K. Print “-1” if no such node exists. Examples: Input: 2 K = 2 / \ 3 5 / / \ 7 8 6Output: 2Explanation: Children of 2 are 3 and 5. Both give remainder 1 with 2Similarly for 5, both children give remainder as 0
6 min read
Count divisors which generates same Quotient and Remainder
Given a positive integer N, the task is to find the count of all the numbers M such that when the number N is divided by M, the quotient is equal to its remainder i.e (?N/M? = N mod M) where ? ? denotes the floor value of a given number. Examples: Input: N = 8Output: 2Explanation: When 8 is divided by 3 and 7, it returns the same Quotient and Remai
7 min read
Check if a number S can be made divisible by D by repeatedly adding the remainder to S
Given two integers S and D, the task is to check if the integer S can be made divisible by D or not by repeatedly adding S modulo D to S. If S is divisible by D, then print "Yes". Otherwise, print "No". Examples: Input: S = 3, D = 6Output: YesExplanation: Lets say that the value on the ith interval mod D is V(i) i.e., V(i) = (V(i - 1) + V(i - 1) %
5 min read
Maximize remainder of sum of a pair of array elements with different parity modulo K
Given an array arr[] of size N, consisting of N / 2 even and odd integers each, and an integer K, the task is to find the maximum remainder of sum of a pair of array elements of different parity modulo K. Examples: Input: arr[] = {3, 2, 4, 11, 6, 7}, K = 7Output: 6Explanation: Sum of a pair of array elements = 2 + 11Sum % K = 13 % 7 = 6.Therefore,
7 min read
Count of pairs of integers up to X and Y that generates equal Quotient and Remainder
Given two integers X and Y, the task is to count the number of pairs (m, n), such that m / n = m % n and 1 ? m ? x and 1 ? n ? y. Examples: Input: X = 4, Y = 5 Output: 2 Explanation: The pairs (3, 2) and (4, 3) satisfy the condition. Input: X = 3, Y = 1 Output : 0 Approach: The given problem can be solved based on the following observations: For th
4 min read
Maximize K to make given array Palindrome when each element is replaced by its remainder with K
Given an array A[] containing N positive integers, the task is to find the largest possible number K, such that after replacing all elements by the elements modulo K(A[i]=A[i]%K, for all 0&lt;=i&lt;N), the array becomes a palindrome. If K is infinitely large, print -1. Examples: Input: A={1, 2, 3, 4}, N=4Output:1Explanation:For K=1, A becomes {1%1,
7 min read
Check whether each Array element can be reduced to minimum element by replacing it with remainder with some X
Given an array arr[] of non-negative integers, the task is to check whether all array elements can be reduced to the minimum element in the array by choosing any positive integer X and update an array element arr[i] to arr[i]%X. If it is possible to do so, then print Yes. Otherwise, print No. Examples: Input: arr[] = {1, 1, 3, 4}Output: YesExplanat
6 min read
Article Tags :
Practice Tags :