The Wayback Machine - https://web.archive.org/web/20240930233936/https://www.geeksforgeeks.org/implementation-of-chinese-remainder-theorem-inverse-modulo-based-implementation/
Open In App

Implementation of Chinese Remainder theorem (Inverse Modulo based implementation)

Last Updated : 28 Nov, 2022
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]

Example: 

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.

We strongly recommend to refer below post as a prerequisite for this.

Chinese Remainder Theorem | Set 1 (Introduction)
We have discussed a Naive solution to find minimum x. In this article, an efficient solution to find x is discussed.
The solution is based on below formula.

x =  ( ? (rem[i]*pp[i]*inv[i]) ) % prod
   Where 0 <= i <= n-1

rem[i] is given array of remainders

prod is product of all given numbers
prod = num[0] * num[1] * ... * num[k-1]

pp[i] is product of all divided by num[i]
pp[i] = prod / num[i]

inv[i] = Modular Multiplicative Inverse of 
         pp[i] with respect to num[i]

Example: 

Let us take below example to understand the solution
   num[] = {3, 4, 5}, rem[] = {2, 3, 1}
   prod  = 60 
   pp[]  = {20, 15, 12}
   inv[] = {2,  3,  3}  // (20*2)%3 = 1, (15*3)%4 = 1
                        // (12*3)%5 = 1

   x = (rem[0]*pp[0]*inv[0] + rem[1]*pp[1]*inv[1] + 
        rem[2]*pp[2]*inv[2]) % prod
     = (2*20*2 + 3*15*3 + 1*12*3) % 60
     = (80 + 135 + 36) % 60
     = 11

Refer this for nice visual explanation of above formula.

Below is the implementation of above formula. We can use Extended Euclid based method discussed here to find inverse modulo. 

C++




// A C++ program to demonstrate 
// working of Chinese remainder
// Theorem
#include <bits/stdc++.h>
using namespace std;
  
// Returns modulo inverse of a 
// with respect to m using
// extended Euclid Algorithm. 
// Refer below post for details:
// multiplicative-inverse-under-modulo-m/
int inv(int a, int m)
{
    int m0 = m, t, q;
    int x0 = 0, x1 = 1;
  
    if (m == 1)
        return 0;
  
    // Apply extended Euclid Algorithm
    while (a > 1) {
        // q is quotient
        q = a / m;
  
        t = m;
  
        // m is remainder now, process same as
        // euclid's algo
        m = a % m, a = t;
  
        t = x0;
  
        x0 = x1 - q * x0;
  
        x1 = t;
    }
  
    // Make x1 positive
    if (x1 < 0)
        x1 += m0;
  
    return x1;
}
  
// 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)
{
    // Compute product of all numbers
    int prod = 1;
    for (int i = 0; i < k; i++)
        prod *= num[i];
  
    // Initialize result
    int result = 0;
  
    // Apply above formula
    for (int i = 0; i < k; i++) {
        int pp = prod / num[i];
        result += rem[i] * inv(pp, num[i]) * pp;
    }
  
    return result % prod;
}
  
// 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
// working of Chinese remainder
// Theorem
import java.io.*;
  
class GFG {
  
    // Returns modulo inverse of a
    // with respect to m using extended
    // Euclid Algorithm. Refer below post for details:
    // multiplicative-inverse-under-modulo-m/
    static int inv(int a, int m)
    {
        int m0 = m, t, q;
        int x0 = 0, x1 = 1;
  
        if (m == 1)
            return 0;
  
        // Apply extended Euclid Algorithm
        while (a > 1) {
            // q is quotient
            q = a / m;
  
            t = m;
  
            // m is remainder now, process
            // same as euclid's algo
            m = a % m;
            a = t;
  
            t = x0;
  
            x0 = x1 - q * x0;
  
            x1 = t;
        }
  
        // Make x1 positive
        if (x1 < 0)
            x1 += m0;
  
        return x1;
    }
  
    // 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)
    {
        // Compute product of all numbers
        int prod = 1;
        for (int i = 0; i < k; i++)
            prod *= num[i];
  
        // Initialize result
        int result = 0;
  
        // Apply above formula
        for (int i = 0; i < k; i++) {
            int pp = prod / num[i];
            result += rem[i] * inv(pp, num[i]) * pp;
        }
  
        return result % prod;
    }
  
    // 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 Chinese remainder 
# Theorem 
  
# Returns modulo inverse of a with 
# respect to m using extended 
# Euclid Algorithm. Refer below 
# post for details: 
# multiplicative-inverse-under-modulo-m/ 
def inv(a, m) : 
      
    m0 = m 
    x0 = 0
    x1 = 1
  
    if (m == 1) : 
        return 0
  
    # Apply extended Euclid Algorithm 
    while (a > 1) : 
        # q is quotient 
        q = a // m 
  
        t = m 
  
        # m is remainder now, process 
        # same as euclid's algo 
        m = a % m 
        a = t 
  
        t = x0 
  
        x0 = x1 - q * x0 
  
        x1 = t 
      
    # Make x1 positive 
    if (x1 < 0) : 
        x1 = x1 + m0 
  
    return x1 
  
# 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) : 
      
    # Compute product of all numbers 
    prod = 1
    for i in range(0, k) : 
        prod = prod * num[i] 
  
    # Initialize result 
    result = 0
  
    # Apply above formula 
    for i in range(0,k): 
        pp = prod // num[i] 
        result = result + rem[i] * inv(pp, num[i]) * pp 
      
      
    return result % prod 
  
# Driver method 
num = [3, 4, 5] 
rem = [2, 3, 1] 
k = len(num) 
print( "x is " , findMinX(num, rem, k)) 
  
# This code is contributed by Nikita Tiwari. 


C#




// A C# program to demonstrate 
// working of Chinese remainder 
// Theorem 
using System; 
  
class GFG 
{ 
    // Returns modulo inverse of 
    // 'a' with respect to 'm' 
    // using extended Euclid Algorithm. 
    // Refer below post for details: 
    // multiplicative-inverse-under-modulo-m/ 
    static int inv(int a, int m) 
    { 
        int m0 = m, t, q; 
        int x0 = 0, x1 = 1; 
      
        if (m == 1) 
        return 0; 
      
        // Apply extended 
        // Euclid Algorithm 
        while (a > 1) 
        { 
            // q is quotient 
            q = a / m; 
      
            t = m; 
      
            // m is remainder now, 
            // process same as 
            // euclid's algo 
            m = a % m; a = t; 
      
            t = x0; 
      
            x0 = x1 - q * x0; 
      
            x1 = t; 
        } 
      
        // Make x1 positive 
        if (x1 < 0) 
        x1 += m0; 
      
        return x1; 
    } 
      
    // 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) 
    { 
        // Compute product 
        // of all numbers 
        int prod = 1; 
        for (int i = 0; i < k; i++) 
            prod *= num[i]; 
      
        // Initialize result 
        int result = 0; 
      
        // Apply above formula 
        for (int i = 0; i < k; i++) 
        { 
            int pp = prod / num[i]; 
            result += rem[i] * 
                    inv(pp, num[i]) * pp; 
        } 
      
        return result % prod; 
    } 
      
    // Driver Code 
    static public 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 ajit 


PHP




<?php 
// PHP program to demonstrate working 
// of Chinese remainder Theorem 
  
// Returns modulo inverse of a with 
// respect to m using extended Euclid 
// Algorithm. Refer below post for details: 
// multiplicative-inverse-under-modulo-m/ 
function inv($a, $m) 
{ 
    $m0 = $m; 
    $x0 = 0; 
    $x1 = 1; 
  
    if ($m == 1) 
    return 0; 
  
    // Apply extended Euclid Algorithm 
    while ($a > 1) 
    { 
        // q is quotient 
        $q = (int)($a / $m); 
  
        $t = $m; 
  
        // m is remainder now, process 
        // same as euclid's algo 
        $m = $a % $m; 
        $a = $t; 
  
        $t = $x0; 
  
        $x0 = $x1 - $q * $x0; 
  
        $x1 = $t; 
    } 
  
    // Make x1 positive 
    if ($x1 < 0) 
    $x1 += $m0; 
  
    return $x1; 
} 
  
// 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) 
{ 
    // Compute product of all numbers 
    $prod = 1; 
    for ($i = 0; $i < $k; $i++) 
        $prod *= $num[$i]; 
  
    // Initialize result 
    $result = 0; 
  
    // Apply above formula 
    for ($i = 0; $i < $k; $i++) 
    { 
        $pp = (int)$prod / $num[$i]; 
        $result += $rem[$i] * inv($pp, 
                    $num[$i]) * $pp; 
    } 
  
    return $result % $prod; 
} 
  
// 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 mits 
?> 


Javascript




<script>
// Javascript program to demonstrate working
// of Chinese remainder Theorem
  
// Returns modulo inverse of a with
// respect to m using extended Euclid
// Algorithm. Refer below post for details:
// multiplicative-inverse-under-modulo-m/
function inv(a, m)
{
    let m0 = m;
    let x0 = 0;
    let x1 = 1;
  
    if (m == 1)
    return 0;
  
    // Apply extended Euclid Algorithm
    while (a > 1)
    {
        // q is quotient
        let q = parseInt(a / m);
  
        let t = m;
  
        // m is remainder now, process
        // same as euclid's algo
        m = a % m;
        a = t;
  
        t = x0;
  
        x0 = x1 - q * x0;
  
        x1 = t;
    }
  
    // Make x1 positive
    if (x1 < 0)
    x1 += m0;
  
    return x1;
}
  
// 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)
{
    // Compute product of all numbers
    let prod = 1;
    for (let i = 0; i < k; i++)
        prod *= num[i];
  
    // Initialize result
    let result = 0;
  
    // Apply above formula
    for (let i = 0; i < k; i++)
    {
        pp = parseInt(prod / num[i]);
        result += rem[i] * inv(pp,
                    num[i]) * pp;
    }
  
    return result % prod;
}
  
// Driver Code
let num = new Array(3, 4, 5);
let rem = new Array(2, 3, 1);
let k = num.length;
document.write("x is " + findMinX(num, rem, k));
  
// This code is contributed by _saurabh_jaiswal
</script>


Output: 

x is 11

Time Complexity : O(N*LogN)

Auxiliary Space : O(1)

 



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
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
Introduction to Chinese Remainder Theorem
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 th
8 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
Maximum frequency of a remainder modulo 2i
Given an octal number N, the task is to convert the number to decimal and then find the modulo with every power of 2 i.e. 2i such that i > 0 and 2i < N, and print the maximum frequency of the modulo.Examples: Input: N = 13 Output: 2 Octal(13) = decimal(11) 11 % 2 = 1 11 % 4 = 3 11 % 8 = 3 3 occurs the most i.e. 2 times. Input: N = 21 Output:
11 min read
Program to find remainder without using modulo or % operator
Given two numbers 'num' and 'divisor', find remainder when 'num' is divided by 'divisor'. The use of modulo or % operator is not allowed.Examples : Input: num = 100, divisor = 7 Output: 2 Input: num = 30, divisor = 9 Output: 3 Method 1 : C/C++ Code // C++ program to find remainder without using // modulo operator #include <iostream> using nam
9 min read
Nearest smaller number to N having multiplicative inverse under modulo N equal to that number
Given a prime number N, the task is to find the closest smaller number than N such that modulo multiplicative inverse of a number under modulo N is equal to the number itself. Examples: Input: N = 7Output: 6Explanation:Modulo multiplicative inverse of all possible natural numbers from 1 to less than N are:Modulo multiplicative inverse of 1 under mo
3 min read
Quotient Remainder Theorem
The Quotient Remainder Theorem is a fundamental result in arithmetic and algebra that describes the relationship between dividend, divisor, quotient, and remainder. This theorem is crucial in understanding division in the set of integers and has significant applications in number theory, computer science, and engineering. Table of Content What is t
8 min read
Finding Inverse of a Square Matrix using Cayley Hamilton Theorem in MATLAB
Matrix is the set of numbers arranged in rows & columns in order to form a Rectangular array. Here, those numbers are called the entries or elements of that matrix. A Rectangular array of (m*n) numbers in the form of 'm' horizontal lines (rows) & 'n' vertical lines (called columns), is called a matrix of order m by n, which is written as m
4 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
Check if final remainder is present in original Array by reducing it based on given conditions
Given an array arr[] of Natural numbers, the task is to remove one element from front and one element from end and find their product and then divide the product by middle element of the array and append remainder we got in the end of the array and continue the same operation until size of array becomes 2. Now when at last array contains only two e
13 min read
Sort the given stack elements based on their modulo with K
Given a stack of integers and an integer K, the task is to sort the elements of the given stack using another stack in the increasing order of their modulo with K. If two numbers have the same remainder then the smaller number should come first.Examples Input: stack = {10, 3, 2, 6, 12}, K = 4 Output: 12 2 6 10 3 {12, 2, 6, 10, 3} is the required so
7 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
Array-Based Queues vs List-Based Queues
Queues:A queue is a linear data structure in which elements are inserted from one end called the rear end and deleted from another end called the front end. It follows FIFO (First In First Out) technique.Insertion in the queue is called enqueue and deletion in the queue is called dequeue.Queues can be implemented in two ways: Array-based queues and
3 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 < B < 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 < 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 => 2 % 3 = 2 which is N - 1 itself Input: N = 4 Output: No Explanation: Here, n = 4 so (4 - 1)! = 3! = 6 => 6 % 3 = 0 which is not N - 1. Naive approach: To solve the ques
6 min read