https://ac.nowcoder.com/discuss/399522?type=101&order=0&pos=14&page=2
#include <bits/stdc++.h> using namespace std; #define int long long int l, r, a[20], b[20]; int shou(int x) { int ans = 0 ; while (x>0) { ans = x % 10; x /= 10; } return ans; } void calc(int r, int *a) { for (int i = 1; i * i <= r; i++) //枚举一个因子a { int b = r/i; //b的范围左界是i+1(为了不算重复),右界是r/i for (int j = 1; j <= r; j *= 10) //枚举位数(直接用1后面若干个0,方便后面计算) { for (int k = 1; k <= 9; k++) // 枚举首位数 { int x = max(j*k, i+1); //x是最高位为k的时候的下界 int y = min((j *(k+1)) -1, b); //y是上界 if (y-x>=0) a[k] += y-x+1; //这个区间存在,算个数 } } int tmp = shou(i); //算a的首位 a[tmp] += b-i+1; //算用了多少个a } } signed main() { scanf("%lld%lld", &l, &r); calc(r, a); calc(l - 1, b); for(int i = 1; i <= 9; ++i) printf("%lld\n", a[i]-b[i]); return 0; }