The single-variable case is indirect but easy. Let's use the symbolic equations machinery, and create the elements of your problem :
sage: var("a, b, c, f, g, h") # Variables
(a, b, c, f, g, h)
sage: Ex=a*x^2+b*x+c # Square to complete
sage: CS=((f*x+g)^2+h) # (Hypothetical) completed square
We want to solve ∀x,ax2+bx+c=(fx+g)2+h, which is equivalent to
sage: (Ex-CS).expand()==0
-f^2*x^2 - 2*f*g*x + a*x^2 - g^2 + b*x + c - h == 0
A polynomial is zero if and only if all its coefficients are zero. Sage allows us to deduce an equivalent system :
sage: Sys=[u[0]==0 for u in (Ex-CS).coefficients(x)] ; Sys
[-g^2 + c - h == 0, -2*f*g + b == 0, -f^2 + a == 0]
whose solution is trivial :
sage: Sols=solve(Sys, (f, g, h), solution_dict=True) ; Sols
[{f: sqrt(a), g: 1/2*b/sqrt(a), h: -1/4*(b^2 - 4*a*c)/a},
{f: -sqrt(a), g: -1/2*b/sqrt(a), h: -1/4*(b^2 - 4*a*c)/a}
We can check that both solutions check :
sage: [bool(CS.subs(s)==Ex) for s in Sols]
[True, True]
One notes that this squaring problem has two solutions, because the equations are quadratic (or, if you prefer, x2=(−x)2, roughly...)
The multivariate case can be solved in similar ways ; however, the solution is not identical since your expression has only one constant coefficient, whereas you have n squares to complete for n variables. Run :
reset()
NN=3 # Number of variables
var("c") # Constant coefficient set apart
varnames=("a", "b", "c", "f", "g", "h", "y") # Sheer laziness : create sets of "indexed" variables
for u in varnames: exec("%s=var('%s', n=NN)"%(u.upper(), u))
Exs=[A[u]*Y[u]^2+B[u]*Y[u]+C[u] for u in range(NN)] # Original expressions, with artificial constant coefficients !
CSs=[(F[u]*Y[u]+G[u])^2+H[u] for u in range(NN)] # Desired "completed squares".
Sys=flatten([(Exs[u]-CSs[u]).coefficients(Y[u], sparse=False) for u in range(NN)]) # Equations determining F, G, H
Sys+=[sum(C)-c] # ONE equation on the NN artificial constant coefficients and the (single) natural constant coefficient
Sols=solve(Sys, F+G+H+C, solution_dict=True)
Check=[bool(sum(Exs)==sum(CSs).subs(s)) for s in Sols]
The system to solve has 3n+1 (quadratic) equations with 4n unknowns ; there are 2n solutions involving n−1 arbitrary constants (the rxx
quantities in the solutions) ; one notes that this holds in the n=1 case...
There are better ways, using the polynomials machinery, to solve this problem ; there are lazily left to the reader as an exercise...
Another "interesting" problem : what happens if you introduce some xy terms ? (Hint : this is a special case of a very important class of problems...).
HTH,
Univariate case was discussed at https://ask.sagemath.org/question/10062/