Let F(x)=βi=0Nβciβxi. If N=0, then F itself is palindromic, so we can output it directly. Assume Nβ₯1 from now on.
Construct coefficient arrays a0β,β―,aNβ and b0β,β―,bNβ1β, and define
g(x)=i=0βNβaiβxi,h(x)=i=0βNβ1βbiβxi.
Start with
a0β=aNβ=cNβ.
For i=0,1,β―,β2Nβ1ββ, perform the following assignments in order, all modulo M:
biβ=ciββaiβ,bNβ1βiβ=biβ,
ai+1β=cNβ1βiββbiβ,aNβ1βiβ=ai+1β.
Each iteration fixes the two outer coefficients of b and then the next two outer coefficients of a. After the loop, aiβ=aNβiβ for all i, so g is palindromic, and biβ=bNβ1βiβ also holds. Substituting the assignments coefficient by coefficient gives
F=g+h.
If h=0, output only g. If hξ =0 and b0βξ =0, then bNβ1β=b0βξ =0, so h has degree Nβ1 and is itself palindromic. In this case output g,h.
The remaining case is hξ =0 and b0β=0. Let k be the smallest index with bkβξ =0. By symmetry, the first and last k coefficients of b are all zero and bNβ1βkβ=bkβξ =0. Define
d=Nβ1β2k,
r(x)=j=0βdβbj+kβxj.
Then r is a nonzero palindromic polynomial and
h=xkr.
Now define
s=r+xkr.
Since r is palindromic of degree d, the coefficients of s are symmetric around degree d+k, so s is palindromic as well. The polynomial βr is also palindromic, and
s+(βr)=xkr=h.
Therefore
F=g+s+(βr),
which uses at most three palindromic polynomials.
The leading coefficient of g is cNβξ =0. In the two-polynomial case, the leading coefficient of h is b0βξ =0. In the last case, the construction also gives nonzero leading coefficients for r, s, and βr. 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 O(N) and the extra memory usage is O(N). Over the whole input, the time complexity is O(β(N+1)). Only addition and subtraction are used, so M does not need to be prime.
Solution written by GPT5.6