Shepherds and Engineers

Time limit1sMemory limit128 MB

Summary
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:

  1. what the shepherd keeps must be strictly more than what the engineer takes, and
  2. 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 nn sheep and pays a toll of tt sheep, the kept sheep n−tn - t must satisfy n−t=k⋅tn - t = k\cdot t for some integer k≥2k \ge 2; equivalently n=(k+1) tn = (k+1)\,t with k+1≥3k+1 \ge 3. Among all valid tolls the engineer takes the maximum tt. 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 4040 sheep four bridges from town can start with 4747 sheep:

  • Bridge 1: 4747 sheep, toll 11, keep 4646.
  • Bridge 2: 4646 sheep, toll 22, keep 4444.
  • Bridge 3: instead of paying the toll 1111 on 4444, give away 11 sheep, cross with 4343, toll 11, keep 4242.
  • Bridge 4: give away 11 sheep, cross with 4141, toll 11, keep 4040.

He enters town with exactly 4040 sheep, and no smaller starting number works.

Given the number ss of sheep a shepherd wants to bring into town and the number bb 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 TT: the number of test cases.

Each test case is a single line with two integers ss and bb:

  • ss (0<s≤1060 < s \le 10^6) — the number of sheep that must enter the town,
  • bb (0≤b≤10000 \le b \le 1000) — 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.

Examples1

  1. Example 1

    Input
    3
    40 4
    13 1
    10 10
    
    Expected output
    47
    17
    34