The Wayback Machine - https://web.archive.org/web/20240711065504/https://www.geeksforgeeks.org/modular-arithmetic-for-competitive-programming/
Open In App

Modular Arithmetic for Competitive Programming

Last Updated : 09 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 underlying concepts, and practical applications. By understanding and implementing modular arithmetic, programmers can effectively manage and manipulate large integers, enhancing their skills in competitive programming.

What is Modular Arithmetic?

Modular arithmetic is a branch of arithmetic mathematics related to the “mod” functionality. It is a system of arithmetic for integers, where numbers “wrap around” upon reaching a certain value, known as the modulus. In its most elementary form, it is arithmetic done with a count that resets itself to zero every time a certain whole number N greater than one, known as the modulus (mod), has been reached.

Modular Arithmetic Operations

The implementation of modular arithmetic involves various operations such as addition, subtraction, multiplication, division, and exponentiation. Here are some rules for these operations:

  • Modular Addition: (a + b) mod m = ((a mod m) + (b mod m)) mod m1.
  • Modular Subtraction: The same rule as modular addition applies.
  • Modular Multiplication: (a * b) mod m = ((a mod m) * (b mod m)) mod m1.
  • Modular Division: (a / b) mod m = (a * (inverse of b if exists)) mod m1. The modular inverse of a mod m exists only if a and m are relatively prime i.e., gcd(a, m) = 1.
  • Modular Exponentiation: Finding a^b mod m is the modular exponentiation.

Idea behind Modular Arithmetic:

The concept of modular arithmetic is to find the remainder of a number upon division by another number. For example, if we have “A mod B” and we increase ‘A‘ by a multiple of ‘B‘, we will end up in the same spot, i.e.,”A mod B = (A + K * B) mod B” for any integer ‘K‘.

Visualizing the Idea behind Modular Arithmetic:

To visualize the modulo operator, we can use circles. We write 0 at the top of a circle and continuing clockwise writing integers 1, 2, … up to one less than the modulus. For example, a clock with the 12 replaced by a 0 would be the circle for a modulus of 12.

To find the result of “A mod B” we can follow these steps:

  1. Construct this clock for size ‘B’.
  2. Start at 0 and move around the clock ‘A’ steps.
  3. Wherever we land is our solution. (If the number is positive we step clockwise, if it’s negative we step counter-clockwise.)

Here are some examples of modular arithmetic operations:

  • 8 mod 4 = 0: With a modulus of 4 we make a clock with numbers 0, 1, 2, 3. We start at 0 and go through 8 numbers in a clockwise sequence 1, 2, 3, 0. We ended up at 0 so 8 mod 4 = 0.
  • 7 mod 2 = 1: With a modulus of 2 we make a clock with numbers 0, 1. We start at 0 and go through 7 numbers in a clockwise sequence 1, 0, 1, 0, 1, 0, 1. We ended up at 1 so 7 mod 2 = 1.
  • -5 mod 3 = 1: With a modulus of 3 we make a clock with numbers 0, 1, 2. We start at 0 and go through 5 numbers in counter-clockwise sequence (5 is negative) 2, 1, 0, 2, 1. We ended up at 1 so -5 mod 3 = 1.

Implementation of Modular Arithmetic

Below code performs modular addition, subtraction, multiplication, and division.

C++




#include <bits/stdc++.h>
using namespace std;
 
// Function to perform Modular Addition
int modAdd(int a, int b, int m)
{
    return ((a % m) + (b % m)) % m;
}
 
// Function to perform Modular Subtraction
int modSub(int a, int b, int m)
{
    return ((a % m) - (b % m) + m)
        % m; // Adding m to handle negative numbers
}
 
// Function to perform Modular Multiplication
int modMul(int a, int b, int m)
{
    return ((a % m) * (b % m)) % m;
}
 
// Function to calculate power of a number
int power(int x, unsigned int y, int p)
{
    int res = 1;
    x = x % p;
    if (x == 0)
        return 0;
    while (y > 0) {
        if (y & 1)
            res = (res * x) % p;
        y = y >> 1;
        x = (x * x) % p;
    }
    return res;
}
 
// Function to find modular inverse of a under modulo m
// Assumption: m is prime
int modInverse(int a, int m) { return power(a, m - 2, m); }
 
// Function to perform Modular Division
int modDiv(int a, int b, int m)
{
    a = a % m;
    int inv = modInverse(b, m);
    return (inv * a) % m;
}
 
int main()
{
    int a = 10, b = 20, m = 7;
    cout << "Modular Addition: " << modAdd(a, b, m) << endl;
    cout << "Modular Subtraction: " << modSub(a, b, m)
        << endl;
    cout << "Modular Multiplication: " << modMul(a, b, m)
        << endl;
    cout << "Modular Division: " << modDiv(a, b, m) << endl;
    return 0;
}


Java




class GFG {
    // Function to perform Modular Addition
    static int modAdd(int a, int b, int m)
    {
        return ((a % m) + (b % m)) % m;
    }
 
    // Function to perform Modular Subtraction
    static int modSub(int a, int b, int m)
    {
        return ((a % m) - (b % m) + m)
            % m; // Adding m to handle negative numbers
    }
 
    // Function to perform Modular Multiplication
    static int modMul(int a, int b, int m)
    {
        return ((a % m) * (b % m)) % m;
    }
 
    // Function to calculate power of a number
    static int power(int x, int y, int p)
    {
        int res = 1;
        x = x % p;
        if (x == 0)
            return 0;
        while (y > 0) {
            if ((y & 1) == 1)
                res = (res * x) % p;
            y = y >> 1;
            x = (x * x) % p;
        }
        return res;
    }
 
    // Function to find modular inverse of a under modulo m
    // Assumption: m is prime
    static int modInverse(int a, int m)
    {
        return power(a, m - 2, m);
    }
 
    // Function to perform Modular Division
    static int modDiv(int a, int b, int m)
    {
        a = a % m;
        int inv = modInverse(b, m);
        return (inv * a) % m;
    }
 
    public static void main(String[] args)
    {
        int a = 10, b = 20, m = 7;
        System.out.println("Modular Addition: "
                           + modAdd(a, b, m));
        System.out.println("Modular Subtraction: "
                           + modSub(a, b, m));
        System.out.println("Modular Multiplication: "
                           + modMul(a, b, m));
        System.out.println("Modular Division: "
                           + modDiv(a, b, m));
    }
}
 
// This code is contributed by ragul21


C#




using System;
 
class Program
{
    // Function to perform Modular Addition
    static int ModAdd(int a, int b, int m)
    {
        return ((a % m) + (b % m)) % m;
    }
 
    // Function to perform Modular Subtraction
    static int ModSub(int a, int b, int m)
    {
        return ((a % m) - (b % m) + m) % m;
    }
 
    // Function to perform Modular Multiplication
    static int ModMul(int a, int b, int m)
    {
        return ((a % m) * (b % m)) % m;
    }
 
    // Function to calculate power of a number
    static int Power(int x, uint y, int p)
    {
        int res = 1;
        x = x % p;
        if (x == 0)
            return 0;
        while (y > 0)
        {
            if ((y & 1) == 1)
                res = (res * x) % p;
            y = y >> 1;
            x = (x * x) % p;
        }
        return res;
    }
 
    // Function to find modular inverse of a under modulo m
    // Assumption: m is prime
    static int ModInverse(int a, int m)
    {
        return Power(a, (uint)(m - 2), m);
    }
 
    // Function to perform Modular Division
    static int ModDiv(int a, int b, int m)
    {
        a = a % m;
        int inv = ModInverse(b, m);
        return (inv * a) % m;
    }
 
    static void Main()
    {
        int a = 10, b = 20, m = 7;
        Console.WriteLine("Modular Addition: " + ModAdd(a, b, m));
        Console.WriteLine("Modular Subtraction: " + ModSub(a, b, m));
        Console.WriteLine("Modular Multiplication: " + ModMul(a, b, m));
        Console.WriteLine("Modular Division: " + ModDiv(a, b, m));
    }
}
 
// This code is contributed by shivamgupta310570


Javascript




// Function to perform Modular Addition
function modAdd(a, b, m) {
    return ((a % m) + (b % m) + m) % m; // Adding m to handle negative numbers
}
 
// Function to perform Modular Subtraction
function modSub(a, b, m) {
    return ((a % m) - (b % m) + m) % m; // Adding m to handle negative numbers
}
 
// Function to perform Modular Multiplication
function modMul(a, b, m) {
    return ((a % m) * (b % m) + m) % m; // Adding m to handle negative numbers
}
 
// Function to calculate power of a number
function power(x, y, p) {
    let res = 1;
    x = x % p;
    if (x === 0) return 0;
 
    while (y > 0) {
        if (y & 1) res = (res * x) % p;
        y = y >> 1;
        x = (x * x) % p;
    }
    return res;
}
 
// Function to find modular inverse of a under modulo m
// Assumption: m is prime
function modInverse(a, m) {
    return power(a, m - 2, m);
}
 
// Function to perform Modular Division
function modDiv(a, b, m) {
    a = a % m;
    let inv = modInverse(b, m);
    return (inv * a) % m;
}
 
// Example usage
let a = 10, b = 20, m = 7;
console.log("Modular Addition:", modAdd(a, b, m));
console.log("Modular Subtraction:", modSub(a, b, m));
console.log("Modular Multiplication:", modMul(a, b, m));
console.log("Modular Division:", modDiv(a, b, m));
 
// This code is contributed by shivamgupta310570


Python3




# Function to perform Modular Addition
def mod_add(a, b, m):
    return (a % m + b % m) % m
 
# Function to perform Modular Subtraction
def mod_sub(a, b, m):
    return ((a % m) - (b % m) + m) % m
 
# Function to perform Modular Multiplication
def mod_mul(a, b, m):
    return (a % m * b % m) % m
 
# Function to calculate power of a number
def power(x, y, p):
    res = 1
    x = x % p
    if x == 0:
        return 0
    while y > 0:
        if y & 1:
            res = (res * x) % p
        y = y >> 1
        x = (x * x) % p
    return res
 
# Function to find modular inverse of a under modulo m
# Assumption: m is prime
def mod_inverse(a, m):
    return power(a, m - 2, m)
 
# Function to perform Modular Division
def mod_div(a, b, m):
    a = a % m
    inv = mod_inverse(b, m)
    return (inv * a) % m
 
if __name__ == "__main__":
    a, b, m = 10, 20, 7
    print("Modular Addition:", mod_add(a, b, m))
    print("Modular Subtraction:", mod_sub(a, b, m))
    print("Modular Multiplication:", mod_mul(a, b, m))
    print("Modular Division:", mod_div(a, b, m))
 
# This code is contributed by shivamgupta0987654321


Output

Modular Addition: 2
Modular Subtraction: 4
Modular Multiplication: 4
Modular Division: 4





Use Cases of Modular arithmetic in Competitive Programming:

Modular arithmetic is commanly used in competitive programming and coding contests that require us to calculate the mod of something. It is typically used in combinatorial and probability tasks, where you are asked to calculate a huge number, then told to output it modulo 10^9 + 7. Below are the more use cases of modular arithmetic in CP.

1. Modular arithmetic in Combinatorial Tasks:

In combinatorial tasks, you are often asked to calculate a huge number, then told to output it modulo 10^9 + 7. This is because the number can be so large that it cannot be stored in a variable of any data type. By taking the mod of the number, we reduce its size to a manageable level.

2. Modular arithmetic in Polynomial Arithmetic:

Modular arithmetic is used in polynomial arithmetic to perform addition, subtraction, and multiplication of polynomials under a modulus

3. Modular arithmetic in Hashing Algorithms:

Many hashing algorithms use modular arithmetic to ensure that the hash values they produce fit into a certain range.

4. Modular arithmetic in Probability Tasks:

In probability tasks, you might need to calculate the probability of an event occurring. The probability can be a huge number, and you are often asked to output it modulo 10^9 + 7.

5. Modular arithmetic in Solving Linear Congruence:

Modular arithmetic can be used to solve linear congruence, which are equations of the form ax ≡ b (mod m). These types of problems often appear in number theory and cryptography.

Practice Problems on Modular Arithmetic for CP

Problem

Practice

Find (a^b)%m

Solve

Friends Pairing Problem

Solve

How Many X’s?

Solve

Padovan Sequence

Solve

Matrix Exponentiation

Solve

Mr Modulo and Pairs

Solve

Challenge by Nikitasha

Solve

Rahul and The Lift

Solve

Find the pattern

Solve

nCr mod M | Part 1

Solve



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
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 a
7 min read
Tips and Tricks for Competitive Programmers | Set 2 (Language to be used for Competitive Programming)
This is a question asked quite often as in which language should be preferred to be efficient in competitive programming. It is something one should not worry about as what matters is the logic, not the language. Most of the languages are more or less same, but till now the most preferred language is C++, and here are the reasons. Python Simple and
5 min read
Competitive Programming vs General Programming
Programming enthusiasts face a crossroads - Competitive Programming or General Programming? This article sheds light on the distinctions between Competitive Programming vs General Programming, offering a quick guide for those navigating the coding landscape. Whether you're aiming for speed and precision in competitions or tackling real-world projec
3 min read
Dynamic Programming in Game Theory for Competitive Programming
In the fast-paced world of competitive programming, mastering dynamic programming in game theory is the key to solving complex strategic challenges. This article explores how dynamic programming in game theory can enhance your problem-solving skills and strategic insights, giving you a competitive edge. Whether you're a seasoned coder or a newcomer
15+ min read
Top Programming Languages For Competitive Programming
Building an application, running a server, or even implementing a game needs a programming language as the foundation. There are almost more than 700 programming languages which are the most popular ones and this number will increase day by day. But, you don't need to learn all of them. Having a good command of anyone is enough for you to grow your
13 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 (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
three90RightbarBannerImg