Let M=998244353. Since M is prime, every integer not divisible by M has a modular inverse modulo M.
By Fermat's little theorem, if aξ β‘0(modM), then
aMβ1β‘1(modM).
Therefore, when computing powers of nonzero numbers modulo M, only the exponent modulo
Ο=Mβ1=998244352
matters.
The condition gives
gcd(β£qβ£,Ο)=1.
Thus, q has an inverse modulo Ο. That is, there exists an integer r such that
qrβ‘1(modΟ).
The original equation is
xqβ‘np(modM).
Raise both sides to the power r:
(xq)rβ‘(np)r(modM).
Then
xqrβ‘npr(modM).
Since qrβ‘1(modΟ), Fermat's little theorem gives
xqrβ‘x(modM).
Therefore,
xβ‘npr(modM).
So there is exactly one possible value of x, and the answer is
npqβ1(modM).
Here, qβ1 is not the inverse modulo M, but the inverse modulo Mβ1.
The algorithm is as follows.
- Set Ο=998244352.
- Normalize p modulo Ο to obtain P.
- Normalize q modulo Ο, then compute its inverse r using the extended Euclidean algorithm.
- Compute eβ‘Pr(modΟ).
- Compute and print ne(modM) using binary exponentiation.
Be careful that 998244352 is not prime. Therefore, qβ1(mod998244352) must not be computed using Fermat's little theorem. Use the extended Euclidean algorithm instead.
Also, p and q may be negative, so remainders must be normalized into the range from 0 to Οβ1.
The time complexity is O(logM).