This page is still under construction.

Parts of this page are still being built. What you see may change.

Tornado operation homework

Time limit1sMemory limit128 MB

Summary
Choose the fewest nondecreasing addition and exponent steps so the iterated value plus C is a multiple of 10 to the P.
Level

Medium7 of 10

Topics
BFS, Graph, Number theory
Solved
No attempts yet

Problem

Time for your math homework. A Tornado operation T(n)T(n) is defined as follows.

T(n)={a(n=0)[T(n−1)+Xn]Yn(n∈Z+)T(n) = \begin{cases} a & (n = 0) \\ \left[ T(n-1) + X_n \right]^{Y_n} & (n \in \mathbb{Z}^{+}) \end{cases}

aa is a given constant and Z+\mathbb{Z}^{+} is the set of positive integers. XnX_n and YnY_n are positive integers, chosen so that Xn≤Xn+1X_n \le X_{n+1} and Yn≤Yn+1Y_n \le Y_{n+1} hold for every positive nn. They also satisfy min⁡X≤Xn≤max⁡X\min X \le X_n \le \max X and min⁡Y≤Yn≤max⁡Y\min Y \le Y_n \le \max Y for every positive nn.

For example, if a=1a = 1, X1=2X_1 = 2, X2=4X_2 = 4 and Y1=Y2=3Y_1 = Y_2 = 3, then

T(2)=[T(1)+X2]Y2=[(T(0)+X1)Y1+X2]Y2=[(1+2)3+4]3=29791T(2) = \left[ T(1) + X_2 \right]^{Y_2} = \left[ (T(0) + X_1)^{Y_1} + X_2 \right]^{Y_2} = \left[ (1 + 2)^3 + 4 \right]^3 = 29791

You are given aa, min⁡X\min X, max⁡X\max X, min⁡Y\min Y, max⁡Y\max Y and two positive integers PP and CC. Your homework is to find the smallest nn for which X1,…,XnX_1, \ldots, X_n and Y1,…,YnY_1, \ldots, Y_n can be chosen so that T(n)+CT(n) + C is divisible by 10P10^P. Here nn is a non-negative integer, and n=0n = 0 means that no operation is applied at all, so the value is T(0)=aT(0) = a.

Input

The input holds one or more test cases. The first line contains a single integer TT, the number of test cases (1≤T≤2001 \le T \le 200). Each of the next TT lines holds one test case.

Each of those lines contains 7 integers aa, min⁡X\min X, max⁡X\max X, min⁡Y\min Y, max⁡Y\max Y, PP and CC in this order, separated by single spaces (1≤min⁡X,max⁡X,min⁡Y,max⁡Y≤1001 \le \min X, \max X, \min Y, \max Y \le 100, 1≤P≤31 \le P \le 3, 1≤a,C≤1 000 0001 \le a, C \le 1\,000\,000).

Output

For each test case, print on a single line the smallest nn such that T(n)+CT(n) + C is divisible by 10P10^P. If no such nn exists, print -1 instead.

Examples1

  1. Example 1

    Input
    4
    4 1 1 1 2 1 5
    4 1 100 1 100 1 6
    3 1 1 2 2 2 11
    1 2 2 1 1 3 2
    
    Expected output
    1
    0
    2
    -1