Expansion and Factoring

Transform expressions between expanded and factored forms for easier manipulation and analysis.

📐

Mathematical Definition

Distributive Law:

a(b+c)=ab+aca(b + c) = ab + ac

Binomial Expansion:

(x+y)n=k=0n(nk)xnkyk(x + y)^n = \sum_{k=0}^{n} \binom{n}{k} x^{n-k} y^k

For small powers: -

(x+y)2=x2+2xy+y2(x + y)^2 = x^2 + 2xy + y^2
-
(x+y)3=x3+3x2y+3xy2+y3(x + y)^3 = x^3 + 3x^2y + 3xy^2 + y^3
-
(xy)2=x22xy+y2(x - y)^2 = x^2 - 2xy + y^2

Special Products: - Difference of Squares: (x+y)(xy)=x2y2(x + y)(x - y) = x^2 - y^2 - Perfect Square Trinomial: (x+y)2=x2+2xy+y2(x + y)^2 = x^2 + 2xy + y^2

Noncommutative Expansion: For matrices (noncommutative):

(A+B)2=A2+AB+BA+B2(4 terms, cannot combine AB and BA)(A + B)^2 = A^2 + AB + BA + B^2 \quad \text{(4 terms, cannot combine } AB \text{ and } BA\text{)}

Code Examples

Simple Products

Expand products of sums

use mathhook::prelude::*;

let x = symbol!(x);

// Expand 2(x + 3)
let expr1 = expr!(2 * (x + 3));
let expanded1 = expr1.expand();
// Result: 2x + 6

// Expand (x + 1)(x + 2)
let expr2 = expr!((x + 1) * (x + 2));
let expanded2 = expr2.expand();
// Result: x² + 3x + 2

// Expand (x + y)(x - y) - difference of squares
let y = symbol!(y);
let expr3 = expr!((x + y) * (x - y));
let expanded3 = expr3.expand();
// Result: x² - y²

Power Expansion

Expand expressions raised to integer powers

use mathhook::prelude::*;

let x = symbol!(x);
let y = symbol!(y);

// Expand (x + 1)^2
let expr1 = expr!((x + 1) ^ 2);
let expanded1 = expr1.expand();
// Result: x² + 2x + 1

// Expand (x + y)^3
let expr2 = expr!((x + y) ^ 3);
let expanded2 = expr2.expand();
// Result: x³ + 3x²y + 3xy² + y³

// Expand (x - 2)^4
let expr3 = expr!((x - 2) ^ 4);
let expanded3 = expr3.expand();
// Result: x⁴ - 8x³ + 24x² - 32x + 16

Noncommutative Matrix Expansion

For matrices, order matters - (A+B)² has 4 terms

use mathhook::prelude::*;

// Create matrix symbols
let A = symbol!(A; matrix);
let B = symbol!(B; matrix);
let C = symbol!(C; matrix);

// Expand (A + B)^2 - preserves noncommutativity
let expr = expr!((A + B) ^ 2);
let expanded = expr.expand();
// Result: A² + AB + BA + B²   (4 terms, NOT A² + 2AB + B²)

// Expand (A + B)(C)
let expr2 = expr!((A + B) * C);
let expanded2 = expr2.expand();
// Result: AC + BC   (order preserved: A*C first, then B*C)

🔗 Related Topics