Let . If , then itself is palindromic, so we can output it directly. Assume from now on.
Construct coefficient arrays and , and define
Start with
For , perform the following assignments in order, all modulo :
Each iteration fixes the two outer coefficients of and then the next two outer coefficients of . After the loop, for all , so is palindromic, and also holds. Substituting the assignments coefficient by coefficient gives
If , output only . If and , then , so has degree and is itself palindromic. In this case output .
The remaining case is and . Let be the smallest index with . By symmetry, the first and last coefficients of are all zero and . Define
Then is a nonzero palindromic polynomial and
Now define
Since is palindromic of degree , the coefficients of are symmetric around degree , so is palindromic as well. The polynomial is also palindromic, and
Therefore
which uses at most three palindromic polynomials.
The leading coefficient of is . In the two-polynomial case, the leading coefficient of is . In the last case, the construction also gives nonzero leading coefficients for , , and . Hence every printed polynomial satisfies the definition in the statement.
Every coefficient is processed only a constant number of times, so the time complexity for one test case is and the extra memory usage is . Over the whole input, the time complexity is . Only addition and subtraction are used, so does not need to be prime.
Solution written by GPT5.6