1257: [CQOI2007]余数之和
Time Limit: 5 Sec Memory Limit: 128 MBDescription
给出正整数n和k,计算j(n, k)=k mod 1 + k mod 2 + k mod 3 + … + k mod n的值
其中k mod i表示k除以i的余数。
例如j(5, 3)=3 mod 1 + 3 mod 2 + 3 mod 3 + 3 mod 4 + 3 mod 5=0+1+0+3+3=7
Input
输入仅一行,包含两个整数n, k。
1<=n ,k<=10^9
Output
输出仅一行,即j(n, k)。
Sample Input
5 3
Sample Output
7
HINT
Source
x % i = x – [x / i] * i
ans = n * k - ∑ [x / i] * i
[x / i]的值最多有√n种,枚举一下就可以啦
1 #include<iostream> 2 #include<cstdio> 3 #include<algorithm> 4 #include<cmath> 5 #include<cstring> 6 #include<vector> 7 8 using namespace std; 9 10 template <typename tn> void read (tn & a) { 11 tn x = 0, f = 1; 12 char c = getchar(); 13 while (c < '0' || c > '9'){ if (c == '-') f = -1; c = getchar(); } 14 while (c >= '0' && c <= '9'){ x = x * 10 + c - '0'; c = getchar(); } 15 a = f == 1 ? x : -x; 16 } 17 18 long long n, k, ans; 19 20 int main() { 21 read(n); 22 read(k); 23 ans = n * k; 24 n = min(n, k); 25 long long j = 0; 26 for (long long i = 1; i <= n; i = j + 1) { 27 long long x = k / i; 28 j = k / x; 29 j = min(n, j); 30 ans -= x * (i + j) * (j - i + 1) / 2; 31 } 32 cout << ans << "\n"; 33 return 0; 34 }