34 lines
2.1 KiB
Plaintext
34 lines
2.1 KiB
Plaintext
[[wp:Josephus problem|Josephus problem]] is a math puzzle with a grim description: <math>n</math> prisoners are standing on a circle, sequentially numbered from <math>0</math> to <math>n-1</math>.
|
|
|
|
An executioner walks along the circle, starting from prisoner <math>0</math>,
|
|
removing every <math>k</math>-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 <math>n=5</math> prisoners and <math>k=2</math>, 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.
|
|
|
|
|
|
;Task:
|
|
Given any <big><math>n, k > 0</math></big>, find out which prisoner will be the final survivor.
|
|
|
|
In one such incident, there were 41 prisoners and every 3<sup>rd</sup> prisoner was being killed (<big><math>k=3</math></big>).
|
|
|
|
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 <math>m</math> survivors free,
|
|
<br>and Josephus might just have <big><math>m-1</math></big> friends to save.
|
|
|
|
Provide a way to calculate which prisoner is at any given position on the killing sequence.
|
|
|
|
|
|
;Notes:
|
|
# 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 <math>O(kn)</math>. However, individually it takes no more than <math>O(m)</math> to find out which prisoner is the <math>m</math>-th to die.
|
|
# If it's more convenient, you can number prisoners from <math>1</math> to <math>n</math> instead. If you choose to do so, please state it clearly.
|
|
# 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.
|
|
<br><br>
|
|
|