Consider below simple method to multiply two numbers.
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.
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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Modular Exponentiation (Power in Modular Arithmetic)
- Check for integer overflow on multiplication
- Modular Multiplication
- Reverse digits of an integer with overflow handled
- Compute average of two numbers without overflow
- Program to check if tank will overflow, underflow or filled in given time
- Modular multiplicative inverse
- Modular Division
- Using Chinese Remainder Theorem to Combine Modular equations
- Find modular node in a linked list
- Modular multiplicative inverse from 1 to n
- Number of solutions to Modular Equations
- Trick for modular division ( (x1 * x2 .... xn) / b ) mod (m)
- Modular exponentiation (Recursive)
- Modular Exponentiation of Complex Numbers
- Modular Addition
- Modular Arithmetic
- Find the value of P and modular inverse of Q modulo 998244353
- Multiply two integers without using multiplication, division and bitwise operators, and no loops
- Write you own Power without using multiplication(*) and division(/) operators