The Wayback Machine - https://web.archive.org/web/20240604012321/https://www.geeksforgeeks.org/multiply-large-integers-under-large-modulo/
Open In App

Multiply large integers under large modulo

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

Given an integer a, b, m. Find (a * b ) mod m, where a, b may be large and their direct multiplication may cause overflow. However, they are smaller than half of the maximum allowed long long int value.

Examples: 

Input: a = 426, b = 964, m = 235
Output: 119
Explanation: (426 * 964) % 235  = 410664 % 235 = 119

Input: a = 10123465234878998, 
          b = 65746311545646431
         m = 10005412336548794 
Output: 4652135769797794

Naive Approach: A naive approach is to use arbitrary precision data types such as int in python or Biginteger class in Java. But that approach will not be fruitful because the internal conversion of string to int and then perform operation will lead to slow down the calculations of addition and multiplications in the binary number system.

Efficient Approach: Since a and b may be very large numbers, if we try to multiply directly, they will definitely overflow. Therefore we use the basic approach of multiplication i.e., a * b = a + a + … + a (b times). Now easily compute the value of addition (under modulo m) without any overflow in the calculation. But if we try to add the value of a repeatedly up to b times then it will definitely timeout for the large value of b, since the time complexity of this approach would become O(b).

So, divide the above-repeated steps for a in simpler way i.e., 

If b is even then 
a * b = 2 * a * (b / 2), 

otherwise 
a * b = a + a * (b – 1)

Below is the approach describing the above explanation : 

C++




// C++ program of finding modulo multiplication
#include <bits/stdc++.h>
  
using namespace std;
  
// Returns (a * b) % mod
long long moduloMultiplication(long long a, long long b,
                               long long mod)
{
    long long res = 0; // Initialize result
  
    // Update a if it is more than
    // or equal to mod
    a %= mod;
  
    while (b) {
        // If b is odd, add a with result
        if (b & 1)
            res = (res + a) % mod;
  
        // Here we assume that doing 2*a
        // doesn't cause overflow
        a = (2 * a) % mod;
  
        b >>= 1; // b = b / 2
    }
  
    return res;
}
  
// Driver program
int main()
{
    long long a = 426;
    long long b = 964;
    long long m = 235;
    cout << moduloMultiplication(a, b, m);
    return 0;
}
  
// This code is contributed
// by Akanksha Rai


C




// C program of finding modulo multiplication
#include<stdio.h>
  
// Returns (a * b) % mod
long long moduloMultiplication(long long a,
                               long long b,
                               long long mod)
{
    long long res = 0;  // Initialize result
  
    // Update a if it is more than
    // or equal to mod
    a %= mod;
  
    while (b)
    {
        // If b is odd, add a with result
        if (b & 1)
            res = (res + a) % mod;
  
        // Here we assume that doing 2*a
        // doesn't cause overflow
        a = (2 * a) % mod;
  
        b >>= 1;  // b = b / 2
    }
  
    return res;
}
  
// Driver program
int main()
{
    long long a = 10123465234878998;
    long long b = 65746311545646431;
    long long m = 10005412336548794;
    printf("%lld", moduloMultiplication(a, b, m));
    return 0;
}


Java




// Java program of finding modulo multiplication 
import java.util.*;
import java.io.*;
class GFG 
{
  
    // Returns (a * b) % mod 
    static long moduloMultiplication(long a,
                            long b, long mod)
    {
          
        // Initialize result
        long res = 0;  
  
        // Update a if it is more than 
        // or equal to mod 
        a %= mod;
  
        while (b > 0) 
        {
              
            // If b is odd, add a with result 
            if ((b & 1) > 0) 
            {
                res = (res + a) % mod;
            }
  
            // Here we assume that doing 2*a 
            // doesn't cause overflow 
            a = (2 * a) % mod;
  
            b >>= 1; // b = b / 2 
        }
        return res;
    }
  
    // Driver code 
    public static void main(String[] args) 
    {
        long a = 10123465234878998L;
        long b = 65746311545646431L;
        long m = 10005412336548794L;
        System.out.print(moduloMultiplication(a, b, m));
    }
} 
  
// This code is contributed by Rajput-JI


Python3




# Python 3 program of finding
# modulo multiplication
  
# Returns (a * b) % mod
def moduloMultiplication(a, b, mod):
  
    res = 0; # Initialize result
  
    # Update a if it is more than
    # or equal to mod
    a = a % mod;
  
    while (b):
      
        # If b is odd, add a with result
        if (b & 1):
            res = (res + a) % mod;
              
        # Here we assume that doing 2*a
        # doesn't cause overflow
        a = (2 * a) % mod;
  
        b >>= 1; # b = b / 2
      
    return res;
  
# Driver Code
a = 10123465234878998;
b = 65746311545646431;
m = 10005412336548794;
print(moduloMultiplication(a, b, m));
      
# This code is contributed
# by Shivi_Aggarwal


C#




// C# program of finding modulo multiplication
using System;
  
class GFG
{
      
// Returns (a * b) % mod
static long moduloMultiplication(long a,
                            long b,
                            long mod)
{
    long res = 0; // Initialize result
  
    // Update a if it is more than
    // or equal to mod
    a %= mod;
  
    while (b > 0)
    {
        // If b is odd, add a with result
        if ((b & 1) > 0)
            res = (res + a) % mod;
  
        // Here we assume that doing 2*a
        // doesn't cause overflow
        a = (2 * a) % mod;
  
        b >>= 1; // b = b / 2
    }
  
    return res;
}
  
// Driver code
static void Main()
{
    long a = 10123465234878998;
    long b = 65746311545646431;
    long m = 10005412336548794;
    Console.WriteLine(moduloMultiplication(a, b, m));
}
}
  
// This code is contributed 
// by chandan_jnu


PHP




<?php
//PHP program of finding 
// modulo multiplication
  
// Returns (a * b) % mod
function moduloMultiplication($a, $b, $mod)
{
    $res = 0; // Initialize result
  
    // Update a if it is more than
    // or equal to mod
    $a %= $mod;
  
    while ($b)
    {
          
        // If b is odd, 
        // add a with result
        if ($b & 1)
            $res = ($res + $a) % $mod;
  
        // Here we assume that doing 2*a
        // doesn't cause overflow
        $a = (2 * $a) % $mod;
  
        $b >>= 1; // b = b / 2
    }
  
    return $res;
}
  
    // Driver Code
    $a = 10123465234878998;
    $b = 65746311545646431;
    $m = 10005412336548794;
    echo moduloMultiplication($a, $b, $m);
  
// This oce is contributed by ajit
?>


Javascript




<script>
  
// JavaScript program for the above approach
  
// Returns (a * b) % mod 
function moduloMultiplication(a, b, mod)
{
      
    // Initialize result
    let res = 0;  
  
    // Update a if it is more than 
    // or equal to mod 
    a = (a % mod);
  
    while (b > 0) 
    {
          
        // If b is odd, add a with result 
        if ((b & 1) > 0) 
        {
            res = (res + a) % mod;
        }
  
        // Here we assume that doing 2*a 
        // doesn't cause overflow 
        a = (2 * a) % mod;
  
        b = (b >> 1); // b = b / 2 
    }
    return res;
}
  
// Driver Code
let a = 426;
let b = 964;
let m = 235;
  
document.write(moduloMultiplication(a, b, m));
  
// This code is contributed by code_hunt
  
</script>


Output

119

Time complexity: O(log b), A number n has log(n) bits therefore the loop will run log(b) times.
Auxiliary space: O(1)

Note: Above approach will only work if 2 * m can be represented in standard data type otherwise it will lead to overflow. 

 



Previous Article
Next Article

Similar Reads

Equalizing array using increment under modulo 3
Given an array A containing N non-negative integers. Only following operation can be performed on the array: A[i] = ( A[i] + 1 ) % 3 where A[i] is the element of array A at index i, and performing this operation once costs 1 unit. Find the minimum cost to make all elements equal. Examples : Input : 1 0 3 2 Output : 4 units Explanation: First 3 is c
14 min read
Nearest smaller number to N having multiplicative inverse under modulo N equal to that number
Given a prime number N, the task is to find the closest smaller number than N such that modulo multiplicative inverse of a number under modulo N is equal to the number itself. Examples: Input: N = 7Output: 6Explanation:Modulo multiplicative inverse of all possible natural numbers from 1 to less than N are:Modulo multiplicative inverse of 1 under mo
3 min read
Expressing a fraction as a natural number under modulo 'm'
Given two integers A and B where A is not divisible by B, the task is to express A / B as a natural number modulo m where m = 1000000007. Note: This representation is useful where we need to express Probability of an event, Area of Curves and polygons etc.Examples: Input: A = 2, B = 6 Output: 333333336Input: A = 4, B = 5 Output: 600000005 Approach:
12 min read
Find Square Root under Modulo p | (When p is product of two primes in the form 4*i + 3)
Given an integer N and an integer P denoting the product of two primes, the task is to find all possible Square Root of N under modulo P if it exists. It is given that P is the product of p1 and p2, where p1 and p2 are prime numbers of the form 4i + 3 where i is any integer. Some examples of such prime numbers are (7, 11, 19, 23, 31). Examples: Inp
17 min read
Compute n! under modulo p
Given a large number n and a prime p, how to efficiently compute n! % p?Examples : Input: n = 5, p = 13 Output: 3 5! = 120 and 120 % 13 = 3 Input: n = 6, p = 11 Output: 5 6! = 720 and 720 % 11 = 5 A Naive Solution is to first compute n!, then compute n! % p. This solution works fine when the value of n! is small. The value of n! % p is generally ne
22 min read
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 number x such that (x*x)%7 is 2. The number is 3.
11 min read
Find Square Root under Modulo p | Set 1 (When p is in form of 4*i + 3)
Given a number 'n' and a prime 'p', find square root of n under modulo p if it exists. It may be given that p is in the form for 4*i + 3 (OR p % 4 = 3) where i is an integer. Examples of such primes are 7, 11, 19, 23, 31, ... etc,Examples: Input: n = 2, p = 7Output: 3 or 4Explanation: 3 and 4 both are square roots of 2 under modulo 7 because (3*3)
14 min read
Find Square Root under Modulo p | Set 2 (Shanks Tonelli algorithm)
Given a number ‘n’ and a prime ‘p’, find square root of n under modulo p if it exists. Examples: Input: n = 2, p = 113 Output: 62 62^2 = 3844 and 3844 % 113 = 2 Input: n = 2, p = 7 Output: 3 or 4 3 and 4 both are square roots of 2 under modulo 7 because (3*3) % 7 = 2 and (4*4) % 7 = 2 Input: n = 2, p = 5 Output: Square root doesn't exist We have di
20 min read
Multiply Large Numbers using Grid Method
Given two large numbers A and B, the task is to find the product of these two numbers using Grid Method.Examples:   Input: A = 23, B = 15 Output: 345Input: A = 321, B = 69 Output: 22149     Approach:   Create 2D Array of N Rows and M columns where N is number of digit in first number and M is number of digit in second number.    Multiply each eleme
16 min read
Multiply Large Numbers represented as Strings
Given two positive numbers as strings. The numbers may be very large (may not fit in long long int), the task is to find product of these two numbers.Examples:  Input : num1 = 4154 num2 = 51454Output : 213739916 Input : num1 = 654154154151454545415415454 num2 = 63516561563156316545145146514654 Output : 4154962260395530977724371606999799700762043993
27 min read