Eeny Meeny Moo

题目描述
Surely you have made the experience that when too many people use the Internet simultaneously, the net becomes very, very slow. 
To put an end to this problem, the University of Ulm has developed a contingency scheme for times of peak load to cut off net access for some cities of the country in a systematic, totally fair manner. Germany's cities were enumerated randomly from 1 to n. Freiburg was number 1, Ulm was number 2, Karlsruhe was number 3, and so on in a purely random order. 
Then a number m would be picked at random, and Internet access would first be cut off in city 1 (clearly the fairest starting point) and then in every mth city after that, wrapping around to 1 after n, and ignoring cities already cut off. For example, if n=17 and m=5, net access would be cut off to the cities 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 Ulm 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 city 2 is the last city selected. 

Your job is to write a program that will read in a number of cities n and then determine the smallest integer m that will ensure that Ulm can surf the net while the rest of the country is cut off.
输入
The input will contain one or more lines, each line containing one integer n with 3 <= n < 150, representing the number of cities in the country. 
Input is terminated by a value of zero (0) for n.
输出
For each line of the input, print one line containing the integer m fulfilling the requirement specified above.
样例输入
大家都有这种经验,当太多的人同时使用互联网的时候,网络会变得非常,非常缓慢。为了结决这一问题,北师大制定了一项应急计划,在网络使用高峰期切断一些连接以保证网络的畅通。所有的网络连接都将被标号(从1开始,依次是2号,3号……)。当应急计划启动的时候,首先切断1号连接,然后切断1号之后的第M个连接,在然后是上一个被切断之后的第M个连接,以此类推。例如,如果有17个连接,并且M=5,则依次切断的顺序为[1,6,11,16,5,12,2,9,17,10,4,15,14,3,8,13,7]。DXY同学大公无私地将自己的机器设置为1连接,而ZSL同学的机器为2号连接。原本这种切断连接的方式是很公平的,不过ZSL同学想要知道当M为多少时,他的机器会被最后一个切断连接(他果然很不厚道)。                
 
Input
输入不止一行,每一行都只有一个无符号整数N,且 3 <= n < 150。当输入0的时候程序退出。                
 
Output
对于每一行的输入,输出一个最小的值M,满足ZSL同学的2号连接会被最后一个切断。                
 
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

//第一个人总是最先被删除的。因此可以把该问题看成是n-1个人的问题,  
//希望最后问题中最原始的2留下来,找这个递增的m  */
#include<stdio.h>
#include<string.h>
#include<math.h>

int call(int n,int m)
{
    int i,s=0;
    for(i=2;i<=n-1;i++)
    {
        s=(s+m)%i;
//如果s从1开始,则(s+m-1)%i+1  
    }
    return s;
}
int main()
{
    int n,i;
    while(scanf("%d",&n),n)
    {
        if(n==0)
            break;
        for(i=1;;i++)
        {
            if(call(n,i)==0)
            {

//编号为1的城市已经出列,所以第二座城市现在编号为1,但递推式的第一个值为0  
                printf("%d\n",i);
                break;
            }
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/A_I_Q/article/details/82186110