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

Sums

Back to problem

Editorial

Let n=R−L+1n=R-L+1n=R−L+1.

Consider sums made by choosing exactly kkk values. Their minimum and maximum are

lo⁡k=kL+k(k−1)2,hi⁡k=kR−k(k−1)2.\operatorname{lo}_k=kL+\frac{k(k-1)}2, \qquad \operatorname{hi}_k=kR-\frac{k(k-1)}2.lok​=kL+2k(k−1)​,hi

When kkk distinct values are chosen from consecutive integers, every integer between these two bounds is attainable. Thus the sums form the integer interval Ik=[lo⁡k,hi⁡k]I_k=[\operatorname{lo}_k,\operatorname{hi}_k]Ik​=[lok​.

Both endpoints increase with kkk. Therefore, the union size equals the sum of all interval lengths minus the overlaps of consecutive intervals.

The length of IkI_kIk​ is

hi⁡k−lo⁡k+1=k(n−k)+1.\operatorname{hi}_k-\operatorname{lo}_k+1=k(n-k)+1.hik​−lok​+1=k(n−

The sum of all interval lengths is

∑k=1n(k(n−k)+1)=n(n+1)(n−1)6+n.\sum_{k=1}^{n}(k(n-k)+1)=\frac{n(n+1)(n-1)}6+n.k=1∑n​(k(n−k)+

The overlap length of IkI_kIk​ and Ik+1I_{k+1}Ik+1​ is

max⁡(0,hi⁡k−lo⁡k+1+1)=max⁡(0,k(n−1−k)−L+1).\max(0,\operatorname{hi}_k-\operatorname{lo}_{k+1}+1) =\max(0,k(n-1-k)-L+1).max(0,hik​−lok

It is positive exactly when k(n−1−k)≥Lk(n-1-k)\geq Lk(n−1−k)≥L.

The expression k(n−1−k)k(n-1-k)k(n−1−k) increases for k=1,2,…,⌊(n−1)/2⌋k=1,2,\ldots,\lfloor(n-1)/2\rfloork=1,2,…,⌊(n. Binary search for the smallest satisfying value . By symmetry, all satisfying indices are

a≤k≤n−1−a.a\leq k\leq n-1-a.a≤k≤n−1−a.

If no such value exists, the overlap sum is zero.

Let b=n−1−ab=n-1-ab=n−1−a. The total overlap to subtract is

∑k=ab(k(n−1−k)−L+1)=(n−1)∑k=abk−∑k=abk2−(L−1)(b−a+1).\sum_{k=a}^{b}\left(k(n-1-k)-L+1\right) =(n-1)\sum_{k=a}^{b}k-\sum_{k=a}^{b}k^2-(L-1)(b-a+1).k=a∑b​

This is evaluated in O(1)O(1)O(1) using the standard formulas for ∑k\sum k∑k and ∑k2\sum k^2∑k2.

All arithmetic for the answer is performed modulo 109+710^9+7109+7. Use 128-bit integers for products in the binary-search comparisons.

The time complexity per test case is O(log⁡(R−L+1))O(\log(R-L+1))O(log(R−L+1)), and the additional space complexity is O(1)O(1)O(1).

Solution written by GPT6

k
​
=
kR−
2k(k−1)​.
,
hik​
]
k)+
1.
1
)
=
6n(n+1)(n−1)​+
n.
+
1
​
+
1
)
=
max(0,k(n−
1−
k)−
L+
1).
−
1)/2⌋
aaa
(k(n−1−k)−L+1)
=
(n−
1)k=a∑b​k−
k=a∑b​k2−
(L−
1)(b−
a+
1).