And Then There Was One

Interview

Time limit1sMemory limit128 MB

Summary
Simulate a Josephus-style circle elimination game with a custom starting removal point and report the last remaining stone for each test case.
Level

Easy3 of 10

Topics
Simulation, Queue, Math
Solved
No attempts yet

Problem

Let's play a stone-removal game.

Initially, as shown in Figure 1, nn stones numbered from 11 to nn are arranged clockwise in a circle. Two numbers kk and mm are also given. Starting from this arrangement, remove the stones one at a time according to the rules below, until only one stone remains.

  • Step 1: remove stone mm.
  • Step ii (for i≥2i \ge 2): starting from the position of the stone removed in step (i−1)(i-1), remove the kk-th stone clockwise among the remaining stones. That is, skip k−1k-1 stones and remove the next one; stones that have already been removed are not counted while skipping.

Carry out step 1, step 2, step 3, and so on in order until a single stone is left. That last stone is the answer.

For example, as in Figure 1, when n=8n = 8, k=5k = 5, m=3m = 3 the answer is 11.

Figure 1: Game Example

  • Initial state: 8 stones are placed clockwise.
  • Step 1: since m=3m = 3, stone 3 is removed.
  • Step 2: starting from 3 and with k=5k = 5, skip stones 4, 5, 6, 7 (four stones) and remove stone 8.
  • Step 3: starting from 8, skip stones 1, 2, 4, 5 and remove stone 6. Note that stone 3 is ignored (it is already removed, so it is not counted among the skipped stones).
  • Steps 4-7: continue until only one stone remains.
  • Finally, the remaining stone is 1, so the answer is 1.

Input

The input consists of several data lines; each data line contains three numbers:

n k m

The line after the last data line contains three zeros. Each number satisfies the following ranges.

2≤n≤100002 \le n \le 10000, 1≤k≤100001 \le k \le 10000, 1≤m≤n1 \le m \le n

The number of data lines is fewer than 100.

Output

For each data line, output the number of the last remaining stone.

Examples2

  1. Example 1

    Input
    8 5 3
    100 9999 98
    10000 10000 10000
    0 0 0
    
    Expected output
    1
    93
    2019
    
  2. Example 2

    Input
    5 2 1
    0 0 0
    
    Expected output
    2