Josephus, Once More!
Time limit2sMemory limit128 MB
People are selected around a circle by the rule f(x)=(a x^2+b) mod N, starting at 0; each drinks on the second selection, and on the third everyone leaves. Count how many never drink.
- Level
Medium7 of 10
- Topics
- Simulation, Math, Implementation
- Solved
- No attempts yet
Problem
Sanggeun, a pro drinker, drinks in exactly the same order as the Josephus problem. Having solved the Josephus problem more than a thousand times, he can figure out in his head who drinks last. So his drinking buddies came up with a new order to beat him.
First, everyone sits around a round table. If people sit down, they are numbered from to .
Unlike the classic Josephus problem, the next person is chosen using two integers and . If the currently selected person is numbered , the next person is numbered .
The very first person selected is number , and every subsequent person is chosen with the formula above.
Each person gets one extra chance. That is, being selected once does not mean drinking; a person drinks only when selected for the second time.
If a person is selected for the third time, everyone immediately jumps up and goes home.
Given , , and , write a program that finds how many people go home without drinking.
Input
The input consists of several test cases. Each test case is a single line containing three integers , , and separated by spaces. (, ) Also, the number of steps needed for the first person to drink is less than . The last line of the input contains a single .
Output
For each test case, print the number of people who go home without drinking, one per line.
Hint
This is a variation of the classic Josephus problem, where people sit in a circle and are selected one by one according to a fixed counting rule.