The problem is named after Flavius Josephus, a Jewish historian living in the 1st century. According to Josephus' account of the siege of Yodfat, he and his 40 soldiers were trapped in a cave by Roman soldiers. They chose suicide over capture, and settled on a serial method of committing suicide by drawing lots. Josephus states that by luck or possibly by the hand of God, he and another man remained until the end and surrendered to the Romans rather than killing themselves.
An executioner walks along the circle, starting from prisoner 0, removing every k-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 n = 5 prisoners and k = 2, 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.
Given any n, k > 0, and m >= 0, find out which prisoner(s) will be the final survivor(s). In one such incident, there were 41 prisoners and every 3rd prisoner was being killed (k = 3). 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? The captors may be especially kind and let m survivors free, and Josephus might just have m − 1 friends to save.
Provide a way to calculate which prisoner is at any given position on the killing sequence.
Input Format:
The line of input will be the values of n, k and m respectively
n = total number of prisoners
k = killing pattern (killing sequence)
m = number of prisoners who will not be executed
Output Format:
The first line of output will be all the prisoners (labelled by their indices) who are executed
The second line of output will be the prisoners (labelled by their indices) who survived the execution.
Reminder: The index (first prisoner) should start from 0. If there are no survivors, please display, “No prisoners lived”