Factorial Simplification
Time limit1sMemory limit128 MB
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:
Factorials show up often in combinatorics, since counts the permutations of 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
where the are distinct integers greater than one written in strictly decreasing order (), and every and is a positive integer. Among all such representations Peter wants the one where is as large as possible; among those, the one where is as large as possible; among those, the one where is as large as possible; then ; and so on, until the remaining can no longer be written in this form. Peter does not care about the value of ; he only wants the factorial-product part of the result.
Input
The first line contains two integers and (). The second line contains integers () separated by spaces. The third line contains integers () separated by spaces.
Output
On the first line print a single integer .
- Print if the ratio of the two factorial products is not an integer.
- Print if the ratio is an integer but cannot be represented in the required form.
- Print if the ratio can be represented as described. In that case print more lines; the -th of them contains two integers and separated by a space.