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

Modular Arithmetic

Last Updated : 21 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Modular arithmetic is the branch of arithmetic mathematics related to the “mod” functionality. Basically, modular arithmetic is related to the computation of a “mod” of expressions. Expressions may have digits and computational symbols of addition, subtraction, multiplication, division or any other.

Modular arithmetic, often referred to as “clock arithmetic,” is a system of arithmetic for integers, where numbers wrap around upon reaching a certain value, known as the modulus. This concept is widely used in various fields, including cryptography, computer science, and engineering.

Here we will discuss briefly all modular arithmetic operations.

What is Modular Arithmetic?

In modular arithmetic, numbers are reduced within a certain range, defined by the modulus. For two integers a and b, and a positive integer n, we say that a is congruent to b modulo n if their difference is an integer multiple of n. This is denoted as:

a ≡ b (mod n)

Quotient Remainder Theorem

It states that, for any pair of integers a and b (b is positive), there exist two unique integers q and r such that:

a = b x q + r where 0 <= r < b

Example: If a = 20, b = 6 then q = 3, r = 2 20 = 6 x 3 + 2

Modular Addition

The rule for modular addition is:

(a + b) mod m = ((a mod m) + (b mod m)) mod m

Example:

(15 + 17) % 7
= ((15 % 7) + (17 % 7)) % 7
= (1 + 3) % 7
= 4 % 7
= 4

The same rule is to modular subtraction. We don’t require much modular subtraction but it can also be done in the same way.

Modular Multiplication

The Rule for modular multiplication is:

(a x b) mod m = ((a mod m) x (b mod m)) mod m

Example:

(12 x 13) % 5
= ((12 % 5) x (13 % 5)) % 5
= (2 x 3) % 5
= 6 % 5
= 1

Modular Division

The modular division is totally different from modular addition, subtraction and multiplication. It also does not exist always.

(a / b) mod m is not equal to ((a mod m) / (b mod m)) mod m.

This is calculated using the following formula:

(a / b) mod m = (a x (inverse of b if exists)) mod m

Modular Inverse

The modular inverse of a mod m exists only if a and m are relatively prime i.e. gcd(a, m) = 1. Hence, for finding the inverse of a under modulo m, if (a x b) mod m = 1 then b is the modular inverse of a.

Example: a = 5, m = 7 (5 x 3) % 7 = 1 hence, 3 is modulo inverse of 5 under 7.

Modular Exponentiation

Finding a^b mod m is the modular exponentiation. There are two approaches for this – recursive and iterative.

Example:

a = 5, b = 2, m = 7
(5 ^ 2) % 7 = 25 % 7 = 4

There is often a need to efficiently calculate the value of xn mod m. This can be done in O(logn) time using the following recursion: 

It is important that in the case of an even n, the value of xn/2 is calculated only once.

This guarantees that the time complexity of the algorithm is O(logn) because n is always halved when it is even.

The following function calculates the value of xn mod m:

int modpower(int x, int n, int m) 
{
   if (n == 0) 
       return 1%m;
   long long u = modpower(x,n/2,m);                                              
   u = (u*u)%m;
   if (n%2 == 1) 
       u = (u*x)%m;
   return u;
}
C++
#include<bits/stdc++.h>
#include<iostream>

using namespace std;

//function that calculate modular exponentiation x^n mod m.
int modpower(int x, int n, int m) 
{
    if (n == 0) //base case 
        return 1%m; 
    long long u = modpower(x,n/2,m);  
    u = (u*u)%m;
    if (n%2 == 1) //when 'n' is odd
        u = (u*x)%m;
    return u;
}

//driver function
int main()
{ 
    cout<<modpower(5,2,7)<<endl;
    return 0;
}
C
#include <stdio.h>

//function that calculate modular exponentiation x^n mod m.
int modpower(int x, int n, int m) 
{
    if (n == 0) //base case 
        return 1 % m; 
    long long u = modpower(x, n / 2, m);  
    u = (u * u) % m;
    if (n % 2 == 1) // when 'n' is odd
        u = (u * x) % m;
    return u;
}

//driver function
int main()
{ 
    printf("%d\n", modpower(5, 2, 7));
    return 0;
}
Java
import java.util.*;

class GFG {
    //function that calculate modular exponentiation x^n mod m.
    public static int modpower(int x, int n, int m) {
        if (n == 0) //base case 
            return 1 % m; 
        long u = modpower(x, n / 2, m);  
        u = (u * u) % m;
        if (n % 2 == 1) // when 'n' is odd
            u = (u * x) % m;
        return (int)u;
    }

    //driver function
    public static void main(String[] args) {
        System.out.println(modpower(5, 2, 7));
    }
}
Python
#function that calculate modular exponentiation x^n mod m.
def modpower(x, n, m):
    if n == 0: # base case
        return 1 % m
    u = modpower(x, n // 2, m)
    u = (u * u) % m
    if n % 2 == 1: # when 'n' is odd
        u = (u * x) % m
    return u

#driver function
print(modpower(5, 2, 7))
JavaScript
// function that calculates modular exponentiation x^n mod m.
function modpower(x, n, m) {
    if (n == 0) { // base case
        return 1 % m;
    }
    let u = modpower(x, Math.floor(n / 2), m);
    u = (u * u) % m;
    if (n % 2 == 1) { // when 'n' is odd
        u = (u * x) % m;
    }
    return u;
}

// driver function
console.log(modpower(5, 2, 7));
output:
4

Time complexity: O(logn), because n is always halved when it is even.

Fermat’s theorem states that

                                              xm−1 mod m = 1 

when m is prime and x and m are coprime. This also yields

xk mod m = xk mod (m−1) mod m.

Also Read:

Applications of Modular Arithmetic

1. Cryptography

Modular arithmetic is fundamental in cryptography, particularly in public-key cryptosystems like RSA, which relies on the difficulty of factoring large numbers and properties of modular exponentiation.

2. Computer Science

Modular arithmetic is used in hashing algorithms, checksums, and cryptographic hash functions to ensure data integrity and security.

3. Number Theory

In number theory, modular arithmetic helps solve congruences and Diophantine equations, contributing to the understanding of integer properties and relationships.

4. Digital Signal Processing

Modular arithmetic is used in algorithms for efficient computation in digital signal processing, particularly in the Fast Fourier Transform (FFT) and error-correcting codes.

5. Clock Arithmetic

The concept of modular arithmetic is akin to how clocks work, where the hours wrap around after reaching 12 or 24.

Conclusion – Modular Arithmetic

Modular arithmetic is a powerful mathematical tool with wide-ranging applications in cryptography, computer science, number theory, and digital signal processing. Its properties and rules enable efficient computation and problem-solving in various domains. Understanding modular arithmetic is essential for professionals and researchers in these fields.

FAQs on Modular Arithmetic

What is modular arithmetic?

Modular arithmetic is a system of arithmetic for integers, where numbers wrap around upon reaching a certain value, known as the modulus.

How is modular arithmetic used in cryptography?

Modular arithmetic is fundamental in cryptography, especially in public-key cryptosystems like RSA, which rely on properties of modular exponentiation.

What are the basic operations in modular arithmetic?

The basic operations include addition, subtraction, multiplication, exponentiation, and division, each performed within the confines of a given modulus.

How is modular arithmetic applied in computer science?

It is used in hashing algorithms, checksums, and cryptographic hash functions to ensure data integrity and security.

Why is modular arithmetic important in digital signal processing?

It is used in efficient computation algorithms like the Fast Fourier Transform (FFT) and error-correcting codes, reducing computational complexity.



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
Modular Arithmetic for Competitive Programming
In mathematics, modular arithmetic refers to the arithmetic of integers that wraps around when a certain value is reached, called the modulus. This becomes particularly crucial when handling large numbers in competitive programming. This article "Modular Arithmetic for Competitive Programming" will explore modular arithmetic, its operations, the un
11 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
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
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
XOR of array elements whose modular inverse with a given number exists
Given an array arr[] of length N and a positive integer M, the task is to find the Bitwise XOR of all the array elements whose modular inverse with M exists. Examples: Input: arr[] = {1, 2, 3}, M = 4Output: 2Explanation:Initialize the value xor with 0:For element indexed at 0 i.e., 1, its mod inverse with 4 is 1 because (1 * 1) % 4 = 1 i.e., it exi
7 min read
Modular multiplicative inverse from 1 to n
Give 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 Explanation : For 1, modular inverse is 1 as (1 * 1)
9 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 mod M will never be 1). The multiplicative inverse
15+ min read
How to avoid overflow in modular multiplication?
Consider below simple method to multiply two numbers. C/C++ Code #include &lt;iostream&gt; using namespace std; #define ll long long // Function to multiply two numbers modulo mod ll multiply(ll a, ll b, ll mod) { // Multiply two numbers and then take modulo to prevent // overflow return ((a % mod) * (b % mod)) % mod; } int main() { ll a = 12345678
6 min read