- Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathJosephusProblem.cs
33 lines (28 loc) · 968 Bytes
/
JosephusProblem.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
usingSystem;
namespaceAlgorithms.Numeric;
publicstaticclassJosephusProblem
{
/// <summary>
/// Calculates the winner in the Josephus problem.
/// </summary>
/// <param name="n">The number of people in the initial circle.</param>
/// <param name="k">The count of each step. k-1 people are skipped and the k-th is executed.</param>
/// <returns>The 1-indexed position where the player must choose in order to win the game.</returns>
publicstaticlongFindWinner(longn,longk)
{
if(k<=0)
{
thrownewArgumentException("The step cannot be smaller than 1");
}
if(k>n)
{
thrownewArgumentException("The step cannot be greater than the size of the group");
}
longwinner=0;
for(longstepIndex=1;stepIndex<=n;++stepIndex)
{
winner=(winner+k)%stepIndex;
}
returnwinner+1;
}
}