Editorial
The extended Euclidean algorithm is a classical algorithm that finds integer pairs that satisfy .
In this problem, since and are coprime (), you can find an integer pair that satisfies .
Rewriting as , and taking both sides modulo , we obtain .
Thus, we conclude that .
By using the extended Euclidean algorithm, we can efficiently compute .
Since is not necessarily a prime number in this problem, we cannot use Fermat's little theorem.
Sample Code
Below is a sample program:
# Extended Euclidean Algorithm
def extended_euclidean(a: int, b: int) -> tuple[int, int, int]:
# when b == 0:
if b == 0:
return a, 1, 0
# recursive step
gcd, x1, y1 = extended_euclidean(b, a % b)
# update x and y
x = y1
y = x1 - (a // b) * y1
return gcd, x, y
def solve(a: int, L: int) -> int:
_, x, _ = extended_euclidean(a, L)
return x % L