约瑟夫环问题

约瑟夫环是一个数学的应用问题:
已知16个人(以编号0,1,2...15分别表示)围坐在一张圆桌周围。从编号为0的人开始报数(报数从1开始),数到3的倍数的那个人出列;直到圆桌剩下一个,请打印出每个人出列的编号
 
C#非递归发实现

 static void Main(string[] args)
        {
            //保存移走的人的个数
            int RemoveCount = 0;
            //保存每个人读出的数字
            int ReadCount = 0;
            int[] personNum = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };

            while (true)
            {
                for (int i = 0; i < personNum.Length; i++)
                {
                    //表示没有移除的数据
                    if (personNum[i] != -1)
                    {
                        //数字加1
                        ReadCount++;
                        if (ReadCount % 3 == 0)
                        {
                            //设置为移除-1
                            Console.WriteLine(personNum[i]+"号移除");
                            personNum[i] = -1;
                            //移除的个数
                            RemoveCount++;
                            if (RemoveCount >= 16)
                            {
                                break;
                            }
                        }
                    }
                }
                if (RemoveCount >= 16)
                {
                    break;
                }
            }
            //最后输出一个数字
            for (int i = 0; i < personNum.Length; i++)
            {
                if (personNum[i] != -1)
                {
                    Console.WriteLine("最后一个人原来的编号是"+personNum[i]);
                    break;

                }
            }
        }

 
 
 
 
posted @ 2013-12-02 11:30  王国营的博客  阅读(262)  评论(0编辑  收藏  举报