(one day one problem)poj 2800 Joseph's Problem (数学)

来源:互联网 发布:韩端机器人编程软件 编辑:程序博客网 时间:2024/06/03 16:35

题目链接:点击打开链接

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 dor := (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 dor := 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
题目大意:给出n,k,求sigama(k%i)(i-1~n)

题解:既然是有k%i取余,那么当i>k的k%i=k.现在就是求[1,k]内的k%i的和。在纸上画一画可以看出,有以k/i为等差的等差数列。那么等差值为1~sqrt(k).枚举2~sqrt(k)。求出这个区间的和。最后暴力求出1-k/(sqrt(k))的值。为什么是这个区间呢?看一个序列:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15,k=15。那么p=sqrt(k)=3.q=k/3=5.在求等差数列的时候是从q+1开始的。在q之前的都没有求。

#include <iostream>#include <cstring>#include <cmath>#include <algorithm>#include <cstdio>using namespace std;typedef long long LL;int main(){    LL n,k;    while(~scanf("%lld%lld",&n,&k))    {        LL p=(LL)sqrt(k*1.0);        LL q=k/p;        LL sum=0;        if(n>=k)sum+=(n-k)*k;        for(LL i=p;i>1;i--)        {            LL s=k/i;            LL e=k/(i-1);            if(s>n)break;            if(e>n)e=n;            sum+=(k%(s+1)+k%e)*(e-s)/2;        }        for(LL i=1;i<=n&&i<=q;i++)            sum+=k%i;        printf("%lld\n",sum);    }    return 0;}



0 0
原创粉丝点击