# Replace small expressions in larger expressions?

How can I replace small expressions in larger expressions?

Simple example

Replace[a^2 + b^2 + 2*a*b + x, (a + b)^2 -> c]

I want to get c + x but the output is a^2 + b^2 + 2*a*b + x.

• Replace does only literal replacements. Try Simplify[a^2 + b^2 + 2*a*b + x, Assumptions -> (a + b)^2 == c] instead. Jan 13, 2021 at 21:40
• An algebraic approach: Last@PolynomialReduce[a^2 + b^2 + 2*a*b + x, {(a + b)^2 - c}, {a, b, c, x}]. (The goal of PolynomialReduce is not replacement, and, while it works here, it may not work in every instance. OTOH, depending on what the general goal is, if there is a more general goal, it may be more appropriate than replacement, since it is a quite common algebraic operation.) With a similar caveat, there's also First@GroebnerBasis[{a^2 + b^2 + 2*a*b + x, (a + b)^2 - c}, {c, x}, {a, b}] Jan 13, 2021 at 23:30

Try this.

First:

s = Solve[(a + b)^2 == c, a][[1, 1]]

(*  a -> -b - Sqrt[c]  *)


second:

a^2 + b^2 + 2*a*b + x /. s // Simplify

(*  c + x   *)


Have fun!

A simple method:

   a^2 + b^2 + 2*a*b + x /. Expand[(a + b)^2 -> c]