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)
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 using the extended Euclidean algorithm.
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).