The Wayback Machine - https://web.archive.org/web/20240617133101/https://www.geeksforgeeks.org/modular-division/
Open In App

Modular Division

Last Updated : 27 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given three positive numbers a, b and m. Compute a/b under modulo m. The task is basically to find a number c such that (b * c) % m = a % m.
Examples: 

Input  : a  = 8, b = 4, m = 5
Output : 2

Input  : a  = 8, b = 3, m = 5
Output : 1
Note that (1*3)%5 is same as 8%5

Input  : a  = 11, b = 4, m = 5
Output : 4
Note that (4*4)%5 is same as 11%5

Following articles are prerequisites for this. 
Modular multiplicative inverse 
Extended Euclidean algorithms 
Can we always do modular division? 
The answer is “NO”. First of all, like ordinary arithmetic, division by 0 is not defined. For example, 4/0 is not allowed. In modular arithmetic, not only 4/0 is not allowed, but 4/12 under modulo 6 is also not allowed. The reason is, 12 is congruent to 0 when modulus is 6.
When is modular division defined? 
Modular division is defined when modular inverse of the divisor exists. The inverse of an integer ‘x’ is another integer ‘y’ such that (x*y) % m = 1 where m is the modulus. 
When does inverse exist? As discussed here, inverse a number ‘a’ exists under modulo ‘m’ if ‘a’ and ‘m’ are co-prime, i.e., GCD of them is 1.
How to find modular division? 

The task is to compute a/b under modulo m.
1) First check if inverse of b under modulo m exists or not. 
    a) If inverse doesn't exists (GCD of b and m is not 1), 
          print "Division not defined"
    b) Else return  "(inverse * a) % m" 

 

C++




// C++ program to do modular division
#include<iostream>
using namespace std;
 
// C++ function for extended Euclidean Algorithm
int gcdExtended(int a, int b, int *x, int *y);
 
// Function to find modulo inverse of b. It returns
// -1 when inverse doesn't
int modInverse(int b, int m)
{
    int x, y; // used in extended GCD algorithm
    int g = gcdExtended(b, m, &x;, &y;);
 
    // Return -1 if b and m are not co-prime
    if (g != 1)
        return -1;
 
    // m is added to handle negative x
    return (x%m + m) % m;
}
 
// Function to compute a/b under modulo m
void modDivide(int a, int b, int m)
{
    a = a % m;
    int inv = modInverse(b, m);
    if (inv == -1)
       cout << "Division not defined";
    else
       cout << "Result of division is " << (inv * a) % m;
}
 
// C function for extended Euclidean Algorithm (used to
// find modular inverse.
int gcdExtended(int a, int b, int *x, int *y)
{
    // Base Case
    if (a == 0)
    {
        *x = 0, *y = 1;
        return b;
    }
 
    int x1, y1; // To store results of recursive call
    int gcd = gcdExtended(b%a, a, &x1;, &y1;);
 
    // Update x and y using results of recursive
    // call
    *x = y1 - (b/a) * x1;
    *y = x1;
 
    return gcd;
}
 
// Driver Program
int main()
{
    int  a  = 8, b = 3, m = 5;
    modDivide(a, b, m);
    return 0;
}
 
//this code is contributed by khushboogoyal499


C




// C program to do modular division
#include <stdio.h>
 
// C function for extended Euclidean Algorithm
int gcdExtended(int a, int b, int *x, int *y);
 
// Function to find modulo inverse of b. It returns
// -1 when inverse doesn't
int modInverse(int b, int m)
{
    int x, y; // used in extended GCD algorithm
    int g = gcdExtended(b, m, &x;, &y;);
 
    // Return -1 if b and m are not co-prime
    if (g != 1)
        return -1;
 
    // m is added to handle negative x
    return (x%m + m) % m;
}
 
// Function to compute a/b under modulo m
void modDivide(int a, int b, int m)
{
    a = a % m;
    int inv = modInverse(b, m);
    if (inv == -1)
     printf ("Division not defined");
    else
    {
      int c = (inv * a) % m ;
       printf ("Result of division is %d", c) ;
    }
}
 
// C function for extended Euclidean Algorithm (used to
// find modular inverse.
int gcdExtended(int a, int b, int *x, int *y)
{
    // Base Case
    if (a == 0)
    {
        *x = 0, *y = 1;
        return b;
    }
 
    int x1, y1; // To store results of recursive call
    int gcd = gcdExtended(b%a, a, &x1;, &y1;);
 
    // Update x and y using results of recursive
    // call
    *x = y1 - (b/a) * x1;
    *y = x1;
 
    return gcd;
}
 
// Driver Program
int main()
{
    int  a  = 8, b = 3, m = 5;
    modDivide(a, b, m);
    return 0;
}


Java




// java program to do modular division
 
import java.io.*;
import java.lang.Math;
 
public class GFG {
 
    static int gcd(int a,int b){
        if (b == 0){
            return a;
        }        
        return gcd(b, a % b);
    }
     
    // Function to find modulo inverse of b. It returns
    // -1 when inverse doesn't
    // modInverse works for prime m
    static int modInverse(int b,int m){
        int g = gcd(b, m) ;
        if (g != 1)
            return -1;
        else
        {
            //If b and m are relatively prime,
            //then modulo inverse is b^(m-2) mode m
            return (int)Math.pow(b, m - 2) % m;
        }
    }
     
    // Function to compute a/b under modulo m
    static void modDivide(int a,int b,int m){
        a = a % m;
        int inv = modInverse(b,m);
        if(inv == -1){
            System.out.println("Division not defined");
        }  
        else{
             System.out.println("Result of Division is " + ((inv*a) % m));
        }
    } 
     
    // Driver Program
    public static void main(String[] args) {
        int a = 8;
        int b = 3;
        int m = 5;
        modDivide(a, b, m);
    }
}
 
// The code is contributed by Gautam goel (gautamgoel962)


Python3




# Python3 program to do modular division
import math
 
# Function to find modulo inverse of b. It returns
# -1 when inverse doesn't
# modInverse works for prime m
def modInverse(b,m):
    g = math.gcd(b, m)
    if (g != 1):
        # print("Inverse doesn't exist")
        return -1
    else:
        # If b and m are relatively prime,
        # then modulo inverse is b^(m-2) mode m
        return pow(b, m - 2, m)
 
 
# Function to compute a/b under modulo m
def modDivide(a,b,m):
    a = a % m
    inv = modInverse(b,m)
    if(inv == -1):
        print("Division not defined")
    else:
        print("Result of Division is ",(inv*a) % m)
 
# Driver Program
a = 8
b = 3
m = 5
modDivide(a, b, m)
 
# This code is Contributed by HarendraSingh22


C#




using System;
 
// C# program to do modular division
class GFG {
 
  // Recursive Function  to find
  // GCD of two numbers
  static int gcd(int a,int b){
    if (b == 0){
      return a;
    }        
    return gcd(b, a % b);
  }
 
  // Function to find modulo inverse of b. It returns
  // -1 when inverse doesn't
  // modInverse works for prime m
  static int modInverse(int b,int m){
    int g = gcd(b, m) ;
    if (g != 1){
      return -1;
    }       
    else
    {
 
      //If b and m are relatively prime,
      //then modulo inverse is b^(m-2) mode m
      return (int)Math.Pow(b, m - 2) % m;
    }
  }
 
  // Function to compute a/b under modulo m
  static void modDivide(int a,int b,int m){
    a = a % m;
    int inv = modInverse(b,m);
    if(inv == -1){
      Console.WriteLine("Division not defined");
    }  
    else{
      Console.WriteLine("Result of Division is " + ((inv*a) % m));
    }
  } 
 
  // Driver Code
  static void Main() {
    int a = 8;
    int b = 3;
    int m = 5;
    modDivide(a, b, m);
  }
}
 
// The code is contributed by Gautam goel (gautamgoel962)


Javascript




<script>
// JS program to do modular division
function gcd(a, b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
 
// Function to find modulo inverse of b. It returns
// -1 when inverse doesn't
// modInverse works for prime m
function modInverse(b,m)
{
    g = gcd(b, m) ;
    if (g != 1)
        return -1;
    else
    {
        //If b and m are relatively prime,
        //then modulo inverse is b^(m-2) mode m
        return Math.pow(b, m - 2, m);
    }
}
 
// Function to compute a/b under modulo m
function modDivide(a,b,m)
{
    a = a % m;
    inv = modInverse(b,m);
    if(inv == -1)
        document.write("Division not defined");
    else
        document.write("Result of Division is ",(inv*a) % m);
}
 
// Driver Program
a = 8;
b = 3;
m = 5;
modDivide(a, b, m);
 
// This code is Contributed by phasing17
</script>


PHP




<?php
// PHP program to do modular division
 
// Function to find modulo inverse of b.
// It returns -1 when inverse doesn't
function modInverse($b, $m)
{
    $x = 0;
    $y = 0; // used in extended GCD algorithm
    $g = gcdExtended($b, $m, $x, $y);
 
    // Return -1 if b and m are not co-prime
    if ($g != 1)
        return -1;
 
    // m is added to handle negative x
    return ($x % $m + $m) % $m;
}
 
// Function to compute a/b under modulo m
function modDivide($a, $b, $m)
{
    $a = $a % $m;
    $inv = modInverse($b, $m);
    if ($inv == -1)
        echo "Division not defined";
    else
        echo "Result of division is " .
                      ($inv * $a) % $m;
}
 
// function for extended Euclidean Algorithm
// (used to find modular inverse.
function gcdExtended($a, $b, &$x, &$y)
{
    // Base Case
    if ($a == 0)
    {
        $x = 0;
        $y = 1;
        return $b;
    }
 
    $x1 = 0;
    $y1 = 0; // To store results of recursive call
    $gcd = gcdExtended($b % $a, $a, $x1, $y1);
 
    // Update x and y using results of
    // recursive call
    $x = $y1 - (int)($b / $a) * $x1;
    $y = $x1;
 
    return $gcd;
}
 
// Driver Code
$a = 8;
$b = 3;
$m = 5;
modDivide($a, $b, $m);
 
// This code is contributed by mits
?>


Output: 

Result of division is 1

Modular division is different from addition, subtraction and multiplication. 
One difference is division doesn’t always exist (as discussed above). Following is another difference. 
 

Below equations are valid
(a * b) % m = ((a % m) * (b % m)) % m
(a + b) % m = ((a % m) + (b % m)) % m

// m is added to handle negative numbers
(a - b + m) % m = ((a % m) - (b % m) + m) % m 

But, 
(a / b) % m may NOT be same as ((a % m)/(b % m)) % m

For example, a = 10, b = 5, m = 5. 
   (a / b) % m is 2, but ((a % m) / (b % m)) % m 
                          is not defined.

References: 
http://www.doc.ic.ac.uk/~mrh/330tutor/ch03.html

 



Previous Article
Next Article

Similar Reads

Modular Exponentiation (Power in Modular Arithmetic)
Given three numbers x, y and p, compute (xy) % p. Examples : Input: x = 2, y = 3, p = 5 Output: 3 Explanation: 2^3 % 5 = 8 % 5 = 3. Input: x = 2, y = 5, p = 13 Output: 6 Explanation: 2^5 % 13 = 32 % 13 = 6.Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. We have discussed recursive and iterative solutions for powe
9 min read
Trick for modular division ( (x1 * x2 .... xn) / b ) mod (m)
Given integers x1, x2, x3......xn, b, and m, we are supposed to find the result of ((x1*x2....xn)/b)mod(m). Example 1: Suppose that we are required to find (55C5)%(1000000007) i.e ((55*54*53*52*51)/120)%1000000007 Naive Method : Simply calculate the product (55*54*53*52*51)= say x,Divide x by 120 and then take its modulus with 1000000007 Using Modu
9 min read
Benefits of Double Division Operator over Single Division Operator in Python
The Double Division operator in Python returns the floor value for both integer and floating-point arguments after division. C/C++ Code # A Python program to demonstrate use of # &amp;quot;//&amp;quot; for both integers and floating points print(5//2) print(-5//2) print(5.0//2) Output: 2 -3 2.0 The time complexity of the program is O(1) as it conta
2 min read
Number of solutions to Modular Equations
Given A and B, the task is to find the number of possible values that X can take such that the given modular equation (A mod X) = B holds good. Here, X is also called a solution of the modular equation. Examples: Input : A = 26, B = 2Output : 6Explanation:X can be equal to any of {3, 4, 6, 8, 12, 24} as A modulus any of these values equals 2 i. e.,
13 min read
Python Program for Number of solutions to Modular Equations
Given A and B, the task is to find the number of possible values that X can take such that the given modular equation (A mod X) = B holds good. Here, X is also called a solution of the modular equation. Examples: Input : A = 26, B = 2Output : 6ExplanationX can be equal to any of {3, 4, 6, 8,12, 24} as A modulus any of these valuesequals 2 i. e., (2
6 min read
Modular exponentiation (Recursive)
Given three numbers a, b and c, we need to find (ab) % cNow why do “% c” after exponentiation, because ab will be really large even for relatively small values of a, b and that is a problem because the data type of the language that we try to code the problem, will most probably not let us store such a large number.Examples: Input : a = 2312 b = 34
6 min read
Modular Exponentiation of Complex Numbers
Given four integers A, B, K, M. The task is to find (A + iB)K % M which is a complex number too. A + iB represents a complex number. Examples: Input : A = 2, B = 3, K = 4, M = 5 Output: 1 + i*0 Input : A = 7, B = 3, K = 10, M = 97 Output: 25 + i*29 Prerequisite: Modular Exponentiation Approach: An efficient approach is similar to the modular expone
7 min read
Modular Multiplication
Below are some interesting properties of Modular Multiplication (a x b) mod m = ((a mod m) x (b mod m)) mod m (a x b x c) mod m = ((a mod m) x (b mod m) x (c mod m)) mod m The same property holds for more than three numbers. The above formula is the extended version of the following formula: Example 1: Find the remainder of 15 x 17 x 19 when divide
3 min read
Modular Addition
Below are some interesting properties of Modular Addition: (a + b) mod m = ((a mod m) + (b mod m)) mod m (a + b + c) mod m = ((a mod m) + (b mod m) + (c mod m)) mod m Example 1: Find the remainder of 22 + 26 + 29 when divided by 5. Solution: On dividing 22 by 5 we get 2 as remainder. On dividing 26 by 5 we get 1 as remainder. On dividing 29 by 5 we
2 min read
Count array elements having modular inverse under given prime number P equal to itself
Given an array arr[] of size N and a prime number P, the task is to count the elements of the array such that modulo multiplicative inverse of the element under modulo P is equal to the element itself. Examples: Input: arr[] = {1, 6, 4, 5}, P = 7Output: 2Explanation:Modular multiplicative inverse of arr[0](=1) under modulo P(= 7) is arr[0](= 1) its
5 min read