[UVA][數學] 1363 - Joseph's Problem
Joseph likes taking part in programming contests. His favorite problem is, of course, Joseph's problem. It is stated as follows.
There are n persons numbered from 0 to n - 1 standing in a circle. The person number k, counting from the person number 0, is executed. After that the person number k of the remaining persons is executed, counting from the person after the last executed one. The process continues until only one person is left. This person is a survivor. The problem is, given n and k detect the survivor's number in the original circle.
Of course, all of you know the way to solve this problem. The solution is very short, all you need is one cycle:
r := 0; for i from 1 to n do r := (r + k) mod i; return r;
Here ``x mod y" is the remainder of the division of x
by y
But Joseph is not very smart. He learned the algorithm, but did not learn the reasoning behind it. Thus he has forgotten the details of the algorithm and remembers the solution just approximately.
He told his friend Andrew about the problem, but claimed that the solution can be found using the following algorithm:
r := 0; for i from 1 to n do r := r + (k mod i); return r;
Of course, Andrew pointed out that Joseph was wrong. But calculating the function Joseph described is also very interesting.
Given n
and k
, find
(k mod i)
.
Input
The input file contains several test cases, each of them consists of a line containing n
and k
(1n, k
109)
Output
For each test case, output a line containing the sum requested.
Sample Input
5 3
Sample Input
7
try this code:
for(int i = 1; i <= n; i++) {
printf("%d : %d %d\n", i, k/i, k%i);
}
n = 50, k = 50
1 : 50 0
2 : 25 0
3 : 16 2
4 : 12 2
5 : 10 0
6 : 8 2
7 : 7 1
8 : 6 2
9 : 5 5
10 : 5 0
11 : 4 6
12 : 4 2
13 : 3 11
14 : 3 8
15 : 3 5
16 : 3 2
17 : 2 16
18 : 2 14
19 : 2 12
20 : 2 10
21 : 2 8
22 : 2 6
23 : 2 4
24 : 2 2
25 : 2 0
26 : 1 24
27 : 1 23
28 : 1 22
29 : 1 21
30 : 1 20
31 : 1 19
32 : 1 18
33 : 1 17
34 : 1 16
35 : 1 15
36 : 1 14
37 : 1 13
38 : 1 12
39 : 1 11
40 : 1 10
41 : 1 9
42 : 1 8
43 : 1 7
44 : 1 6
45 : 1 5
46 : 1 4
47 : 1 3
48 : 1 2
49 : 1 1
50 : 1 0
我們發現,當 k/i 相同時,呈現一個 "等差級數"。
如此判定下 ... 計算之
#include <stdio.h>
int main() {
long long n, k;
while(scanf("%lld %lld", &n, &k) == 2) {
long long l = 1, r, div;
long long ret = 0;
while(l <= k) {
div = k/l;
r = k/div;
// d = div
if(r > n) r = n;
long long a0 = k%l, d = -div, tn = r-l+1;
ret += (a0*2+(tn-1)*d)*tn/2;
//printf("%lld %lld %lld\n", l, r, k%l);
l = r+1;
if(r == n)
break;
}
if(l <= n)
ret += (n-l+1)*k;
printf("%lld\n", ret);
}
return 0;
}
/*
999999999 999999999
999999999 999999998
999999990 999999999
*/