title | tags | |||||
---|---|---|---|---|---|---|
06. Modular Division |
|
There is a significant difference between division in modular arithmetic and ordinary integer division, and it is crucial to understand it. In this tutorial, we will introduce modular division, modular inverse, and methods for calculating the inverse.
In the previous tutorial, we introduced addition and multiplication in modular arithmetic, which are similar to ordinary addition and multiplication. However, division in modular arithmetic is very different from ordinary division. If we apply integer division to modular arithmetic, we will get strange results. For example, we know that
In general, division is the inverse operation of multiplication and can reverse the effect of multiplication. For example, in modulo
For example, to calculate
To better define and calculate division in modular arithmetic, we will now introduce modular inverse.
The modular inverse is defined as follows: If there exists an integer
The inverse exists only when
With the inverse, we can convert modular division
So, how do we calculate the inverse of
In modular arithmetic,
|
Multiplication with 2 | Remainder |
---|---|---|
0 | 0 | 0 |
1 | 2 | 2 |
2 | 4 | 4 |
3 | 6 | 1 |
4 | 8 | 3 |
In the previous tutorials, we learned that the extended Euclidean algorithm can be used to calculate the coefficients that satisfy the Bezout's identity. In fact, it can also be used to calculate the inverse, which is more efficient than an exhaustive search.
When the inverse w
of y
exists,
By moving
In other words,
Therefore, the
For example, we can use this method to find the inverse of
def extended_euclidean_algorithm(a, b):
x1, y1, x2, y2 = 1, 0, 0, 1
while b:
q = a // b
a, b = b, a % b
x1, x2 = x2, x1 - q * x2
y1, y2 = y2, y1 - q * y2
return a, x1, y1
# Example
y = 7
n = 69
gcd_result, k, w = extended_euclidean_algorithm(n, y)
if gcd_result == 1:
print(f'The greatest common divisor of {n} and {y} is {gcd_result}, the inverse exists, which is {w}')
else:
print(f'The greatest common divisor of {n} and {y} is {gcd_result}, the inverse does not exist')
# The greatest common divisor of 69 and 7 is 1, the inverse exists, which is 10
By using the extended Euclidean algorithm, we obtain
Here is the recursive version of the extended Euclidean algorithm implemented in code to calculate the modular inverse:
def get_inverse(a, N):
if gcd(a, N) == 1:
x, y = ext_gcd(a, N)
return (x + N) % N
print("No inverse!")
return 0
Now, please try to solve the following problem:
In this tutorial, we introduced the concepts of division and inverse in modular arithmetic, and two methods for calculating the inverse: exhaustive search and the extended Euclidean algorithm. There is a significant difference between division in modular arithmetic and ordinary integer division, and everyone need to practice and become familiar with it.