Given three positive numbers a, b and m. Compute a/b under modulo m. The task is basically to find a number c such that (b * c) % m = a % m.
Input : a = 8, b = 4, m = 5 Output : 2 Input : a = 8, b = 3, m = 5 Output : 1 Note that (1*3)%5 is same as 8%5 Input : a = 11, b = 4, m = 5 Output : 4 Note that (4*4)%5 is same as 11%5
Following articles are prerequisites for this.
Modular multiplicative inverse
Extended Euclidean algorithms
Can we always do modular division?
The answer is “NO”. First of all, like ordinary arithmetic, division by 0 is not defined. For example, 4/0 is not allowed. In modular arithmetic, not only 4/0 is not allowed, but 4/12 under modulo 6 is also not allowed. The reason is, 12 is congruent to 0 when modulus is 6.
When is modular division defined?
Modular division is defined when modular inverse of the divisor exists. The inverse of an integer ‘x’ is another integer ‘y’ such that (x*y) % m = 1 where m is the modulus.
When does inverse exist? As discussed here, inverse a number ‘a’ exists under modulo ‘m’ if ‘a’ and ‘m’ are co-prime, i.e., GCD of them is 1.
How to find modular division?
The task is to compute a/b under modulo m. 1) First check if inverse of b under modulo m exists or not. a) If inverse doesn't exists (GCD of b and m is not 1), print "Division not defined" b) Else return "(inverse * a) % m"
Result of division is 1
Modular division is different from addition, subtraction and multiplication.
One difference is division doesn’t always exist (as discussed above). Following is another difference.
Below equations are valid (a * b) % m = ((a % m) * (b % m)) % m (a + b) % m = ((a % m) + (b % m)) % m // m is added to handle negative numbers (a - b + m) % m = ((a % m) - (b % m) + m) % m But, (a / b) % m may NOT be same as ((a % m)/(b % m)) % m For example, a = 10, b = 5, m = 5. (a / b) % m is 2, but ((a % m) / (b % m)) % m is not defined.
This article is contributed by Dheeraj Gupta. 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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.