> For the complete documentation index, see [llms.txt](https://trizen.gitbook.io/sidef-lang/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://trizen.gitbook.io/sidef-lang/programming_tasks/j/josephus_problem.md).

# Josephus problem

Iterative:

```ruby
func josephus(n, k) {
    var prisoners = @^n
    while (prisoners.len > 1) {
        prisoners.rotate!(k - 1).shift
    }
    return prisoners[0]
}
```

Recursive:

```ruby
func josephus(n, k) {
    n == 1 ? 0 : ((__FUNC__(n-1, k) + k) % n)
}
```

Calling the function:

```ruby
var survivor = josephus(41, 3)
say "Prisoner #{survivor} survived."
```

#### Output:

```
Prisoner 30 survived.
```
