Joseph's problem I 筛法求素数和数组环

本文探讨了Joseph's Problem的一个新变种,其中淘汰顺序由连续的素数决定。通过筛法求素数和环状数组算法,文章提供了一个预测最终幸存者位置的解决方案。

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

HOJ 1016

Problem Description

The Joseph’s problem is notoriously known. For those who are not familiar with the problem, among n people numbered 1,2…n, standing in circle every mth is going to be executed and only the life of the last remaining person will be saved. Joseph was smart enough to choose the position of the last remaining person, thus saving his life to give the message about the incident.
Although many good programmers have been saved since Joseph spread out this information, Joseph’s cousin introduced a new variant of the malignant game. This insane character is known for its barbarian ideas and wishes to clean up the world from silly programmers. We had to infiltrate some the agents of the ACM in order to know the process in this new mortal game.
In order to save yourself from this evil practice, you must develop a tool capable of predicting which person will be saved.
The Destructive Process
The persons are eliminated in a very peculiar order; m is a dynamical variable, which each time takes a different value corresponding to the prime numbers’ succession (2,3,5,7…). So in order to kill the ith person, Joseph’s cousin counts up to the ith prime.

Input

It consists of separate lines containing n [1…3501], and finishes with a 0.

Output

The output will consist in separate lines containing the position of the person which life will be saved.

Sample Input

6

Sample Output

4

筛法求素数参考ACM基础知识储备-快速筛法求素数,数组环的解法参考HOJ1016 Joseph’s problem I

#include <iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
using namespace std;

#define MAX 100000
long long su[MAX],cnt;
bool isprime[MAX];

void prime()
{
    cnt=1;
    memset(isprime,1,sizeof(isprime));
    isprime[0]=isprime[1]=0;
    for(long long i=2; i<=MAX; i++)
    {
        if(isprime[i])
        {
            su[cnt++]=i;
        }
        for(long long j=1;j<cnt&&su[j]*i<MAX;j++)
        {
            isprime[su[j]*i]=0;
        }
    }
}

    int main()
    {
        prime();
        int n;
        while(scanf("%d",&n)==1)
        {

            if(!n)
                break;
        int result=0;
            for(int j=2; j<=n; j++)
            {
                result=(result+su[n-j+1])%j;
            }
            cout << result + 1 << endl;

        }
        return 0;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值