思路

本题一定要注意的关键在于:$10^{x} \mod 9 = 1$

所以如数字 $2345 \mod 9$ 和 $(2 + 3 +4 +5) \mod 9$ 是完全等价的,那么这个问题就转化成了求
$$
(l + r)*(r - l + 1) / 2 \mod 9
$$
难度:中位橙

代码

第一版

最开始写的第一板子是没有用到逆元的,即看 (l + r) 和 (r - l + 1) 中哪个是偶数,就先除他。二者之中必有一个偶数,是可以知道的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<iostream>
#include<string>
#define ll long long
using namespace std;

int main()
{
int t = 0;
cin >> t;
ll x, y;
while (t--)
{
ll m, n;
cin >> m >> n;
if ((m + n) % 2 == 0)
{
x = (m + n) / 2;
y = (n - m + 1);
}
else {
x = m + n;
y = (n - m + 1) / 2;
}
cout << ((x % 9) * (y % 9))%9 << endl;
}
return 0;
}

第二版

后面学习了逆元之后才知道,除 2 在模 9 的情况下其实就是乘 2 模 9 的逆元,即 5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;

signed main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
int T;
cin >> T;
while(T--){
int l, r;
cin >> l >> r;
int re = ((l + r) % 9 * (r - l + 1) % 9 * 5) % 9;
//一定要记得 mod 9,都要mod,不然只能拿70
cout << re << endl;
}
return 0;
}

当然,不想都 mod 9 也没关系,可以直接用 快速乘 防爆ll

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
int fp(int a, int b, int m) {
int re = 0;
a %= m;
while (b) {
if (b & 1) {
re = (re + a) % m;
}
a = a * 2 % m;
b >>= 1;
}
return re % m;
}

signed main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
int T;
cin >> T;
while(T--){
int l, r;
cin >> l >> r;
int re = (fp((l + r),(r - l + 1),9) * 5) % 9;
cout << re << endl;
}
return 0;
}