您的位置:首页 > 其它

Joseph's Problem 数论 找规律

2017-04-20 23:06 295 查看
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 <= 10 9).

Output

Output the sum requested.

Sample Input

5 3

Sample Output

7

看了别人的思路

“对于k/i相同的那些项是形成等差数列的,把整个序列进行拆分成[k,k/2],[k/2, k/3], [k/3,k/4]…k[k/a, k/b]这样的等差数列,枚举到sqrt(k)就可以了(大于sqrt(k) 只剩下除数单个的情况了 从1到k/a枚举即可),还剩下[1,k/a]的序列需要去枚举,总时间复杂度为O(sqrt(k)),n大于k的情况,n超过k的部分全是等于k,为(n - k) * k”

#include <cstdio>
#include <cmath>
typedef long long ll;

int main(){
ll n,k;
scanf("%lld%lld",&n,&k);
ll ans = 0;
ll a = (ll)sqrt(k*1.0),b = k/a;
if (n > k) ans += (n-k)*k;
for (ll i = a; i > 1; --i){
ll s = k/i,e = k/(i-1);
if (s > n) break;    //大于n再去从2到k/sqrt(k)枚举
if (e > n) e = n;   //e到n的范围
ans += (k%(s+1)+k%e)*(e-s)/2;
}
for (int i = 2; i <= n&&i <= b; ++i){
ans += k%i;
}
pri
4000
ntf("%lld\n",ans);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: