Description Download as PDF
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 ∑ni=1 (k mod i).
对于一段连续的i..j,如果除k的商相同,那么除k的余数是一个等差数列。这样每一段都可以O(1)求出。
这样问题就变成了对于k/i=p,找到最大的j,使n/j=p。不难发现,若p=0,则j=n。否则j=k/p。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define LL long long
int main()
{
int i,j,k,m,n,p,q;
LL ans,x,y,z;
while (scanf("%d%d",&n,&k)==2)
{
ans=0;
for (i=1;i<=n;i=j+1)
{
p=k/i;
if (p==0) j=n;
else j=min(k/p,n);
x=k%i;
y=k%j;
ans+=(x+y)*(j-i+1)/2;
}
printf("%lld\n",ans);
}
}