How to avoid overflow in modular multiplication?

27 May, 2022
Consider below simple method to multiply two numbers. 
C
Java
Python
C#
Javascript
// 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;}
// 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
# 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# program to implement// the above approachusing System; class GFG{      // A Simple solution that causes overflow when// value of (a % mod) * (b % mod) becomes more than// maximum value of long intstatic long multiply(long a, long b, long mod){   return ((a % mod) * (b % mod)) % mod;}} // This code is contributed by code_hunt.
<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++
Java
Python3
C#
Javascript
// C++ program for modular multiplication without// any overflow#include<iostream>using namespace std; typedef long long int ll; // To compute (a * b) % modll 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 programint main(){   ll a = 9223372036854775807, b = 9223372036854775807;   cout << mulmod(a, b, 100000000000);   return 0;}
// 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 program for modular multiplication# without any overflow # To compute (a * b) % moddef 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 Codea = 9223372036854775807;b = 9223372036854775807;print(mulmod(a, b, 100000000000)); # This code is contributed by mits
// C# program for modular multiplication// without any overflowusing System; class GFG{ // To compute (a * b) % modstatic 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 codepublic static void Main(String[] args){    long a = 9223372036854775807L,         b = 9223372036854775807L;    Console.WriteLine(mulmod(a, b, 100000000000L));}} // This code is contributed by 29AjayKumar
<script>// JavaScript program for modular multiplication// without any overflow // To compute (a * b) % modfunction 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 //= 2;    }         // Return result    return res % mod;}  // Driver Codelet 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.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
Rajput-Ji
29AjayKumar
Mithun Kumar
GauravRajput1
rag2127
gautamgoel962
code_hunt
large-numbers
Modular Arithmetic
Mathematical
Mathematical
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
Coin Change | DP-7
Operators in C / C++
Prime Numbers
Program to find GCD or HCF of two numbers
Find minimum number of coins that make a given value