This program is an implementation of the famous Josephus problem from antiquity. It accepts two parameters:

  • M - every Mth person is eliminated
  • N - the number of people

The result is a list in the order in which people are eliminated. The last person in the list is safe.

using System;
using System.Text;

namespace ConsoleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            int M = Int32.Parse(args[0]); // eliminating every M-th person
            int N = Int32.Parse(args[1]); // the number of people

            Queue q = new Queue();

            // Populate the queue with N numbers.
            for (int i = 0; i < N; ++i)
                q.Enqueue(i);

            StringBuilder sb = new StringBuilder();

            while (!q.IsEmpty)
            {
                for (int i = 0; i < M; ++i)
                {
                    if (i < M - 1)
                        q.Enqueue(q.Dequeue()); // skipped persons; re-attach them to the end of queue
                    else
                        sb.Append(q.Dequeue() + " "); // an eliminated person
                }
            }

            Console.WriteLine(sb.ToString()); // print the order in which people are eliminated
            Console.ReadKey();
        }

        class Queue
        {
            private Node first; // link to least recently added node
            private Node last;  // link to most recently added node
            private int N;      // queue size

            public bool IsEmpty { get { return first == null; } } // the same as N == 0
            public int Size { get { return N; } }

            public void Enqueue(T item)
            {
                // Add item to the end of the list.
                Node oldLast = last;
                last = new Node();
                last.Item = item;
                last.Next = null;

                if (IsEmpty)
                    first = last;
                else
                    oldLast.Next = last;

                ++N;
            }

            public T Dequeue()
            {
                // Remove item from the beginning of the list.
                T item = first.Item;
                first = first.Next;

                if (IsEmpty)
                    last = null;

                --N;

                return item;
            }

            // Nested class to define nodes of linked list.
            private class Node
            {
                public T Item { get; set; }
                public Node Next { get; set; }

                public override string ToString() { return (Item == null ? "null" : Item.ToString()); }
            }
        }
    }
}

Sample outputs:

Input Output
2 7 1 3 5 0 4 2 6
2 8 1 3 5 7 2 6 4 0
3 8 2 5 0 4 1 7 3 6