Common Polynomial
Time limit1sMemory limit128 MB
Parse two polynomial expressions with parentheses and exponents, expand them, then compute and print the normalized greatest common divisor polynomial.
- Level
Medium7 of 10
- Topics
- Math, Recursion, Implementation
- Solved
- No attempts yet
Problem
Among polynomials in a single variable , one whose coefficients are all integers is called an integer polynomial.
Given two integer polynomials and , an integer polynomial is called a common divisor of and if there exist integer polynomials and such that and .
The greatest common divisor of the two polynomials is the common divisor of the highest degree. Ignoring a constant multiple, the greatest common divisor is unique: if both and are greatest common divisors of and , then there exist non-negative integers and with .
Given two integer polynomials and , write a program that computes their greatest common divisor.
Input
The first line contains the number of test cases . Each test case consists of two lines, each containing one polynomial. A polynomial is written according to the following rules.
- A primary term is the variable
x, a constant (digits0~9), or an expression enclosed in parentheses. Examples:x,99,(x+1) - A factor is a primary term followed by
^and an exponent (digits). Examples:x^05,1^15,(x+1)^3 - A term is a product of one or more factors. Examples:
4x,(x+1)(x-2),3(x+1)^2 - A polynomial is one or more terms joined by
+or-. The first term may begin with-. Examples:-x+1,3(x+1)^2-x(x-1)^2
When several digits are written together, they form a single constant. That is, 99 means , not .
When every input polynomial is fully expanded, each coefficient is at most and the degree of is at most . Every exponent written after ^ is a non-negative integer. Only data that can be computed with 32-bit integers is given, so a correct computation does not overflow.
Output
For each test case, print the greatest common divisor of the two polynomials in the following format.
c0x^p0±c1x^p1±...±cnx^pn
Each is a positive integer, each is a non-negative integer, and . The greatest common divisor of the coefficients, , is . Each ± between terms is + or - according to the sign of that term's coefficient, and the first term is written without a leading sign.
In addition, follow these rules.
- If is and is not , omit .
- Omit .
- Write as
x.