Under construction

Still being built. Things may change

Factorial Simplification

Time limit1sMemory limit128 MB

Summary
Given a ratio of products of factorials, determine if it is an integer and greedily decompose it into a canonical product of factorial powers with maximal bases and exponents in order.
Level

Hard8 of 10

Topics
Math, Number theory, Greedy
Solved
No attempts yet

Problem

Peter is working on a combinatorial problem. After a long derivation he obtained a formula that is a ratio of two products of factorials:

p1! p2!…pn!q1! q2!…qm!\frac{p_1!\,p_2! \dots p_n!}{q_1!\,q_2! \dots q_m!}

Factorials show up often in combinatorics, since n!n! counts the permutations of nn elements.

Peter may have made a mistake, though. He knows the result must be an integer, so he first wants to check that. If it is an integer, he wants to rewrite it as a product of factorials of the form

r1! s1 r2! s2…rk! sk tr_1!^{\,s_1}\, r_2!^{\,s_2} \dots r_k!^{\,s_k}\, t

where the rir_i are distinct integers greater than one written in strictly decreasing order (ri>ri+1>1r_i > r_{i+1} > 1), and every sis_i and tt is a positive integer. Among all such representations Peter wants the one where r1r_1 is as large as possible; among those, the one where s1s_1 is as large as possible; among those, the one where r2r_2 is as large as possible; then s2s_2; and so on, until the remaining tt can no longer be written in this form. Peter does not care about the value of tt; he only wants the factorial-product part of the result.

Input

The first line contains two integers nn and mm (1≤n,m≤10001 \le n, m \le 1000). The second line contains nn integers pip_i (1≤pi≤10 0001 \le p_i \le 10\,000) separated by spaces. The third line contains mm integers qiq_i (1≤qi≤10 0001 \le q_i \le 10\,000) separated by spaces.

Output

On the first line print a single integer kk.

  • Print k=−1k = -1 if the ratio of the two factorial products is not an integer.
  • Print k=0k = 0 if the ratio is an integer but cannot be represented in the required form.
  • Print k>0k > 0 if the ratio can be represented as described. In that case print kk more lines; the ii-th of them contains two integers rir_i and sis_i separated by a space.

Examples4

  1. Example 1

    Input
    4 2
    9 2 2 2
    3 4
    
    Expected output
    2
    7 1
    2 2
    
  2. Example 2

    Input
    1 2
    6
    4 4
    
    Expected output
    -1
    
  3. Example 3

    Input
    1 2
    6
    3 4
    
    Expected output
    0
    
  4. Example 4

    Input
    1 1
    5
    1
    
    Expected output
    1
    5 1