# How to factor a polynomial expression with variable coefficients (and imaginary values)

How can I factor terms with variable coefficients?

For example for the expression: $$x^2 + a$$

I know that I can factor this to: $$(x+i\sqrt{a})(x -i\sqrt{a})$$

How do I do this in mathematica?

I would've expected something like Factor[x^2 + a, x] but I don't see anything like this so far.

• Times @@ (x - (x /. Solve[x^2 + a == 0, x])) Commented Dec 31, 2020 at 1:36
• Thanks Bob! Here's the function version of your answer which also seems to work: factorVariable[expression_, var_] := Times @@ (var - (var /. Solve[expression == 0, var])); Commented Dec 31, 2020 at 1:45
• If you write that as an answer I'll accept it (which I think will be helpful for people like me who were googling for it and might not see it in the comments) Commented Dec 31, 2020 at 1:45
• You can answer your own question. Commented Dec 31, 2020 at 1:48
• Okay. I thought it might be a bit rude to do this without asking, but I'll go ahead and do that, thanks. Commented Dec 31, 2020 at 1:51

For my specific answer, @Bob Hanlon answered that it can be done doing:

Times @@ (x - (x /. Solve[x^2 + a == 0, x]))


Writing this up in a more general form as a function:

factorVariable[expression_, var_] :=
Times @@ (var - (var /. Solve[expression == 0, var]));


This appears to work very well!

I think there are no general way to do this.

Factor[x^2 + 1, Extension -> {1, I}]
Factor[x^2 + 2, Extension -> {Sqrt[2], I}]
Factor[x^2 + 3, Extension -> {Sqrt[3], I}]
Factor[x^2 - 1]
Factor[x^2 - 2, Extension -> Sqrt[2]]
Factor[x^4 - 9, Extension -> {Sqrt[3], I}]
Factor[x^4 + 1, Extension -> I]
Factor[x^5 + 1, Extension -> I]

(-I + x) (I + x)
(Sqrt[2] - I x) (Sqrt[2] + I x)
(Sqrt[3] - I x) (Sqrt[3] + I x)
(-1 + x) (1 + x)
-((Sqrt[2] - x) (Sqrt[2] + x))
-((Sqrt[3] - x) (Sqrt[3] - I x) (Sqrt[3] + I x) (Sqrt[3] + x))
(-I + x^2) (I + x^2)
(1 + x) (1 - x + x^2 - x^3 + x^4)