Joseph's Problem 数论 找规律

探讨约瑟夫问题的一个变种版本,通过优化算法实现高效求解。该算法利用等差数列特性,将问题分解并仅需遍历到sqrt(k),达到O(sqrt(k))的时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
    }
    printf("%lld\n",ans);
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值