Given three positive integers a, b, and M, the objective is to find (a/b) % M i.e., find the value of (a × b-1 ) % M, where b-1 is the modular inverse of b modulo M.
Examples:
Input: a = 10, b = 2, M = 13
Output: 5
Explanation: The modular inverse of 2 modulo 13 is 7, so (10 / 2) % 13 = (10 × 7) % 13 = 70 % 13 = 5.
Input: a = 7, b = 4, M = 9
Output: 4
Explanation: The modular inverse of 4 modulo 9 is 7, so (7 / 4) % 9 = (7 × 7) % 9 = 49 % 9 = 4.
Modular division is the process of dividing one number by another within the rules of modular arithmetic. Unlike regular arithmetic, modular systems do not support direct division. Instead, division is performed by multiplying the dividend by the modular multiplicative inverse of the divisor under a given modulus.
In simple terms, to compute (a/b) % M we instead calculate (a × b-1 ) % M where b-1 is the modular inverse of b
modulo M
( i.e., b × b-1 ≡ 1 mod M ).
The following articles are prerequisites for this.
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 the 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 we discussed, inverse of a number 'a' exists under modulo 'm' if 'a' and 'm' are co-prime, i.e., GCD of them is 1.
Modular Arithmetic Rules:
(a * b) % m = ((a % m) * (b % m)) % m
(a + b) % m = ((a % m) + (b % m)) % m
(a - b) % m = ((a % m) - (b % m) + m) % m // m is added to handle negative numbers
But,
(a / b) % m not 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.
[Approach 1] Using Fermat's Little Theorem (when M
is prime) O(log M) Time and O(1) Space
If the modulus m
is a prime number, we can use Fermat’s Little Theorem to find the modular inverse of b
. According to the theorem, the inverse of b
modulo m
is b M-2 % M. So we can use Modular Exponentiation for computing b M-2 % M.
C++
#include <iostream>
#include <algorithm>
using namespace std;
// Binary exponentiation
int power(int base, int exp, int mod) {
int result = 1;
base %= mod;
while (exp > 0) {
if (exp % 2 == 1)
result = (1LL * result * base) % mod;
base = (1LL * base * base) % mod;
exp /= 2;
}
return result;
}
// Modular inverse using Fermat's Little Theorem
int modInverse(int b, int m) {
return power(b, m - 2, m);
}
int modDivide(int a, int b, int m) {
// Division not possible
if (b == 0 || __gcd(b, m) != 1)
return -1;
int inv = modInverse(b, m);
return (1LL * a * inv) % m;
}
int main() {
int a = 10, b = 2, m = 13;
cout << modDivide(a, b, m) << "\n";
return 0;
}
C
#include <stdio.h>
// Binary exponentiation
int power(int base, int exp, int mod) {
int result = 1;
base %= mod;
while (exp > 0) {
if (exp % 2 == 1)
result = (1LL * result * base) % mod;
base = (1LL * base * base) % mod;
exp /= 2;
}
return result;
}
// GCD
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
// Modular inverse
int modInverse(int b, int m) {
return power(b, m - 2, m);
}
int modDivide(int a, int b, int m) {
// Division not possible
if (b == 0 || gcd(b, m) != 1)
return -1;
int inv = modInverse(b, m);
return (1LL * a * inv) % m;
}
int main() {
int a = 10, b = 2, m = 13;
printf("%d\n", modDivide(a, b, m));
return 0;
}
Java
class GfG {
// Binary exponentiation
static int power(int base, int exp, int mod) {
int result = 1;
base %= mod;
while (exp > 0) {
if ((exp & 1) == 1)
result = (int)((1L * result * base) % mod);
base = (int)((1L * base * base) % mod);
exp >>= 1;
}
return result;
}
// Function to compute GCD of two numbers
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static int modInverse(int b, int m) {
return power(b, m - 2, m);
}
static int modDivide(int a, int b, int m) {
// Division not possible
if (b == 0 || gcd(b, m) != 1)
return -1;
int inv = modInverse(b, m);
return (int)((1L * a * inv) % m);
}
public static void main(String[] args) {
int a = 10, b = 2, m = 13;
System.out.println(modDivide(a, b, m));
}
}
Python
# Binary exponentiation
def power(base, exp, mod):
result = 1
base %= mod
while exp > 0:
if exp % 2 == 1:
result = (result * base) % mod
base = (base * base) % mod
exp //= 2
return result
# function to calculate GCD
def gcd(a, b):
while b:
a, b = b, a % b
return a
def modInverse(b, m):
return power(b, m - 2, m)
def modDivide(a, b, m):
# Division not possible
if b == 0 or gcd(b, m) != 1:
return -1
inv = modInverse(b, m)
return (a * inv) % m
if __name__ == "__main__":
a, b, m = 10, 2, 13
print(modDivide(a, b, m))
C#
using System;
class GfG {
// Binary exponentiation
static int Power(int baseVal, int exp, int mod) {
int result = 1;
baseVal %= mod;
while (exp > 0) {
if ((exp & 1) == 1)
result = (int)((1L * result * baseVal) % mod);
baseVal = (int)((1L * baseVal * baseVal) % mod);
exp >>= 1;
}
return result;
}
// Function to compute GCD of two numbers
static int GCD(int a, int b) {
return b == 0 ? a : GCD(b, a % b);
}
static int ModInverse(int b, int m) {
return Power(b, m - 2, m);
}
static int ModDivide(int a, int b, int m) {
// Division not possible
if (b == 0 || GCD(b, m) != 1)
return -1;
int inv = ModInverse(b, m);
return (int)((1L * a * inv) % m);
}
static void Main() {
int a = 10, b = 2, m = 13;
Console.WriteLine(ModDivide(a, b, m));
}
}
JavaScript
// Function to compute (base^exp) % mod using binary exponentiation
function power(base, exp, mod) {
let result = 1;
base %= mod;
while (exp > 0) {
if (exp % 2 === 1) {
result = (result * base) % mod;
}
base = (base * base) % mod;
exp = Math.floor(exp / 2);
}
return result;
}
// Function to compute GCD of two numbers
function gcd(a, b) {
return b === 0 ? a : gcd(b, a % b);
}
// Function to compute modular inverse using Fermat's Little Theorem
function modInverse(b, m) {
return power(b, m - 2, m); // Only valid if m is prime
}
// Function to perform modular division (a / b) % m
function modDivide(a, b, m) {
// Division not defined
if (b === 0 || gcd(b, m) !== 1) {
return -1;
}
let inv = modInverse(b, m);
return (a * inv) % m;
}
// Driver Code
let a = 10, b = 2, m = 13;
console.log(modDivide(a, b, m));
[Approach 2] Extended Euclidean Algorithm O(log M) Time and O(1) Space
To find the modular inverse of a number b modulo M using the Extended Euclidean Algorithm, we aim to solve the equation b * x + M * y = gcd(b, M). If the greatest common divisor gcd(b, M) is 1, then x is the modular inverse of b modulo M. The Extended Euclidean Algorithm computes both gcd and the coefficients x and y that satisfy this linear combination. Once x is found, we take its positive equivalent by calculating (x % M + M) % M to get the correct modular inverse. This approach works for any modulus M, not necessarily prime.
C++
#include <iostream>
using namespace std;
// Extended Euclidean Algorithm to find gcd and coefficients x, y
int gcdExtended(int a, int b, int &x, int &y) {
if (a == 0) {
x = 0;
y = 1;
return b;
}
int x1, y1;
int gcd = gcdExtended(b % a, a, x1, y1);
x = y1 - (b / a) * x1;
y = x1;
return gcd;
}
// Compute modular inverse of b modulo M
int modInverse(int b, int M) {
int x, y;
int g = gcdExtended(b, M, x, y);
if (g != 1)
return -1;
// Ensure positive result
return (x % M + M) % M;
}
// Perform (a / b) % M
int modDivide(int a, int b, int M) {
a %= M;
int inv = modInverse(b, M);
if (inv == -1)
return -1;
return (1LL * a * inv) % M;
}
int main() {
int a = 10, b = 2, M = 13;
int result = modDivide(a, b, M);
cout << result << "\n";
return 0;
}
C
#include <stdio.h>
// Extended Euclidean Algorithm to find
// gcd and coefficients x, y
int gcdExtended(int a, int b, int *x, int *y) {
if (a == 0) {
*x = 0;
*y = 1;
return b;
}
int x1, y1;
int gcd = gcdExtended(b % a, a, &x1, &y1);
*x = y1 - (b / a) * x1;
*y = x1;
return gcd;
}
// Function to compute modular inverse of b modulo M
int modInverse(int b, int M) {
int x, y;
int g = gcdExtended(b, M, &x, &y);
if (g != 1)
return -1;
// Ensure positive result
return (x % M + M) % M;
}
// Function to compute (a / b) % M
int modDivide(int a, int b, int M) {
a = a % M;
int inv = modInverse(b, M);
if (inv == -1)
return -1;
return (inv * a) % M;
}
int main() {
int a = 10, b = 2, M = 13;
int result = modDivide(a, b, M);
printf("%d\n", result);
return 0;
}
Java
class GfG {
// Extended Euclidean Algorithm
static int gcdExtended(int a, int b, int[] xy) {
if (a == 0) {
xy[0] = 0;
xy[1] = 1;
return b;
}
int[] xy1 = new int[2];
int gcd = gcdExtended(b % a, a, xy1);
xy[0] = xy1[1] - (b / a) * xy1[0];
xy[1] = xy1[0];
return gcd;
}
// Compute modular inverse of b modulo M
static int modInverse(int b, int M) {
int[] xy = new int[2];
int g = gcdExtended(b, M, xy);
if (g != 1) return -1;
return (xy[0] % M + M) % M;
}
// Perform (a / b) % M
static int modDivide(int a, int b, int M) {
a %= M;
int inv = modInverse(b, M);
if (inv == -1) return -1;
return (int)(((long) a * inv) % M);
}
public static void main(String[] args) {
int a = 10, b = 2, M = 13;
int result = modDivide(a, b, M);
System.out.println(result);
}
}
Python
# Extended Euclidean Algorithm
def gcdExtended(a, b):
if a == 0:
return b, 0, 1
gcd, x1, y1 = gcdExtended(b % a, a)
x = y1 - (b // a) * x1
y = x1
return gcd, x, y
# Compute modular inverse
def modInverse(b, M):
gcd, x, _ = gcdExtended(b, M)
if gcd != 1:
return -1
return (x % M + M) % M
# Perform (a / b) % M
def modDivide(a, b, M):
a %= M
inv = modInverse(b, M)
if inv == -1:
return -1
return (a * inv) % M
if __name__ == "__main__":
a = 10
b = 2
M = 13
result = modDivide(a, b, M)
print(result)
C#
using System;
class GfG {
// Extended Euclidean Algorithm
static int GcdExtended(int a, int b, out int x, out int y) {
if (a == 0) {
x = 0;
y = 1;
return b;
}
int gcd = GcdExtended(b % a, a, out int x1, out int y1);
x = y1 - (b / a) * x1;
y = x1;
return gcd;
}
// Compute modular inverse
static int ModInverse(int b, int M) {
int x, y;
int g = GcdExtended(b, M, out x, out y);
if (g != 1) return -1;
return (x % M + M) % M;
}
// Perform (a / b) % M
static int ModDivide(int a, int b, int M) {
a %= M;
int inv = ModInverse(b, M);
if (inv == -1) return -1;
return (int)((long)a * inv % M);
}
static void Main() {
int a = 10, b = 2, M = 13;
int result = ModDivide(a, b, M);
Console.WriteLine(result);
}
}
JavaScript
// Extended Euclidean Algorithm
function gcdExtended(a, b) {
if (a === 0) return [b, 0, 1];
const [gcd, x1, y1] = gcdExtended(b % a, a);
const x = y1 - Math.floor(b / a) * x1;
const y = x1;
return [gcd, x, y];
}
// Compute modular inverse
function modInverse(b, M) {
const [gcd, x] = gcdExtended(b, M);
if (gcd !== 1) return -1;
return (x % M + M) % M;
}
// Perform (a / b) % M
function modDivide(a, b, M) {
a %= M;
const inv = modInverse(b, M);
if (inv === -1) return -1;
return (a * inv) % M;
}
// Driver Code
const a = 10, b = 2, M = 13;
console.log(modDivide(a, b, M));
Similar Reads
Basics & Prerequisites
Data Structures
Array Data Structure GuideIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem