Josephus Problem in C#

Published on 06 November 2024 (Updated: 06 November 2024)

Welcome to the Josephus Problem in C# page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

using System;

namespace JosephusProblem
{
    class Program
    {
        const string Usage = "Usage: please input the total number of people and number of people to skip.";

        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine(Usage);
                return;
            }

            if (!int.TryParse(args[0], out int n) || !int.TryParse(args[1], out int k) || n <= 0 || k <= 0)
            {
                Console.WriteLine(Usage);
                return;
            }

            int survivor = FindJosephusPosition(n, k);

            Console.WriteLine(survivor);
        }

        static int FindJosephusPosition(int n, int k)
        {
            int result = 0;

            for (int m = 2; m <= n; m++)
            {
                result = (result + k) % m;
            }

            return result + 1;
        }
    }
}

Josephus Problem in C# was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

No 'How to Implement the Solution' section available. Please consider contributing.

How to Run the Solution

No 'How to Run the Solution' section available. Please consider contributing.