All tasks
Hardmathrecursion

Josephus Problem

Time limit 2 s · Memory 64 MBAcceptance: —Solved by: 0

Statement

One line contains n and k. n people numbered 1 to n stand in a circle. Counting starts at person 1: each time the k-th person is removed from the circle and counting resumes from the next one. Print the number of the last person remaining.

Examples

Example 1
Input
5 2
Output
3
Example 2
Input
1 5
Output
1

Constraints

  • 1 ≤ n ≤ 10^5
  • 1 ≤ k ≤ 10^9
Solve this task to unlock the editorial.

AI tutor

Stuck? Get a nudge — the tutor explains the idea, it never hands you the solution.