Josephus Problem in Powershell

Published on 20 May 2025 (Updated: 20 May 2025)

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

Current Solution

function Show-Usage() {
    Write-Host "Usage: please input the total number of people and number of people to skip."
    Exit 1
}

<#
Reference: https://en.wikipedia.org/wiki/Josephus_problem#The_general_case

Use zero-based index algorithm:

    g(1, k) = 0
    g(m, k) = [g(m - 1, k) + k] MOD m, for m = 2, 3, ..., n

Final answer is g(n, k) + 1 to get back to one-based index
#>
function Get-JosephusProblem([int]$N, [int]$K) {
    $G = 0
    for ($M = 2; $M -le $N; $M++) {
        $G = ($G + $K) % $M
    }

    $G + 1
}

if ($args.Length -lt 2) {
    Show-Usage
}

try {
    $N = [int]::Parse($args[0])
    $K = [int]::Parse($args[1])
} catch {
    Show-Usage
}

Write-Host (Get-JosephusProblem $N $K)

Josephus Problem in Powershell 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.