题意:给出n,k,求k%1 + k%2 + …… + k%n;
分析:当k/i = 1 时, k%i = k - i,随着i不断减小1,k-i每次减小1,即k%i每次减小1。当k/i=2时,i减小1,k%i减小2。我们要求k%i的和,可以划分为许多等差数列的和。
View Code
#include#include #include #include using namespace std; long long n, k; int main() { //freopen("t.txt", "r", stdin); while (scanf("%lld%lld", &n, &k) != EOF) { long long ans = 0; if (n > k) ans = k * (n - k); int i = 1; long long a, b; while (true) { a = k / i; b = k / (i + 1) + 1; if (a == b) break; if (b > n) { i++; continue; } if (a > n) a = n; ans += (k % a + k % a + (a - b) * i) * (a - b + 1) / 2; i++; } for (i = 1; i <= min(n, a); i++) ans += k % i; printf("%lld\n", ans); } return 0; }