MCPcopy Create free account
hub / github.com/cortex-js/compute-engine / perfectSquareRoot

Function perfectSquareRoot

src/compute-engine/boxed-expression/factor.ts:161–198  ·  view source on GitHub ↗

* The polynomial square root of a single term if it is a perfect square, else * `null` — computed **structurally**, without a general `.simplify()` (which * was ~half of the whole factoring workload). A product is a perfect square iff * every factor is; a power `u^e` iff `e` is a non-negative eve

(term: Expression)

Source from the content-addressed store, hash-verified

159 *
160 * Patterns:
161 * - a² + 2ab + b² → (a+b)²
162 * - a² - 2ab + b² → (a-b)²
163 *
164 * Strategy: Try to extract square roots of each term to find the bases a and b,
165 * then verify the middle term matches ±2ab.
166 *
167 * IMPORTANT: Does not call .simplify() to avoid infinite recursion.
168 */
169export function factorPerfectSquare(expr: Expression): Expression | null {
170 const ce = expr.engine;
171
172 // Must be an Add expression
173 if (!isFunction(expr, 'Add')) return null;
174
175 const terms = expr.ops;
176
177 // Perfect square trinomial must have exactly 3 terms
178 if (terms.length !== 3) return null;
179
180 // A term that draws is not a perfect square of anything: the match reads
181 // the draws of the three terms as one value (`r(t)² + 2r(t) + 1` is not
182 // `(r(t) + 1)²` when `r` has the `random` effect).
183 if (!isMergeable(expr)) return null;
184
185 // Try all permutations: any two terms could be the squares, the third is the cross term
186 // For efficiency, we'll try to identify which terms look like squares
187 for (let i = 0; i < 3; i++) {
188 for (let j = 0; j < 3; j++) {
189 if (i === j) continue;
190
191 // Try terms[i] and terms[j] as the square terms, remaining as cross term
192 const crossIdx = 3 - i - j; // The remaining index
193 const term1 = terms[i];
194 const term2 = terms[j];
195 const crossTerm = terms[crossIdx];
196
197 // Try to extract square roots of term1 and term2
198 const sqrt1 = extractSquareRoot(term1);
199 const sqrt2 = extractSquareRoot(term2);
200
201 if (sqrt1 === null || sqrt2 === null) continue;

Callers 1

extractSquareRootFunction · 0.85

Calls 8

isNumberFunction · 0.90
isFunctionFunction · 0.90
asSmallIntegerFunction · 0.90
hasNonTrivialRadicalFunction · 0.85
isPolynomialFormFunction · 0.85
sqrtMethod · 0.65
functionMethod · 0.65
numberMethod · 0.65

Tested by

no test coverage detected