Ultraviolet A 1363-Joseph's Problem
Question Link
Question: Given n, k, find ΣNI= 1 (K MOD I)
Idea: Because n and k are both very large, direct violence won't work. Then I drew some information on the paper, and I found thatK/IThe same items form an arithmetic difference sequence, so we can split the entire sequence into [k, k/2], [k/2, k/3], [k/3, k/4]... k [k/a, k/B] and so on. With the idea of the stride small step algorithm, a can enumerate sqrt (k), so that [1, the k/a] sequence needs to be de-enumerated, and the total time complexity is O (sqrt (k). Then, note that for the case where n is greater than k, all the parts where n exceeds k are equal to k, is (n-k) * k, so that all parts are added as the answer
This is a detailed question.
Code:
#include <stdio.h>#include <string.h>#include <math.h>long long n, k;long long solve() { long long ans = 0; if (n > k) ans += (n - k) * k; long long a = (long long )sqrt(k), b = k / a; for (long long i = a; i > 1; i--) {long long a0 = k / i, an = k / (i - 1);if (a0 > n) break;if (an > n) an = n;ans += (k % an + k % (a0 + 1)) * (an - a0) / 2; } for (int i = 1; i <= n && i <= b; i++) ans += k % i; return ans;}int main() { while (~scanf("%lld%lld", &n, &k)) {printf("%lld\n", solve()); } return 0;}