Continued Fraction Arithmetic

No attempts yetTime limit3sMemory limit256 MB

Problem

A simple continued fraction representation of a real number rr is built by splitting rr into its integer part and the reciprocal of what is left, then splitting that reciprocal the same way, and so on. The representation has the form

r=a0+1a1+1a2+1a3+r = a_0 + \cfrac{1}{a_1 + \cfrac{1}{a_2 + \cfrac{1}{a_3 + \cdots}}}

where every aia_i is an integer and a1,a2,a_1, a_2, \ldots are positive. The aia_i are called partial quotients. For 5.4 the partial quotients are a0=5a_0 = 5, a1=2a_1 = 2 and a2=2a_2 = 2.

An irrational number such as 2\sqrt{2} needs infinitely many partial quotients. A rational number has finitely many, and the list is unique once you require the last partial quotient to differ from 1. Two rational numbers are given as continued fractions. Compute their sum, difference, product and quotient, and write each result as a continued fraction.

Input

The input holds several test cases. Each test case takes three lines. The first line has two integers n1n_1 and n2n_2 (1ni91 \le n_i \le 9), the number of partial quotients of the rational numbers r1r_1 and r2r_2. The second line has the n1n_1 partial quotients of r1r_1 and the third line has the n2n_2 partial quotients of r2r_2. Every partial quotient satisfies a010|a_0| \le 10 and 0<ai100 < a_i \le 10 for i1i \ge 1, the last partial quotient of each number is never 1, and r2r_2 is not 0. A line holding two zeros ends the input.

Output

For each test case print a line reading Case k:, where kk is the number of the test case counting from 1. Then print four lines holding the continued fraction representations of r1+r2r_1 + r_2, r1r2r_1 - r_2, r1×r2r_1 \times r_2 and r1/r2r_1 / r_2, in that order. Write the partial quotients of one number on a single line separated by single spaces, and never let the last partial quotient be 1. Every value that appears during the computation fits in a signed 64-bit integer.