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
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 a 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
- Fermat's little theorem
- Number Theory (Interesting Facts and Algorithms)
- Modulo 10^9+7 (1000000007)
- GCD of more than two (or array) numbers
- Multiplicative order
- Find (a^b)%m where 'a' is very large
- How to avoid overflow in modular multiplication?
- Find Square Root under Modulo p | Set 1 (When p is in form of 4*i + 3)
- Compute n! under modulo p
- Compute nCr % p | Set 1 (Introduction and Dynamic Programming Solution)
- Modular Exponentiation (Power in Modular Arithmetic)
- Modular multiplicative inverse
- Euclidean algorithms (Basic and Extended)
- Binomial Coefficient | DP-9
- Program for Fibonacci numbers