Skip to content

Commit

Permalink
Add Josephus Problem in C# (#3979)
Browse files Browse the repository at this point in the history
  • Loading branch information
oakes777 authored Nov 6, 2024
1 parent c622ece commit 5afad5c
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions archive/c/c-sharp/JosephusProblem.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
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;
}
}
}

0 comments on commit 5afad5c

Please sign in to comment.