Problem 343
Josephus Problem
Medium · 20 pts · Math, Recursion, Simulation
Problem
N people stand in a circle, numbered 1 to N clockwise. Starting from person 1, count K people clockwise (counting the starting person as 1); the K-th person is removed from the circle. Counting then continues from the next person, and the process repeats until only one person is left. Print the number of the survivor. A simulation with a list is O(N·K), while the recurrence J(n) = (J(n-1) + K) mod n solves it in O(N).
Input
Two integers N and K.
Output
Print the number of the last remaining person.
Constraints
1 <= N <= 1000000; 1 <= K <= 1000000000
Example input
5 2
Example output
3
Explanation
With N = 5 and K = 2, people are removed in the order 2, 4, 1, 5. Person 3 is the last one left.