# UVA1363 LA3521 POJ2800 ZOJ2646 Joseph‘s Problem【约瑟夫环+数学】

Joseph’s Problem
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 7906 Accepted: 2107

Description

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 numberk, 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 ∑1<=i<=n(k mod i).

Input

The input file contains n and k (1<= n, k <= 109).

Output

Output the sum requested.

Sample Input

5 3

Sample Output

7

Source

Northeastern Europe 2005

AC的C++语言程序如下：

/* UVA1363 LA3521 POJ2800 ZOJ2646 Joseph's Problem */

#include <iostream>
#include <cstdio>
#include <cmath>

using namespace std;

typedef long long LL;

LL jose(LL n, LL k)
{
LL sum = 0, a = sqrt(k), b = k / a;
if(n > k) sum += (n - k) * k;
for(LL i = a; i >= 2; i--) {
LL start = k / i;
LL end2 = k / (i - 1);
if(start > n) break;
if(end2 > n) end2 = n;
sum += (k % end2 + k % (start + 1)) * (end2 - start) / 2;
}
for(LL i = 1; i <= n && i <= b; i++)
sum += k % i;

return sum;
}

int main()
{
LL n, k;
while(~scanf("%lld%lld", &n, &k))
printf("%lld\n", jose(n, k));

return 0;
}


08-01 1708                                                                          01-11 947
03-05 1025
05-29 1224
07-07 2082
08-02 1254
07-29 1139
08-02 1万+
09-02 1686
07-30 1111
07-22 1170
08-04 1280
09-17 1035
05-17 608
08-08 1631
08-13 1058
04-13 254
07-31 1万+
08-04 3031
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客