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

Introduction to Chinese Remainder Theorem

Last Updated : 24 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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
Program to find remainder when large number is divided by 11
Given a number n, the task is to find the remainder when n is divided by 11. The input of number may be very large. Examples: Input : str = 13589234356546756 Output : 6 Input : str = 3435346456547566345436457867978 Output : 4 Since the given number can be very large, we can not use n % 11. There are some steps that needs to be used to find remainde
6 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
Quotient and remainder dividing by 2^k (a power of 2)
Given a positive integer n as a dividend and another number m (a form of 2^k), find the quotient and remainder without performing actual division Examples: Input : n = 43, m = 8Output : Quotient = 5, Remainder = 3 Input : n = 58, m = 16Output : Quotient = 3, Remainder = 10 An approach using bitwise operation In this, we are using a bitwise represen
4 min read
Program to find Quotient And Remainder in Java
The remainder is the integer left over after dividing one integer by another. The quotient is the quantity produced by the division of two numbers. For example, (7/2) = 3 In the above expression 7 is divided by 2, so the quotient is 3 and the remainder is 1. Approach: Divide the dividend by the divisor using / operator. Both dividend and divisor ca
2 min read
Article Tags :
Practice Tags :