本文主要是介绍Joseph's problem I 筛法求素数和数组环,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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;}
这篇关于Joseph's problem I 筛法求素数和数组环的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!