18 Star 133 Fork 63

编程语言算法集 / C-Sharp

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
JosephusProblem.cs 968 Bytes
一键复制 编辑 原始数据 按行查看 历史
Kalkwst 提交于 2022-10-18 21:03 . Add Josephus Problem solver (#356)
using System;
namespace Algorithms.Numeric;
public static class JosephusProblem
{
/// <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>
public static long FindWinner(long n, long k)
{
if (k <= 0)
{
throw new ArgumentException("The step cannot be smaller than 1");
}
if (k > n)
{
throw new ArgumentException("The step cannot be greater than the size of the group");
}
long winner = 0;
for (long stepIndex = 1; stepIndex <= n; ++stepIndex)
{
winner = (winner + k) % stepIndex;
}
return winner + 1;
}
}
C#
1
https://gitee.com/TheAlgorithms/C-Sharp.git
git@gitee.com:TheAlgorithms/C-Sharp.git
TheAlgorithms
C-Sharp
C-Sharp
master

搜索帮助

53164aa7 5694891 3bd8fe86 5694891