代码之路- Joseph‘s problem I(Joseph问题)

题目

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

思路

约瑟夫环指的是在n个人中,从第一个人开始数数,数到m时,第m个人就被淘汰,之后再继续从第m+1个人开始重新数数。求最后被留下来的人在初始n个人中排第几个。而本题m是变量。不过只要修改下求解方程即可。
约瑟夫环可以从一开始开始求解,不过此时需要创立数组进行维护,由于维护非常麻烦,所以想到能否从最后一个开始去逆推。于是找到了如下的关系式

x’(第n轮的序号)=x(第n-1轮的序号)-(m(要数的个数)% people(第n-1轮的人数)

修改下为如下式子:
x = (x’ + m(第n-1轮要数的个数)) % people

AC代码

#include <stdio.h>
#include <stdlib.h>
#define Max 3502
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int prime[Max];

void isprime(){
	int cnt = 0, i = 3;
	prime[cnt++] = 2;
	while(1){
		int flag = 0;
		for(int j = 2; j < i; j++){
			if(i%j == 0){
				flag = 1;
				break;
			}
		}
		if(flag == 0){
			prime[cnt++] = i;
		}
		if(cnt > Max){
			break;
		}
		i += 2;
	}
}

int main() {
	int n;
	isprime();
	while(scanf("%d",&n),n){
		int cut = n-2, ans = 0, people = 2;
		for(; cut >=0; cut--, people++){
			int box = prime[cut];
			ans = (ans+box) % people;
		}
		printf("%d\n",ans+1);
	}
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值