Combination Lock
InterviewTime limit1sMemory limit128 MB
For each lock, find the largest total number of ticks turned over the three stages, maximized over all possible starting positions of the dial.
- Level
Medium4 of 10
- Topics
- Math, Simulation, Implementation
- Solved
- No attempts yet
Problem

A combination lock consists of a circular dial that can be turned (clockwise or counterclockwise) and is set into the fixed part of the lock. The dial has evenly spaced ticks, numbered from to , increasing in the clockwise direction. The fixed part of the lock has a mark that always points to one particular tick on the dial. As the dial is turned, the mark points to different ticks.
The lock comes with three code numbers , , . These are non-negative integers, each less than , and no two of them are equal.
The lock is opened in three stages:
- Turn the dial clockwise exactly two full revolutions, then continue turning it clockwise until the mark points to tick .
- Turn the dial one full revolution counterclockwise, then continue turning it counterclockwise until the mark points to tick .
- Turn the dial clockwise until the mark points to tick . The lock now opens.
You must find the maximum possible number of ticks the dial must be turned in order to open the lock. The number of ticks turned is the sum of the ticks turned across the three stages above, and each stage's amount is counted as a positive number regardless of the direction of the turn. The tick that the mark initially points to is not known in advance, so "maximum possible" means the largest total over all possible initial positions of the dial.
Input
The input consists of several test cases, one per line. Each line contains four integers , , , in this order, separated by spaces. is a multiple of with . The numbers , , satisfy the conditions described above (each is at least and less than , and no two are equal). The input is terminated by a line containing four zeros separated by spaces.
Output
For each test case, print on its own line the maximum possible number of ticks the dial must be turned to open the lock. Do not print blank lines between outputs.