Skip to the content

The last one in the circle

Problem

In the year 67, trapped in a cave under siege, Flavius Josephus and his soldiers sat in a circle to decide, turn by turn, who would leave. The story goes that Josephus knew exactly where to sit to be the last one. Write a function that takes n, how many soldiers there are, and k, how often one leaves, both whole numbers greater than 0. The soldiers are numbered 1 to n around the circle, and after n comes 1 again. Soldier 1 says "one", the next says "two", and whoever says k leaves. The one right after them starts again at "one", and so on until only one is left. Return that soldier's number, as a whole number.

With n = 7 and k = 3 they leave in this order: 3, 6, 2, 7, 5 and 1, so it returns 4. If k is larger than the soldiers left, the count goes around as many times as needed. With k = 1 each one leaves as soon as they say "one", so n is left. With a single soldier, it returns 1.

Examples

  • The example

    7, 3 → 4

  • Every second one leaves

    5, 2 → 3

  • Ten soldiers, every second one

    10, 2 → 5

  • With k equal to 1 the last one stays

    6, 1 → 6

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def last_standing(n, k):
    pass

JavaScript

function lastStanding(n, k) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n²) challenges

See all challenges →