Josephus problem

Revision as of 11:48, 27 October 2012 by rosettacode>Ledrug (draft task)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Josephus problem is a math puzzle with a grim description: prisoners are standing on a circle, sequentially numbered from to . An executioner walks along the circle, starting from prisoner , removing every -th prisoner and killing him. As the process goes on, the circle becomes smaller and smaller, until only one prisoner remains, who is then freed. For example, if there are prisoners and , the order the prisoners are killed in (let's call it the "killing sequence") will be 1, 3, 0, and 4, and the survivor will be #2.

Josephus problem is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Task Given any , find out which prisoner will be the final survivor. In one such incident, there were 41 prisoners and every 3rd prisoner was being killed (). Among them was a clever chap name Josephus who worked out the problem, stood at the surviving position, and lived on to tell the tale. Which number was he?

Extra The captors may be especially kind and let survivors free, and Josephus might just have friends to save. Provide a way to calculate which prisoner is at any given position on the killing sequence.

Notes

  1. You can always play the executioner and follow the procedure exactly as described, walking around the circle, counting (and cutting off) heads along the way. This would yield the complete killing sequence and answer the above questions, with a complexity of probably . However, individually it takes no more than to find out which prisoner is the -th to die.
  2. If it's more convenient, you can number prisoners from to instead. If you choose to do so, please state it clearly.
  3. An alternative description has the people committing assisted suicide instead of being executed, and the last person simply walks away. These details are not relevant, at least not mathematically.