Shepherds and Engineers
Time limit1sMemory limit128 MB
Given s sheep needed in town after b bridges whose tolls follow a strict divisibility rule, find the minimum starting number of sheep.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Greedy, Math, Implementation
- Solved
- No attempts yet
Problem
Westmoreland is a peaceful country of quiet rivers, rough moors, and shepherds who herd their flocks. To reach the town's sheep market a shepherd must cross rivers. After heavy rainfall wading became too dangerous, so engineers built bridges and were allowed to charge a toll, paid in sheep, on every shepherd who crosses.
To stop excessive tolls the king decreed that whenever a shepherd crosses a bridge with some sheep and the engineer takes a toll:
- what the shepherd keeps must be strictly more than what the engineer takes, and
- what the shepherd keeps must be an integral multiple of what the engineer takes.
The engineer always charges the largest toll these rules allow. So if the shepherd arrives at a bridge with sheep and pays a toll of sheep, the kept sheep must satisfy for some integer ; equivalently with . Among all valid tolls the engineer takes the maximum . If no valid toll exists (for example when the shepherd has only one or two sheep) the crossing is free.
Shepherds fight back by giving away sheep to local shepherds before a bridge, lowering their count to a number with a smaller maximum toll. For example, a shepherd who must sell sheep four bridges from town can start with sheep:
- Bridge 1: sheep, toll , keep .
- Bridge 2: sheep, toll , keep .
- Bridge 3: instead of paying the toll on , give away sheep, cross with , toll , keep .
- Bridge 4: give away sheep, cross with , toll , keep .
He enters town with exactly sheep, and no smaller starting number works.
Given the number of sheep a shepherd wants to bring into town and the number of bridges on the way, find the minimum number of sheep he must start his journey with. Note that the best plan may sometimes leave him entering town with more sheep than required.
Input
The first line contains a single integer : the number of test cases.
Each test case is a single line with two integers and :
- () — the number of sheep that must enter the town,
- () — the number of bridges to cross.
Output
For each test case, print a single line with one integer: the minimum number of sheep the shepherd must start with.