DOJ logoDOJ
Problems
Recently added problemsSaved problemsWorkbooks
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

Yet Another Prefix Sum Problem

Back to problem

Editorial

Let Xi=A+iDX_i=A+iDXi​=A+iD. If XiX_iXi​ is divisible by ppp, then XiXi≡0(modp)X_i^{X_i}\equiv0\pmod pXiXi​​≡0(modp. Otherwise, Fermat's little theorem allows us to reduce the exponent modulo p−1p-1p−1.

Group indices as i=r+tpi=r+tpi=r+tp, where 0≤r<min⁡(N,p)0\le r<\min(N,p)0≤r<min(N,p). The number of indices in group rr is

mr=⌊N−1−rp⌋+1.m_r=\left\lfloor\frac{N-1-r}{p}\right\rfloor+1.mr​=⌊pN−1−r​

The integer XrX_rXr​ may exceed the signed 646464-bit range, so compute only

br=(A mod p+(rD) mod p) mod p,er=(A mod (p−1)+(rD) mod (p−1)) mod (p−1).b_r=(A\bmod p+(rD)\bmod p)\bmod p, \qquad e_r=(A\bmod(p-1)+(rD)\bmod(p-1))\bmod(p-1).b

If br=0b_r=0br​=0, every term in that group contributes zero. Otherwise, define

Cr=brer mod p,Rr=brD mod (p−1) mod p.C_r=b_r^{e_r}\bmod p,\qquad R_r=b_r^{D\bmod(p-1)}\bmod p.Cr​=b

Then the term at index i=r+tpi=r+tpi=r+tp satisfies

(A+iD)A+iD≡CrRrt(modp).(A+iD)^{A+iD}\equiv C_rR_r^t\pmod p.(A+iD)A+iD≡Cr

In particular, the first term is brerb_r^{e_r}brer​​, not necessarily brbrb_r^{b_r}br: congruence of the base modulo does not imply congruence of its exponent modulo .

The sum within a group is CrmrC_rm_rCr​mr​ if Rr=1R_r=1Rr​, and otherwise

CrRrmr−1Rr−1(modp).C_r\frac{R_r^{m_r}-1}{R_r-1}\pmod p.Cr​Rr​−1

Use a modular inverse for division. Since br≠0b_r\ne0br​=0, also Rr≠0R_r\ne0Rr​, so exponent reduction modulo is valid. Precompute inverses from to in linear time.

Add the contributions of every group. There are at most min⁡(N,p)\min(N,p)min(N,p) groups, and each requires O(log⁡p)O(\log p)O(logp) time for modular exponentiation. The overall time complexity is O(p+min⁡(N,p)log⁡p)O(p+\min(N,p)\log p)O(p+ and the space complexity is . By reducing operands before multiplication, all intermediate values fit in signed -bit integers.

Solution written by GPT6

)
r
⌋
+
1.
r​
=
(Amod
p+
(rD)mod
p)mod
p,er​=
(Amod
(p−
1)+
(rD)mod
(p−
1))mod
(p−
1).
r
er​
​
mod
p,Rr​=
brDmod(p−1)​mod
p.
​
Rrt​
(modp).
br​
​
ppp
p−1p-1p−1
=
1
Rrmr​​−1
​
(modp).
=
0
p−1p-1p−1
111
p−1p-1p−1
min
(
N
,
p
)
log
p
)
O(p)O(p)O(p)
646464