Recently you must have experienced that when too many people use the BBS simultaneously, the net becomes very, very slow.
To put an end to this problem, the Sysop has developed a contingency scheme for times of peak load to cut off net access for some buildings of the university in a systematic, totally fair manner. Our university buildings were enumerated randomly from 1 to n. XWB is number 1, CaoGuangBiao (CGB) Building is number 2, and so on in a purely random order.
Then a number m would be picked at random, and BBS access would first be cut off in building 1 (clearly the fairest starting point) and then in every mth building after that, wrapping around to 1 after n, and ignoring buildings already cut off. For example, if n=17 and m=5, net access would be cut off to the buildings in the order [1,6,11,16,5,12,2,9,17,10,4,15,14,3,8,13,7]. The problem is that it is clearly fairest to cut off CGB Building last (after all, this is where the best programmers come from), so for a given n, the random number m needs to be carefully chosen so that building 2 is the last building selected.
Your job is to write a program that will read in a number of buildings n and then determine the smallest integer m that will ensure that our CGB Building can surf the net while the rest of the university is cut off.
Input Specification
The input file will contain one or more lines, each line containing one integer n with 3 <= n < 150, representing the number of buildings in the university.Input is terminated by a value of zero (0) for n .
Output Specification
For each line of the input, print one line containing the integer m fulfilling the requirement specified above.Sample Input
3 4 5 6 7 8 9 10 11 12 0
Sample Output
2 5 2 4 3 11 2 3 8 16
题目大意:建筑从1到n编号,设定一个常数m。首先去掉第一个建筑然后再从开端数,第m幢建筑的收集被割断,然后再从1开端持续往下数。数到n之后回到第1幢。曹光彪大楼的编号是2,这是策画机学院的大本营。此题的目标就是按照上述规矩,断定常数m,使得曹楼是全校最后一幢被割断收集的建筑。
约瑟夫环问题,运用数学公式。
m为报的那个数,n为总人数。
(注:n个人(编号0~(n-1)),从0开始报数,报到m-1的退出,剩下的人继续从0开始报数。求胜利者的编号。)
f[1]=0;
f[i]=(f[i-1]+m)%i(i>1)
当f[n]=0时,f[n]=n。
令f表示i个人玩游戏报m退出最后胜利者的编号,最后的结果自然是f[n].编号为f[n]+1。
#include <iostream>
using namespace std;
int judege(int n,int m)
{
int ans=0;
for (int i=2; i<n; i++)
{
ans=(ans+m)%i;
}
if(ans+1==1) //因为去掉了第一个数1,所以第二个数2就相当于1.
{
return 0;
}
return 1;
}
int main()
{
int n;
while (cin>>n && n)
{
int m=1;
while (judege(n, m))
{
m++;
}
cout<<m<<endl;
}
return 0;
}