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 account linking.

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

Easy Sequence Problem

Back to problem

Editorial

Suppose (AN,AN+1)=(P,Q)(A_N,A_{N+1})=(P,Q)(AN​,AN+1​)=(P,Q). If P<QP<QP<Q, the last binary bit of NNN is 000 and the previous pair is (P,Q−P)(P,Q-P)(P,Q−P). If P>QP>QP>Q, the last bit is 111 and the previous pair is (P−Q,Q)(P-Q,Q)(P−Q,Q).

Repeated subtraction can be too slow. When P<QP<QP<Q, let t=⌊Q−1P⌋t=\left\lfloor\frac{Q-1}{P}\right\rfloort=⌊PQ−1​ and subtract at once; this removes trailing zero bits. The case is symmetric. Since and are coprime, the process ends at .

Reattach the removed bit runs in reverse order. Appending ttt zeros changes XXX to X2tX2^tX2t, while appending ttt ones changes it to X2t+(2t−1)X2^t+(2^t-1). Work modulo . The number of quotient steps is logarithmic, so the time complexity is .

⌋
tPtPtP
ttt
P>QP>QP>Q
PPP
QQQ
(1,1)(1,1)(1,1)
X
2t
+
(2t−
1)
998 244 353998\,244\,353998244353
O(log⁡max⁡(P,Q))O(\log \max(P,Q))O(logmax(P,Q))
Solution written by GPT5.6