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
Modular Arithmetic Modular arithmetic is a system of arithmetic for numbers where numbers "wrap around" after reaching a certain value, called the modulus. It mainly uses remainders to get the value after wrap around. It is often referred to as "clock arithmetic. As you can see, the time values wrap after reaching 12
10 min read
Modular Exponentiation (Power in Modular Arithmetic) Given three integers x, n, and M, compute (x^n) % M (remainder when x raised to the power n is divided by M).Examples : Input: x = 3, n = 2, M = 4Output: 1Explanation: 32 % 4 = 9 % 4 = 1.Input: x = 2, n = 6, M = 10Output: 4Explanation: 26 % 10 = 64 % 10 = 4.Table of Content[Naive Approach] Repeated
6 min read
Modular multiplicative inverse Given two integers A and M, find the modular multiplicative inverse of A under modulo M.The modular multiplicative inverse is an integer X such that:A X â¡ 1 (mod M) Note: The value of X should be in the range {1, 2, ... M-1}, i.e., in the range of integer modulo M. ( Note that X cannot be 0 as A*0 m
15+ min read
Multiplicative order In number theory, given an integer A and a positive integer N with gcd( A , N) = 1, the multiplicative order of a modulo N is the smallest positive integer k with A^k( mod N ) = 1. ( 0 < K < N ) Examples : Input : A = 4 , N = 7 Output : 3 explanation : GCD(4, 7) = 1 A^k( mod N ) = 1 ( smallest
7 min read
Modular Multiplication Given three integers a, b, and M, where M is the modulus. Compute the result of the modular multiplication of a and b under modulo M.((aÃb) mod M)Examples:Input: a = 5, b = 3, M = 11Output: 4Explanation: a à b = 5 à 3 = 15, 15 % 11 = 4, so the result is 4.Input: a = 12, b = 15, M = 7Output: 5Explana
6 min read
Modular Division 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 = 13Output: 5Explanation: The modular inverse of 2 modulo 13 is 7, so (10 / 2) % 13 = (10 à 7) % 13 =
13 min read
Modulus on Negative Numbers The modulus operator, denoted as %, returns the remainder when one number (the dividend) is divided by another number (the divisor).Modulus of Positive NumbersProblem: What is 7 mod 5?Solution: From Quotient Remainder Theorem, Dividend=Divisor*Quotient + Remainder7 = 5*1 + 2, which gives 2 as the re
7 min read
Problems on Modular Arithmetic
Euler's criterion (Check if square root under modulo p exists)Given a number 'n' and a prime p, find if square root of n under modulo p exists or not. A number x is square root of n under modulo p if (x*x)%p = n%p. Examples : Input: n = 2, p = 5 Output: false There doesn't exist a number x such that (x*x)%5 is 2 Input: n = 2, p = 7 Output: true There exists a
11 min read
Find sum of modulo K of first N natural numberGiven two integer N ans K, the task is to find sum of modulo K of first N natural numbers i.e 1%K + 2%K + ..... + N%K. Examples : Input : N = 10 and K = 2. Output : 5 Sum = 1%2 + 2%2 + 3%2 + 4%2 + 5%2 + 6%2 + 7%2 + 8%2 + 9%2 + 10%2 = 1 + 0 + 1 + 0 + 1 + 0 + 1 + 0 + 1 + 0 = 5.Recommended PracticeReve
9 min read
How to compute mod of a big number?Given a big number 'num' represented as string and an integer x, find value of "num % a" or "num mod a". Output is expected as an integer. Examples : Input: num = "12316767678678", a = 10 Output: num (mod a) ? 8 The idea is to process all digits one by one and use the property that xy (mod a) ? ((x
4 min read
Exponential Squaring (Fast Modulo Multiplication)Given two numbers base and exp, we need to compute baseexp under Modulo 10^9+7 Examples: Input : base = 2, exp = 2Output : 4Input : base = 5, exp = 100000Output : 754573817In competitions, for calculating large powers of a number we are given a modulus value(a large prime number) because as the valu
12 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 a
9 min read
Modular MultiplicationGiven three integers a, b, and M, where M is the modulus. Compute the result of the modular multiplication of a and b under modulo M.((aÃb) mod M)Examples:Input: a = 5, b = 3, M = 11Output: 4Explanation: a à b = 5 à 3 = 15, 15 % 11 = 4, so the result is 4.Input: a = 12, b = 15, M = 7Output: 5Explana
6 min read
Difference between Modulo and ModulusIn the world of Programming and Mathematics we often encounter the two terms "Modulo" and "Modulus". In programming we use the operator "%" to perform modulo of two numbers. It basically finds the remainder when a number x is divided by another number N. It is denoted by : x mod N where x : Dividend
2 min read
Modulo Operations in Programming With Negative ResultsIn programming, the modulo operation gives the remainder or signed remainder of a division, after one integer is divided by another integer. It is one of the most used operators in programming. This article discusses when and why the modulo operation yields a negative result. Examples: In C, 3 % 2 r
15+ min read
Modulo 10^9+7 (1000000007)In most programming competitions, we are required to answer the result in 10^9+7 modulo. The reason behind this is, if problem constraints are large integers, only efficient algorithms can solve them in an allowed limited time.What is modulo operation: The remainder obtained after the division opera
10 min read
Fibonacci modulo pThe Fibonacci sequence is defined as F_i = F_{i-1} + F_{i-2} where F_1 = 1 and F_2 = 1 are the seeds. For a given prime number p, consider a new sequence which is (Fibonacci sequence) mod p. For example for p = 5, the new sequence would be 1, 1, 2, 3, 0, 3, 3, 1, 4, 0, 4, 4 ⦠The minimal zero of the
5 min read
Modulo of a large Binary StringGiven a large binary string str and an integer K, the task is to find the value of str % K.Examples: Input: str = "1101", K = 45 Output: 13 decimal(1101) % 45 = 13 % 45 = 13 Input: str = "11010101", K = 112 Output: 101 decimal(11010101) % 112 = 213 % 112 = 101 Approach: It is known that (str % K) wh
5 min read
Modular multiplicative inverse from 1 to nGive a positive integer n, find modular multiplicative inverse of all integer from 1 to n with respect to a big prime number, say, 'prime'. The modular multiplicative inverse of a is an integer 'x' such that. a x ? 1 (mod prime) Examples: Input : n = 10, prime = 17 Output : 1 9 6 13 7 3 5 15 2 12 Ex
9 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 suc
6 min read
Chinese Remainder Theorem
Introduction to Chinese Remainder TheoremWe 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
7 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[
11 min read
Cyclic Redundancy Check and Modulo-2 DivisionCyclic Redundancy Check or CRC is a method of detecting accidental changes/errors in the communication channel. CRC uses Generator Polynomial which is available on both sender and receiver side. An example generator polynomial is of the form like x3 + x + 1. This generator polynomial represents key
15+ min read
Using Chinese Remainder Theorem to Combine Modular equationsGiven 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
12 min read