Thanos Hates Josephus
InterviewTime limit0.1sMemory limit512 MB
Find the last squirrel left when each round keeps the first squirrel, removes the next K-1 clockwise, and the first moves to the right, for N and K up to 10^6.
- Level
Medium5 of 10
- Topics
- Dynamic programming, Simulation
- Solved
- No attempts yet
Problem
squirrels sit in a circle in clockwise order, numbered from to . Thanos snapped his fingers and removed the second squirrel each time, in order. When he learned that Josephus, a mathematician from a neighboring country, had already used that method, he was annoyed. So Thanos devised a new way to remove squirrels.
Squirrel is the first squirrel at the start. When Thanos snaps, squirrels are selected clockwise starting from the first squirrel. Then the squirrels th, excluding the first, are removed in increasing order of number, and only the first squirrel survives. However, if fewer than squirrels remain, every squirrel except the first is removed. After the removal, if at least squirrels remain, the squirrel to the right of the first becomes the new first squirrel, and the process repeats. The process continues until squirrel remains.
Given and , find the number of the squirrel that remains last.

Input
The first line contains integers and , separated by a space. ()
Output
Print the number of the last remaining squirrel.
Hint
Let us love animals.