DOJ logoDOJ
Problems
Recently added problemsSaved problems
CategoriesDLCContestsGroupsTeamsBoard
Ranking
Solved Problem RankingStreak rankingDOJ Power ranking
Status
Call for TasksLoginRegister
DOJ logoDOJ

Community online judge with OI-style subtask scoring, Elo ratings, and Discord-backed certification.

Problems
ProblemsCategories
Community
ContestsRankingBoardNoticesHost an external contestGuide
Account
LoginRegisterJudge Status
Policy
Terms of ServiceDLC RulesPrivacyAPI documentationLanguage runtimesContest rank rewardsRating and performance
© 2026 DOJ
All rights reserved
Editorial

Fractional Power

Back to problem

Editorial

Let M=998244353M=998244353M=998244353. Since MMM is prime, every integer not divisible by MMM has a modular inverse modulo MMM.

By Fermat's little theorem, if a≢0(modM)a \not\equiv 0 \pmod Ma≡0(modM), then

aM−1≡1(modM).a^{M-1} \equiv 1 \pmod M.aM−1≡1(modM).

Therefore, when computing powers of nonzero numbers modulo MMM, only the exponent modulo

φ=M−1=998244352\varphi = M-1 = 998244352φ=M−1=998244352

matters.

The condition gives

gcd⁡(∣q∣,φ)=1.\gcd(|q|,\varphi)=1.gcd(∣q∣,φ)=1.

Thus, qqq has an inverse modulo φ\varphiφ. That is, there exists an integer rrr such that

qr≡1(modφ).qr \equiv 1 \pmod \varphi.qr≡1(modφ).

The original equation is

xq≡np(modM).x^q \equiv n^p \pmod M.xq≡np(modM).

Raise both sides to the power rrr:

(xq)r≡(np)r(modM).(x^q)^r \equiv (n^p)^r \pmod M.(xq)r≡(np)

Then

xqr≡npr(modM).x^{qr} \equiv n^{pr} \pmod M.xqr≡npr(modM).

Since qr≡1(modφ)qr \equiv 1 \pmod \varphiqr≡1(modφ), Fermat's little theorem gives

xqr≡x(modM).x^{qr} \equiv x \pmod M.xqr≡x(modM).

Therefore,

x≡npr(modM).x \equiv n^{pr} \pmod M.x≡npr(modM).

So there is exactly one possible value of xxx, and the answer is

npq−1(modM).n^{p q^{-1}} \pmod M.npq−1(modM).

Here, q−1q^{-1}q−1 is not the inverse modulo MMM, but the inverse modulo M−1M-1M−1.

The algorithm is as follows.

  • Set φ=998244352\varphi = 998244352φ=998244352.
  • Normalize ppp modulo φ\varphiφ to obtain PPP.
  • Normalize qqq modulo φ\varphi, then compute its inverse using the extended Euclidean algorithm.

Be careful that 998244352998244352998244352 is not prime. Therefore, q−1(mod998244352)q^{-1} \pmod {998244352}q−1(mod998244352) must not be computed using Fermat's little theorem. Use the extended Euclidean algorithm instead.

Also, ppp and qqq may be negative, so remainders must be normalized into the range from 000 to φ−1\varphi-1φ−1.

The time complexity is O(log⁡M)O(\log M)O(logM).

r
(modM).
φ
rrr
  • Compute e≡Pr(modφ)e \equiv Pr \pmod \varphie≡Pr(modφ).
  • Compute and print ne(modM)n^e \pmod Mne(modM) using binary exponentiation.