The Wayback Machine - https://web.archive.org/web/20240705120952/https://www.geeksforgeeks.org/how-to-avoid-overflow-in-modular-multiplication/
Open In App

How to avoid overflow in modular multiplication?

Last Updated : 14 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Consider below simple method to multiply two numbers.

C++




#include <iostream>
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 = 12345678912345;
    ll b = 98765432198765;
    ll mod = 1000000007;
 
    cout << multiply(a, b, mod) << endl;
 
    return 0;
}


C




// A Simple solution that causes overflow when
// value of (a % mod) * (b % mod) becomes more than
// maximum value of long long int
#define ll long long
 
ll multiply(ll a, ll b, ll mod)
{
   return ((a % mod) * (b % mod)) % mod;
}


Java




// A Simple solution that causes overflow when
// value of (a % mod) * (b % mod) becomes more than
// maximum value of long int
 
 
static long multiply(long a, long b, long mod)
{
   return ((a % mod) * (b % mod)) % mod;
}
 
// This code contributed by gauravrajput1


Python




# A python program to handle overflow
# when multiplying two numbers      
 
def multiply(a,b,mod):
    return ((a % mod) * (b % mod)) % mod;
 
# Code contributed by Gautam goel (gautamgoel962)


C#




// C# program to implement
// the above approach
using System;
 
class GFG{
     
 
// A Simple solution that causes overflow when
// value of (a % mod) * (b % mod) becomes more than
// maximum value of long int
static long multiply(long a, long b, long mod)
{
   return ((a % mod) * (b % mod)) % mod;
}
}
 
// This code is contributed by code_hunt.


Javascript




<script>
 
function multiply(a,b,mod)
{
    return ((a % mod) * (b % mod)) % mod;
}
 
 
// This code is contributed by rag2127
</script>


The above function works fine when multiplication doesn’t result in overflow. But if input numbers are such that the result of multiplication is more than maximum limit.
For example, the above method fails when mod = 1011, a = 9223372036854775807 (largest long long int) and b = 9223372036854775807 (largest long long int). Note that there can be smaller values for which it may fail. There can be many more examples of smaller values. In fact any set of values for which multiplication can cause a value greater than maximum limit.
How to avoid overflow? 
We can multiply recursively to overcome the difficulty of overflow. To multiply a*b, first calculate a*b/2 then add it twice. For calculating a*b/2 calculate a*b/4 and so on (similar to log n exponentiation algorithm). 
 

// To compute (a * b) % mod
multiply(a, b, mod)
1) ll res = 0; // Initialize result
2) a = a % mod.
3) While (b > 0)
a) If b is odd, then add 'a' to result.
res = (res + a) % mod
b) Multiply 'a' with 2
a = (a * 2) % mod
c) Divide 'b' by 2
b = b/2
4) Return res

Below is the implementation. 

C++




// C++ program for modular multiplication without
// any overflow
#include<iostream>
using namespace std;
 
typedef long long int ll;
 
// To compute (a * b) % mod
ll mulmod(ll a, ll b, ll mod)
{
    ll res = 0; // Initialize result
    a = a % mod;
    while (b > 0)
    {
        // If b is odd, add 'a' to result
        if (b % 2 == 1)
            res = (res + a) % mod;
 
        // Multiply 'a' with 2
        a = (a * 2) % mod;
 
        // Divide b by 2
        b /= 2;
    }
 
    // Return result
    return res % mod;
}
 
// Driver program
int main()
{
   ll a = 9223372036854775807, b = 9223372036854775807;
   cout << mulmod(a, b, 100000000000);
   return 0;
}


Java




// Java program for modular multiplication 
// without any overflow
 
class GFG
{
 
    // To compute (a * b) % mod
    static long mulmod(long a, long b,
                            long mod)
    {
        long res = 0; // Initialize result
        a = a % mod;
        while (b > 0)
        {
            // If b is odd, add 'a' to result
            if (b % 2 == 1)
            {
                res = (res + a) % mod;
            }
 
            // Multiply 'a' with 2
            a = (a * 2) % mod;
 
            // Divide b by 2
            b /= 2;
        }
 
        // Return result
        return res % mod;
    }
 
    // Driver code
    public static void main(String[] args)
    {
 
        long a = 9223372036854775807L, b = 9223372036854775807L;
        System.out.println(mulmod(a, b, 100000000000L));
    }
}
 
// This code is contributed by Rajput-JI


Python3




# Python3 program for modular multiplication
# without any overflow
 
# To compute (a * b) % mod
def mulmod(a, b, mod):
 
    res = 0; # Initialize result
    a = a % mod;
    while (b > 0):
     
        # If b is odd, add 'a' to result
        if (b % 2 == 1):
            res = (res + a) % mod;
 
        # Multiply 'a' with 2
        a = (a * 2) % mod;
 
        # Divide b by 2
        b //= 2;
 
    # Return result
    return res % mod;
 
# Driver Code
a = 9223372036854775807;
b = 9223372036854775807;
print(mulmod(a, b, 100000000000));
 
# This code is contributed by mits


C#




// C# program for modular multiplication
// without any overflow
using System;
 
class GFG
{
 
// To compute (a * b) % mod
static long mulmod(long a, long b, long mod)
{
    long res = 0; // Initialize result
    a = a % mod;
    while (b > 0)
    {
        // If b is odd, add 'a' to result
        if (b % 2 == 1)
        {
            res = (res + a) % mod;
        }
 
        // Multiply 'a' with 2
        a = (a * 2) % mod;
 
        // Divide b by 2
        b /= 2;
    }
 
    // Return result
    return res % mod;
}
 
// Driver code
public static void Main(String[] args)
{
    long a = 9223372036854775807L,
         b = 9223372036854775807L;
    Console.WriteLine(mulmod(a, b, 100000000000L));
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
// JavaScript program for modular multiplication
// without any overflow
 
// To compute (a * b) % mod
function mulmod(a, b, mod){
    let res = 0; //Initialize result
    a = a % mod;
    while (b > 0){
        // If b is odd, add 'a' to result
        if (b % 2 == 1){
            res = (res + a) % mod;
        }
 
        // Multiply 'a' with 2
        a = (a * 2) % mod;
 
        // Divide b by 2
        b = Math.floor(b/2);
    }
     
    // Return result
    return res % mod;
}
 
 
// Driver Code
let a = 9223372036854775807;
let b = 9223372036854775807;
document.write(mulmod(a, b, 100000000000));
 
// This code is contributed by Gautam goel (gautamgoel962)
</script>


Output: 

84232501249

Thanks to Utkarsh Trivedi for suggesting above solution.

 



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 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
Check for integer overflow on multiplication
Given two integer a and b, find whether their product (a x b) exceed the signed 64 bit integer or not. If it exceed print Yes else print No. Examples: Input : a = 100, b = 200 Output : No Input : a = 10000000000, b = -10000000000Output : Yes Approach : If either of the number is 0, then it will never exceed the range.Else if the product of the two
4 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
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
three90RightbarBannerImg