[Solved] How to convert a math expression into sums of factors programmatically? [closed]


I found the shortest way to do this using Math.NET Symbolics from Math.NET

The key syntax to do so is like this:

SymbolicExpression.Parse("a*(b+c)").Expand().Summands().Select(x => x.Factors());

In it, I expand the expression and then I get the summands. For each of the summands, I get the factors.

To illustrate it better, consider the following expression:

a * (b + c* -d)

The sums of factors will be returned using this code:

var expression = "a*(b+c*-d)";
var sumsOfFactors = SymbolicExpression.Parse(expression)
    .Expand()
    .Summands()
    .Select(x => x.Factors());

var factorsStr = sumsOfFactors.Select(x => string.Join("\t", x));
var sumOfFactorsStr = string.Join("\n", factorsStr);
Console.WriteLine(sumOfFactorsStr);

That prints the sums of factors:

a   b
-1  a   c   d

That is exactly what I was looking for.

solved How to convert a math expression into sums of factors programmatically? [closed]