@mathzetta/inlinemath 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cas.js CHANGED
@@ -1,2 +1,2 @@
1
- /* Inline Math 0.3.0 — MIT license; includes mathzetta (and @mathzetta/cas, for the CAS) */
2
- import{u as e,v as n,M as t,w as r,x as s,y as o,z as i,A as a,B as u,C as l,G as c,h as f,E as p,F as d,H as h,I as m,j as g,J as v,K as b}from"./chunks/lite-Bo8THzyq.js";import{c as y}from"./chunks/calculate-BGMEvf3f.js";import{a as w}from"./chunks/html-D5QiXGXD.js";const x=new Map,q=-1,k="\\:",$=e=>"string"==typeof e&&e.startsWith(k)&&e.length>2;function S(e){if(!e||!e.symbol)throw new Error("operator needs a symbol");if(!Number.isInteger(e.arity)||e.arity<0&&e.arity!==q)throw new Error(`operator "${e.symbol}" needs an integer arity >= 0, or VARIADIC`);if(e.commutative&&2!==e.arity)throw new Error(`only binary operators can be commutative ("${e.symbol}")`);const n={symbol:e.symbol,arity:e.arity,commutative:!!e.commutative,fold:"function"==typeof e.fold?e.fold:null,label:e.label||e.symbol};return x.set(n.symbol,n),n}const O=Object.freeze({symbol:k,arity:q,commutative:!1,fold:null,label:"function"});function N(e){const n=x.get(e);return n||($(e)?{...O,symbol:e,label:e.slice(2)}:null)}function A(e){return x.has(e)||$(e)}const I=e=>Number.isFinite(e)&&Number.isInteger(e)?e:null,M=e=>Number.isFinite(e)?e:null;!function(){S({symbol:"+",arity:2,commutative:!0,label:"add",fold:(e,n)=>M(e+n)}),S({symbol:"-",arity:2,label:"subtract",fold:(e,n)=>M(e-n)}),S({symbol:"*",arity:2,commutative:!0,label:"multiply",fold:(e,n)=>M(e*n)}),S({symbol:"/",arity:2,label:"divide",fold:(e,n)=>0===n?null:I(e/n)}),S({symbol:"^",arity:2,label:"power",fold:(e,n)=>Number.isInteger(n)&&Math.abs(n)<=64?M(e**n):null}),S({symbol:"neg",arity:1,label:"negate",fold:e=>M(-e)}),S({symbol:"pm",arity:1,label:"plus or minus"}),S({symbol:"±",arity:2,label:"plus or minus"}),S({symbol:"mod",arity:2,label:"modulo",fold:(e,n)=>0===n?null:I((e%n+n)%n)}),S({symbol:"!",arity:1,label:"factorial",fold:e=>Number.isInteger(e)&&e>=0&&e<=18?[...Array(e).keys()].reduce((e,n)=>e*(n+1),1):null}),S({symbol:"_",arity:2,label:"subscript"}),S({symbol:"der",arity:2,label:"derivative"}),S({symbol:"int",arity:q,label:"integral"}),S({symbol:"lim",arity:q,label:"limit"}),S({symbol:"\\sumidx",arity:q,label:"sum over an index"}),S({symbol:"\\prodidx",arity:q,label:"product over an index"}),S({symbol:"abs",arity:1,label:"absolute value",fold:e=>M(Math.abs(e))}),S({symbol:"floor",arity:1,label:"floor",fold:e=>M(Math.floor(e))}),S({symbol:"ceil",arity:1,label:"ceiling",fold:e=>M(Math.ceil(e))}),S({symbol:"round",arity:2,label:"round",fold:(e,n)=>Number.isInteger(n)?M(Math.round(e*10**n)/10**n):null}),S({symbol:"fixed",arity:2,label:"fixed",fold:()=>null}),S({symbol:"sqrt",arity:1,label:"square root",fold:e=>I(Math.sqrt(e))}),S({symbol:"root",arity:2,label:"nth root",fold:(e,n)=>I(Math.round(n**(1/e))**e===n?Math.round(n**(1/e)):NaN)});for(const e of["sin","cos","tan","csc","sec","cot","sinh","cosh","tanh","arcsin","arccos","arctan","arcsinh","arccosh","arctanh","ln","loglog","logloglog","expm1"])S({symbol:e,arity:1,label:e});S({symbol:"log",arity:2,label:"log to a base"}),S({symbol:"atan2",arity:2,label:"atan2"}),S({symbol:"perm",arity:2,label:"permutations"}),S({symbol:"comb",arity:2,label:"combinations"}),S({symbol:"random",arity:0,label:"random"});for(const e of["max","min","gcd","mean","sum","prod"])S({symbol:e,arity:q,label:e});for(const e of["()","[]","{}","(]","[)"])S({symbol:e,arity:q,label:"group"});for(const e of["pmatrix","bmatrix","vmatrix"])S({symbol:e,arity:q,label:"matrix"});S({symbol:"det",arity:1,label:"determinant"});for(const e of["=","===","≠","≠=","<",">","≤","≥","∈","∉","∪","∩","≈","≡","→","pmod","&","|","\\xor","\\nand","\\nor"])S({symbol:e,arity:2,label:e});S({symbol:"\\not",arity:1,label:"not"}),S({symbol:"?:",arity:3,label:"if then else"})}();const E="num",T="sym",j="op",Z=Object.freeze([]);class z extends Error{constructor(e){super(e),this.name="ExprError"}}function D(e){if("number"!=typeof e||!Number.isFinite(e))throw new z(`not a finite number: ${e}`);const n=(t=e,Object.is(t,-0)?"0":String(t));var t;return Object.freeze({type:E,token:n,value:e,args:Z,s:n})}function B(e){if("string"!=typeof e||""===e)throw new z("symbol needs a non-empty token");return Object.freeze({type:T,token:e,value:null,args:Z,s:e})}function C(e){const n=/^(-?)0*(\d+?)(?:\.(\d*?)0*)?$/.exec(String(e));if(!n)throw new z(`not an exact decimal: ${e}`);const[,t,r,s=""]=n,o=s?`${r}.${s}`:r,i=/^0(\.0*)?$/.test(o)?"0":t+o;return Object.freeze({type:E,token:i,value:Number(i),args:Z,s:i})}const F=/^-?\d+(\.\d+)?$/;function V(e){const n=String(e);if(F.test(n))return C(n);if(""!==n&&!/\s/.test(n)){const e=Number(n);if(Number.isFinite(e))return D(e)}return B(n)}function R(e,n){const t=N(e);if(!t)throw new z(`unknown operator "${e}"`);if(t.arity!==q&&n.length!==t.arity)throw new z(`"${e}" takes ${t.arity} operand(s), got ${n.length}`);const r=Object.freeze(n.slice()),s=t.arity===q?` ${r.length}`:"",o=`${r.length?r.map(e=>e.s).join(" "):""}${r.length,""}${s} ${e}`.trimStart();return Object.freeze({type:j,op:e,token:e,value:null,args:r,s:o})}const U=e=>e.type===E,P=e=>e.type===j;function W(e){return L(function(e){const n=String(e).trim();return""===n?[]:n.split(/\s+/)}(e))}function L(e){if(!Array.isArray(e))throw new z("fromPostfix needs an array of tokens");if(0===e.length)throw new z("empty expression");const n=[];for(let t=0;t<e.length;t++){const r=String(e[t]);if(A(r)){let e=N(r).arity;if(e===q){const s=n.pop();if(e=s&&s.type===E&&Number.isInteger(s.value)&&s.value>=0?s.value:-1,e<0)throw new z(`"${r}" at position ${t+1} takes any number of operands, so a count must come before it`)}if(n.length<e)throw new z(`"${r}" at position ${t+1} needs ${e} operand(s), only ${n.length} on the stack`);const s=n.splice(n.length-e,e);n.push(R(r,s))}else n.push(V(r))}if(1!==n.length){const t=[...new Set(e.filter(e=>!A(e)))];throw new z(`expression leaves ${n.length} values on the stack; it should leave exactly 1. Read as operands: ${t.join(", ")} — is one of those meant to be an operator?`)}return n[0]}function _(e){if(e.type!==j)return 0;let n=0;for(const t of e.args)n=Math.max(n,_(t));return n+1}function H(e){if(e.type!==j)return 1;let n=1;for(const t of e.args)n+=H(t);return n}function J(e,n=[]){if(e.type!==j)n.push(e.token);else for(const t of e.args)J(t,n);return n}function Q(e){return e.type===E||e.type!==T&&e.args.every(Q)}function Y(e,n="pre",t=[],r=[]){"pre"===n&&r.push({node:e,path:t});for(let s=0;s<e.args.length;s++)Y(e.args[s],n,t.concat(s),r);return"post"===n&&r.push({node:e,path:t}),r}function K(e,n,t){if(0===n.length)return t;const[r,...s]=n,o=e.args.slice();return o[r]=K(o[r],s,t),R(e.op,o)}class G extends Error{constructor(e){super(e),this.name="CasError"}}const X=1e5,ee=e=>e<0n?-e:e,ne=e=>0n===e?0:ee(e).toString(2).length;function te(e,n){for(e=ee(e),n=ee(n);n;)[e,n]=[n,e%n];return e}class re{constructor(e,n=1n){if(0n===n)throw new G("division by zero");n<0n&&(e=-e,n=-n);const t=te(e,n)||1n;if(this.n=e/t,this.d=n/t,ne(this.n)>X||ne(this.d)>X)throw new G("a number too large to keep exactly")}static of(e){return new re(BigInt(e))}add(e){return new re(this.n*e.d+e.n*this.d,this.d*e.d)}sub(e){return new re(this.n*e.d-e.n*this.d,this.d*e.d)}mul(e){return new re(this.n*e.n,this.d*e.d)}div(e){if(0n===e.n)throw new G("division by zero");return new re(this.n*e.d,this.d*e.n)}neg(){return new re(-this.n,this.d)}abs(){return this.n<0n?this.neg():this}inv(){return re.ONE.div(this)}pow(e){if((e=BigInt(e))<0n)return this.inv().pow(-e);if((0n===this.n||1n===ee(this.n))&&1n===this.d)return 0n===e||-1n===this.n&&e%2n==0n?re.ONE:this;if(BigInt(Math.max(ne(this.n),ne(this.d)))*e>BigInt(X))throw new G("a power too large to work out exactly");return new re(this.n**e,this.d**e)}get isZero(){return 0n===this.n}get isOne(){return 1n===this.n&&1n===this.d}get isInteger(){return 1n===this.d}get sign(){return this.n<0n?-1:this.n>0n?1:0}equals(e){return this.n===e.n&&this.d===e.d}compare(e){const n=this.n*e.d,t=e.n*this.d;return n<t?-1:n>t?1:0}floor(){const e=this.n/this.d;return new re(this.n<0n&&e*this.d!==this.n?e-1n:e)}ceil(){return this.neg().floor().neg()}toNumber(){const e=Number(this.n),n=Number(this.d);if(Number.isFinite(e)&&Number.isFinite(n))return e/n;const t=BigInt(Math.max(ne(this.n),ne(this.d))-1e3);return Number(this.n>>t)/Number(this.d>>t)}toString(){return 1n===this.d?String(this.n):`${this.n}/${this.d}`}}function se(e){const n=/^(-?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(String(e));if(!n||""===n[2]&&!n[3])return null;const[,t,r,s="",o="0"]=n;let i=new re(BigInt((r||"0")+s),10n**BigInt(s.length));const a=Number(o);return a&&(i=i.mul(re.of(10).pow(a))),t?i.neg():i}function oe(e,n){if(e<2n)return e;if(n>=ne(e))return 1n;const t=BigInt(n);let r=1n<<BigInt(Math.ceil(ne(e)/n));for(;;){const n=((t-1n)*r+e/r**(t-1n))/t;if(n>=r)break;r=n}for(;r**t>e;)r--;for(;(r+1n)**t<=e;)r++;return r}re.ZERO=new re(0n),re.ONE=new re(1n),re.MINUS_ONE=new re(-1n),re.HALF=new re(1n,2n);const ie=(()=>{const e=[],n=new Uint8Array(1e4);for(let t=2;t<n.length;t++)if(!n[t]){e.push(BigInt(t));for(let e=t*t;e<n.length;e+=t)n[e]=1}return e})();function ae(e,n){const t=BigInt(n);let r=1n,s=1n,o=e;for(const e of ie){if(e*e>o)break;if(o%e)continue;let n=0n;for(;o%e===0n;)o/=e,n++;r*=e**(n/t),s*=e**(n%t)}if(o>1n){const e=function(e,n){if(e<0n)return null;if(e<2n)return e;const t=oe(e,n);return t**BigInt(n)===e?t:null}(o,n);null!==e?r*=e:s*=o}return{outside:r,inside:s}}const ue=new Set(["pi","e","π"]),le={complex:!1};function ce(e,n){const t=le.complex;le.complex=Boolean(e);try{return n()}finally{le.complex=t}}const fe=e=>ue.has(e)||le.complex&&"i"===e,pe=e=>le.complex&&"atom"===e.k&&"sym"===e.node.type&&"i"===e.node.token,de=e=>({k:"num",q:e}),he=de(re.ONE),me=de(re.ZERO),ge=de(re.HALF),ve=e=>"num"===e.k,be=e=>({k:"atom",node:e}),ye=new WeakMap;function we(e){let n=ye.get(e);return void 0===n&&ye.set(e,n=Ge(e).s),n}function xe(e){if("num"===e.k)return 0;if("atom"===e.k)return"sym"===e.node.type&&fe(e.node.token)?0:1;if("add"===e.k)return Math.max(...e.terms.map(e=>xe(e.x)));let n=0;for(const t of e.fs){const e=xe(t.b);e&&(n+=e*(ve(t.e)?t.e.q.toNumber():1))}return n}function qe(e,n){return"num"===e.k?n&&!ve(n)?3:0:pe(e)?1.5:"atom"===e.k&&"sym"===e.node.type?fe(e.node.token)?n&&!ve(n)?3:1:2:"atom"===e.k?3:4}const ke=(e,n)=>e<n?-1:e>n?1:0;function $e(e){const n=new Map,t=(e,t)=>{"atom"!==e.k||"sym"!==e.node.type||fe(e.node.token)||n.set(e.node.token,(n.get(e.node.token)??0)+t)};if("mul"===e.k)for(const n of e.fs)t(n.b,ve(n.e)?n.e.q.toNumber():1);else t(e,1);return n}function Se(e,n){const t=xe(n.x)-xe(e.x);if(t)return t;const r=$e(e.x),s=$e(n.x);for(const e of[...new Set([...r.keys(),...s.keys()])].sort()){const n=(s.get(e)??0)-(r.get(e)??0);if(n)return n}return ke(we(e.x),we(n.x))}function Oe(e,n){return e.isOne?n:e.isZero?me:Me([de(e),n])}function Ne(e){if("num"===e.k)return{coef:e.q,rest:null};if("mul"!==e.k||e.c.isOne)return{coef:re.ONE,rest:e};const n=1===e.fs.length&&ve(e.fs[0].e)&&e.fs[0].e.q.isOne?e.fs[0].b:{k:"mul",c:re.ONE,fs:e.fs};return{coef:e.c,rest:n}}function Ae(e){let n=re.ZERO;const t=new Map,r=(e,n)=>{const r=we(n),s=t.get(r);s?s.coef=s.coef.add(e):t.set(r,{coef:e,x:n})};for(const t of e)if("num"===t.k)n=n.add(t.q);else if("add"===t.k){n=n.add(t.c);for(const e of t.terms)r(e.coef,e.x)}else{const{coef:e,rest:n}=Ne(t);r(e,n)}const s=[...t.values()].filter(e=>!e.coef.isZero);return s.length?n.isZero&&1===s.length?Oe(s[0].coef,s[0].x):(s.sort(Se),{k:"add",c:n,terms:s}):de(n)}function Ie(e,n){if(!ve(n))return e.isOne?{coef:re.ONE,fs:[]}:{coef:re.ONE,fs:[{b:de(e),e:n}]};const t=n.q;if(t.isInteger)return{coef:e.pow(t.n),fs:[]};if(e.isZero){if(t.sign<0)throw new G("division by zero");return{coef:re.ZERO,fs:[]}}if(e.isOne)return{coef:re.ONE,fs:[]};if(e.sign<0){if(t.d%2n==1n){const{coef:r,fs:s}=Ie(e.neg(),n);return{coef:t.n%2n==0n?r:r.neg(),fs:s}}if(le.complex&&2n===t.d){const{coef:r,fs:s}=Ie(e.neg(),n);return{coef:r,fs:[...s,{b:je,e:de(new re(t.n))}]}}return{coef:re.ONE,fs:[{b:de(e),e:n}]}}if(!e.isInteger){const r=Ie(new re(e.n),n),s=Ie(new re(e.d),de(t.neg()));return{coef:r.coef.mul(s.coef),fs:[...r.fs,...s.fs]}}const r=t.floor(),s=t.sub(r);if(BigInt(ne(e.n))*s.n>BigInt(X)||s.d>1000n)return{coef:re.ONE,fs:[{b:de(e),e:n}]};let o=r.isZero?re.ONE:e.pow(r.n);const{outside:i,inside:a}=ae(e.n**s.n,Number(s.d));o=o.mul(new re(i));return{coef:o,fs:a>1n?[{b:de(new re(a)),e:de(new re(1n,s.d))}]:[]}}function Me(e){let n=re.ONE;const t=new Map,r=(e,n)=>{const r=we(e),s=t.get(r);s?s.e=Ae([s.e,n]):t.set(r,{b:e,e:n})};for(const t of e)if("num"===t.k)n=n.mul(t.q);else if("mul"===t.k){n=n.mul(t.c);for(const e of t.fs)r(e.b,e.e)}else r(t,he);if(n.isZero)return me;const s=[],o=new Map;for(const e of t.values())if(!ve(e.e)||!e.e.q.isZero){if("num"===e.b.k){if(ve(e.e)&&!e.e.q.isInteger&&e.b.q.sign>0&&e.b.q.isInteger){const n=e.e.q.toString(),t=o.get(n);t?t.n*=e.b.q.n:o.set(n,{n:e.b.q.n,e:e.e});continue}const t=Ie(e.b.q,e.e);n=n.mul(t.coef),s.push(...t.fs);continue}if("mul"===e.b.k&&ve(e.e)&&e.e.q.isInteger){const t=Ee(e.b,e.e);"mul"===t.k?(n=n.mul(t.c),s.push(...t.fs)):"num"===t.k?n=n.mul(t.q):s.push({b:t,e:he});continue}s.push(e)}for(const{n:e,e:t}of o.values()){const r=Ie(new re(e),t);n=n.mul(r.coef),s.push(...r.fs)}if(n.isZero)return me;const i=new Map;for(const e of s){const n=we(e.b),t=i.get(n);t?t.e=Ae([t.e,e.e]):i.set(n,{...e})}let a=[...i.values()].filter(e=>!(ve(e.e)&&e.e.q.isZero));if(le.complex){a=a.flatMap(e=>{if(!pe(e.b)||!ve(e.e)||!e.e.q.isInteger)return[e];const t=(e.e.q.n%4n+4n)%4n;return t>=2n&&(n=n.neg()),t%2n?[{b:e.b,e:he}]:[]});const e=a.filter(e=>"add"===e.b.k&&ve(e.e)&&e.e.q.isInteger&&ze(e.b)),t=a.some(e=>pe(e.b)),r=e.every(e=>(e.e.q.sign<0?-e.e.q.n:e.e.q.n)<=60n);if(e.length&&r&&(e.length>1||t||!e[0].e.q.isOne)){const r=a.filter(n=>!e.includes(n)&&!pe(n.b));let s=t?[je]:[he];for(const n of e){const e=n.e.q.sign<0?Ce(n.b):n.b;for(let t=0n;t<(n.e.q.sign<0?-n.e.q.n:n.e.q.n);t++)s=De(s,tn(e))}return Me([de(n),Ae(s),...r.map(e=>Te(e.b,e.e))])}}if(a.some(e=>"num"===e.b.k&&ve(e.e)&&e.e.q.compare(re.ONE)>=0))return Me([de(n),...a.map(e=>"num"===e.b.k?Ee(e.b,e.e):{k:"mul",c:re.ONE,fs:[e]})]);if(!a.length)return de(n);if(1===a.length&&!n.isOne&&"add"===a[0].b.k&&ve(a[0].e)&&a[0].e.q.isOne){const e=a[0].b;return Ae([de(n.mul(e.c)),...e.terms.map(e=>Oe(n.mul(e.coef),e.x))])}return n.isOne&&1===a.length&&ve(a[0].e)&&a[0].e.q.isOne?a[0].b:(a=a.sort((e,n)=>qe(e.b,e.e)-qe(n.b,n.e)||ke(we(e.b),we(n.b))),{k:"mul",c:n,fs:a})}function Ee(e,n){if(le.complex&&ve(n)&&n.q.isInteger){if(pe(e))return Me([{k:"mul",c:re.ONE,fs:[{b:e,e:n}]}]);if("add"===e.k&&ze(e)&&!n.q.isOne)return Me([{k:"mul",c:re.ONE,fs:[{b:e,e:n}]}])}if(ve(n)){if(n.q.isZero){if(ve(e)&&e.q.isZero)throw new G("0^0 is undefined");return he}if(n.q.isOne)return e}if(ve(e)){const t=Ie(e.q,n);if(!t.fs.length)return de(t.coef);if(t.fs.some(e=>pe(e.b)))return Me([de(t.coef),...t.fs.map(e=>({k:"mul",c:re.ONE,fs:[e]}))]);const r={k:"mul",c:t.coef,fs:t.fs};return t.coef.isOne&&1===t.fs.length&&ve(t.fs[0].e)&&t.fs[0].e.q.isOne?t.fs[0].b:r}if(le.complex&&ve(n)&&2n===n.q.d&&ze(e)){const t=Be(e);if(t&&ve(t.im)&&!t.im.q.isZero){const e=e=>Ee(e,de(re.of(2))),r=Ee(Ae([e(t.re),e(t.im)]),ge),s=Ee(Me([Ae([r,t.re]),de(re.HALF)]),ge),o=Ee(Me([Ae([r,Re(t.re)]),de(re.HALF)]),ge);return Ee(Ae([s,Me([de(re.of(t.im.q.sign)),o,je])]),de(new re(n.q.n)))}}if("mul"===e.k){if(ve(n)&&n.q.isInteger)return Me([de(e.c.pow(n.q.n)),...e.fs.map(e=>Te(e.b,Me([e.e,n])))]);if(!e.c.isOne&&e.c.sign>0)return Me([Ee(de(e.c),n),Ee({k:"mul",c:re.ONE,fs:e.fs},n)]);if(e.c.isOne&&1===e.fs.length){const[t]=e.fs;if(ve(t.e)&&ve(n)&&1n===t.e.q.n&&t.e.q.d%2n==1n)return Te(t.b,Me([t.e,n]))}}return{k:"mul",c:re.ONE,fs:[{b:e,e:n}]}}function Te(e,n){return ve(n)&&n.q.isZero?he:ve(e)?Ee(e,n):ve(n)&&n.q.isOne?e:{k:"mul",c:re.ONE,fs:[{b:e,e:n}]}}const je=be(B("i")),Ze=e=>le.complex&&Ge(e).s.split(" ").includes("i");function ze(e){return le.complex&&Ze(e)&&0===nn(Ge(e)).size}function De(e,n){const t=[];for(const r of e)for(const e of n)t.push(Me([r,e]));return tn(Ae(t))}function Be(e){const n=[],t=[];for(const r of tn(e)){const{coef:e,rest:s}=Ne(r),o=s?rn(s):[],i=o.filter(e=>pe(e)),a=o.filter(e=>!pe(e));if(a.some(e=>Ze(e)))return null;(i.length?t:n).push(Me([de(e),...a]))}return{re:Ae(n),im:Ae(t)}}function Ce(e){const n=Be(e);if(!n)return Ee(e,de(re.MINUS_ONE));const t=Ae([Ee(n.re,de(re.of(2))),Ee(n.im,de(re.of(2)))]);return Me([Ae([n.re,Me([de(re.MINUS_ONE),n.im,je])]),Ee(t,de(re.MINUS_ONE))])}const Fe={re:([e])=>Be(e)?.re??null,im:([e])=>Be(e)?.im??null,conj:([e])=>{const n=Be(e);return n?Ae([n.re,Me([de(re.MINUS_ONE),n.im,je])]):null},arg:([e])=>{const n=Be(e);return n?Le("atan2",[n.im,n.re]):null},abs:([e])=>{const n=Be(e);return!n||ve(n.im)&&n.im.q.isZero?null:Ee(Ae([Ee(n.re,de(re.of(2))),Ee(n.im,de(re.of(2)))]),ge)}},Ve={Re:"re",re:"re",Im:"im",im:"im",conj:"conj",overline:"conj",bar:"conj",arg:"arg"},Re=e=>Me([de(re.MINUS_ONE),e]),Ue=(e,n)=>Me([e,Ee(n,de(re.MINUS_ONE))]),Pe=3000n,We={abs:([e])=>ve(e)?de(e.q.abs()):"mul"!==e.k||e.c.isOne?null:Me([de(e.c.abs()),Le("abs",[Ne(e).rest])]),floor:([e])=>ve(e)?de(e.q.floor()):null,ceil:([e])=>ve(e)?de(e.q.ceil()):null,"!":([e])=>{if(!ve(e)||!e.q.isInteger||e.q.sign<0||e.q.n>Pe)return null;let n=1n;for(let t=2n;t<=e.q.n;t++)n*=t;return de(new re(n))},mod:([e,n])=>ve(e)&&ve(n)&&!n.q.isZero?de(e.q.sub(n.q.mul(e.q.div(n.q).floor()))):null,max:e=>e.every(ve)&&e.length?e.reduce((e,n)=>n.q.compare(e.q)>0?n:e):null,min:e=>e.every(ve)&&e.length?e.reduce((e,n)=>n.q.compare(e.q)<0?n:e):null,gcd:e=>e.length&&e.every(e=>ve(e)&&e.q.isInteger)?de(new re(e.reduce((e,n)=>te(e,n.q.n),0n))):null,log:([e,n])=>{if(!ve(e)||!ve(n)||e.q.sign<=0||n.q.sign<=0||e.q.isOne)return null;if(n.q.isOne)return me;const t=Math.log(n.q.toNumber())/Math.log(e.q.toNumber());if(!Number.isFinite(t))return null;for(let r=1;r<=12;r++){const s=Math.round(t*r);if(!(Math.abs(t*r-s)>1e-9||0===s)&&(Math.abs(s)<=256&&e.q.pow(BigInt(s)).equals(n.q.pow(BigInt(r)))))return de(new re(BigInt(s),BigInt(r)))}return null},comb:([e,n])=>ve(e)&&ve(n)&&e.q.isInteger&&n.q.isInteger&&e.q.sign>=0&&n.q.sign>=0&&e.q.n<=Pe?de(function(e,n){if(n>e)return re.ZERO;n>e-n&&(n=e-n);let t=1n;for(let r=1n;r<=n;r++)t=t*(e-n+r)/r;return new re(t)}(e.q.n,n.q.n)):null,perm:([e,n])=>{if(!(ve(e)&&ve(n)&&e.q.isInteger&&n.q.isInteger&&e.q.sign>=0&&n.q.sign>=0&&e.q.n<=Pe))return null;if(n.q.n>e.q.n)return me;let t=1n;for(let r=0n;r<n.q.n;r++)t*=e.q.n-r;return de(new re(t))}};function Le(e,n){if(le.complex&&Fe[e]){const t=Fe[e](n);if(t)return t}const t=We[e];if(t){const e=t(n);if(e)return e}return be(R(e,n.map(Ge)))}const _e=new Map;function He(e){const n=le.complex?`ℂ ${e.s}`:e.s,t=_e.get(n);if(t)return t;const r=function(e){if("num"===e.type){const n=se(e.token);if(!n)throw new G(`not an exact number: ${e.token}`);return de(n)}if("sym"===e.type)return"π"===e.token?be(B("pi")):be(e);const n=e.args.map(He);switch(e.op){case"+":return Ae(n);case"-":return((e,n)=>Ae([e,Re(n)]))(n[0],n[1]);case"neg":return Re(n[0]);case"*":return Me(n);case"/":return Ue(n[0],n[1]);case"^":return Ee(n[0],n[1]);case"sqrt":return Ee(n[0],ge);case"root":return Ee(n[1],Ee(n[0],de(re.MINUS_ONE)));default:{const t=e.op.startsWith("\\:")?e.op.slice(2):null;return t&&le.complex&&Ve[t]&&1===n.length?Le(Ve[t],n):t&&A(t)&&N(t).arity===n.length?Le(t,n):Le(e.op,n)}}}(e);return _e.size>2e4&&_e.clear(),_e.set(n,r),r}const Je=e=>Ge(He(e)),Qe=e=>C(String(e));function Ye(e){return e.isInteger?Qe(e.n):R("/",[Qe(e.n),Qe(e.d)])}const Ke=new WeakMap;function Ge(e){let n=Ke.get(e);return n||Ke.set(e,n=function(e){switch(e.k){case"num":return Ye(e.q);case"atom":return e.node;case"mul":return function(e,n){const t=[],r=[];for(const e of n)ve(e.e)&&e.e.q.sign<0?r.push(Xe(e.b,de(e.e.q.neg()))):t.push(Xe(e.b,e.e));let s=1n!==e.n&&-1n!==e.n||!t.length?en([Qe(e.n),...t]):en(t);-1n===e.n&&t.length&&(s=R("neg",[s]));1n!==e.d&&r.unshift(Qe(e.d));return r.length?R("/",[s,en(r)]):s}(e.c,e.fs);case"add":return function(e){let n=null;const t=e=>le.complex&&Ze(e.x)&&0===nn(Ge(e.x)).size,r=[...e.terms.filter(e=>!t(e)),...e.terms.filter(t)],s=e.c,o=()=>{s.isZero||(n=n?s.sign<0?R("-",[n,Ye(s.neg())]):R("+",[n,Ye(s)]):Ye(s))};let i=!1;for(const e of r)!i&&t(e)&&(o(),i=!0),n=n?e.coef.sign<0?R("-",[n,Ge(Oe(e.coef.neg(),e.x))]):R("+",[n,Ge(Oe(e.coef,e.x))]):Ge(Oe(e.coef,e.x));i||o();return n}(e);default:throw new Error(`bad form ${e.k}`)}}(e)),n}function Xe(e,n){const t=Ge(e);if(ve(n)){const e=n.q;if(e.isOne)return t;if(1n===e.n&&2n===e.d)return R("sqrt",[t]);if(1n===e.n)return R("root",[Qe(e.d),t])}return R("^",[t,Ge(n)])}const en=e=>e.reduce((e,n)=>e?R("*",[e,n]):n,null);function nn(e,n=new Set){if("sym"===e.type)fe(e.token)||n.add(e.token);else if(P(e))for(const t of e.args)nn(t,n);return n}function tn(e){if("add"!==e.k)return[e];const n=e.terms.map(e=>Oe(e.coef,e.x));return e.c.isZero||n.push(de(e.c)),n}function rn(e){if("num"===e.k)return[e];if("mul"!==e.k)return[e];const n=e.c.isOne?[]:[de(e.c)];for(const t of e.fs)n.push(Te(t.b,t.e));return n}const sn="_",on=new WeakMap;function an(e,n){return[...n,...N(e.op)?.arity===q?[String(e.args.length)]:[],e.op].join(" ")}function un(e,n){let t=on.get(e);t||on.set(e,t=new Map);const r=t.get(n);if(r)return r;const s=function(e,n){const t={key:sn,slots:[e]};if(e.type!==j||n<=0)return[t];const r=e.args.map(e=>un(e,n-1)),s=[t],o=new Array(r.length).fill(0);for(;;){const n=[],t=[];for(let e=0;e<r.length;e++){const s=r[e][o[e]];n.push(s.key);for(const e of s.slots)t.push(e)}if(s.push({key:an(e,n),slots:t}),s.length>=4096)break;let i=r.length-1;for(;i>=0&&!(++o[i]<r[i].length);i--)o[i]=0;if(i<0)break}return s}(e,n);return t.set(n,s),s}function ln(e){return e.type!==j?sn:an(e,e.args.map(ln))}function cn(e,n=[]){if(e.type!==j)n.push(e);else for(const t of e.args)cn(t,n);return n}const fn=new Map,pn=new Map;class dn extends Error{constructor(e){super(e),this.name="RequirementError"}}function hn(e,n,t=""){fn.set(e,{name:e,fn:n,doc:t,arity:Math.max(0,n.length-1)})}function mn(e,n,t=""){pn.set(e,{name:e,fn:n,doc:t})}function gn(e){return fn.get(e)||null}function vn(e){return pn.get(e)||null}const bn=e=>e.type===E;function yn(e,n){return e.type===j&&(e.op===n||e.args.some(e=>yn(e,n)))}hn("always",()=>!0,"matches anything"),hn("never",()=>!1,"matches nothing"),hn("isLeaf",e=>e.type!==j,"a bare operand, not an operation"),hn("isCompound",e=>e.type===j,"an operation, not a bare operand"),hn("isSymbol",e=>e.type===T,"a non-numeric operand such as x"),hn("isOperation",(e,n)=>e.type===j&&e.op===n,"is this specific operation"),hn("notOperation",(e,n)=>!(e.type===j&&e.op===n),"is anything except this operation"),hn("isNumber",bn,"a numeric literal"),hn("isInteger",e=>bn(e)&&Number.isInteger(e.value),"a whole number"),hn("isPositive",e=>bn(e)&&e.value>0,"greater than zero"),hn("isNegative",e=>bn(e)&&e.value<0,"less than zero"),hn("isNonNegative",e=>bn(e)&&e.value>=0,"zero or greater"),hn("isZero",e=>bn(e)&&0===e.value,"exactly 0"),hn("isOne",e=>bn(e)&&1===e.value,"exactly 1"),hn("isNonZero",e=>bn(e)&&0!==e.value,"a number that is provably not 0"),hn("isNotZeroLiteral",e=>!(bn(e)&&0===e.value),"anything except a literal 0"),hn("isPositiveInteger",e=>bn(e)&&Number.isInteger(e.value)&&e.value>0,"a whole number above 0"),hn("isNegativeInteger",e=>bn(e)&&Number.isInteger(e.value)&&e.value<0,"a whole number below 0"),hn("isEven",e=>bn(e)&&Number.isInteger(e.value)&&e.value%2==0,"a whole even number"),hn("isOdd",e=>bn(e)&&Number.isInteger(e.value)&&1===Math.abs(e.value%2),"a whole odd number"),hn("greaterThan",(e,n)=>bn(e)&&e.value>Number(n),"above a given value"),hn("lessThan",(e,n)=>bn(e)&&e.value<Number(n),"below a given value"),hn("isValue",(e,n)=>bn(e)&&e.value===Number(n),"equals a given number"),hn("isNumeric",Q,"contains no symbols: a constant (it need not fold to a number: 1 sin)"),hn("hasSymbol",e=>!Q(e),"mentions a symbol somewhere, so it is not just a number"),hn("isVar",(e,n)=>e.type===T&&e.token===String(n),"is exactly this symbol"),hn("contains",(e,n)=>J(e).includes(String(n)),"mentions this operand somewhere"),hn("isFree",(e,n)=>!J(e).includes(String(n)),"never mentions this operand"),hn("hasOperation",(e,n)=>yn(e,String(n)),"uses this operation somewhere inside"),hn("equals",(e,n)=>e.s===String(n),"is exactly this postfix expression");const wn=e=>e.type===j?null:e.token;function xn(e){if("string"==typeof e)return{name:e,args:[]};if(Array.isArray(e)&&e.length>0&&"string"==typeof e[0])return{name:e[0],args:e.slice(1)};throw new dn(`bad requirement: ${JSON.stringify(e)}`)}mn("freeOf",(e,n)=>{const t=wn(n);return null!==t&&!J(e).includes(t)},"the first operand never mentions the second"),mn("dependsOn",(e,n)=>{const t=wn(n);return null!==t&&J(e).includes(t)},"the first operand does mention the second"),mn("sameAs",(...e)=>e.every(n=>n.s===e[0].s),"these operands are structurally identical"),mn("differs",(...e)=>new Set(e.map(e=>e.s)).size===e.length,"these operands are all different"),mn("sameValue",(...e)=>e.every(e=>bn(e))&&e.every(n=>n.value===e[0].value),"these operands are the same number");const qn="simplify";class kn extends Error{constructor(e,n){super(n?`rule "${n}": ${e}`:e),this.name="RuleError",this.ruleId=n}}const $n=/^[A-Za-z_][A-Za-z0-9_]*$/;function Sn(e,n){if(U(e))return{literal:e.value};const t=e.token;if(t.startsWith("=")){const e=t.slice(1);if(""===e)throw new kn('"=" needs an operand after it',n);return{token:e}}if(!$n.test(t))throw new kn(`"${t}" is not a usable slot name; use letters, digits and _`,n);if(A(t))throw new kn(`slot name "${t}" collides with an operator`,n);return{name:t}}function On(e){if(!P(e))return[e];const n=e.args.map(On),t=N(e.op),r=[];for(const s of function(e){let n=[[]];for(const t of e){const e=[];for(const r of n)for(const n of t)e.push(r.concat([n]));if(n=e,n.length>64)return n.slice(0,64)}return n}(n))if(r.push(R(e.op,s)),t.commutative&&2===s.length&&s[0].s!==s[1].s&&r.push(R(e.op,[s[1],s[0]])),r.length>=64)break;return r}function Nn(e,n=[]){return"op"===e.kind?e.args.forEach(e=>Nn(e,n)):"const"===e.kind&&e.free&&n.push(e.node.token),n}function An(e){if(!e||"object"!=typeof e)throw new kn("rule must be a mapping");const n=e.id||e.name;if(!n)throw new kn("rule needs an id");if(!e.pattern)throw new kn("rule needs a pattern",n);if(void 0===e.output||null===e.output)throw new kn("rule needs an output",n);let t;try{t=W(String(e.pattern))}catch(e){if(e instanceof z)throw new kn(`bad pattern: ${e.message}`,n);throw e}const r=cn(t).map(e=>Sn(e,n)),s=new Set(r.filter(e=>e.name).map(e=>e.name)),o=function(e,n,t){const r=[],s=e.when||{};if("object"!=typeof s||Array.isArray(s))throw new kn('"when" must map slot names to lists of requirements',t);for(const[e,o]of Object.entries(s)){if(!n.has(e))throw new kn(`"when" mentions "${e}", which is not a slot in the pattern`,t);const s=Array.isArray(o)?o:[o];for(const n of s){const{name:s,args:o}=xn(n),i=gn(s);if(!i)throw new kn(`unknown requirement "${s}"`,t);r.push({slot:e,name:s,args:o,fn:i.fn})}}return r}(e,s,n),i=function(e,n,t){const r=[],s=e.require||[];if(!Array.isArray(s))throw new kn('"require" must be a list of relations',t);for(const e of s){const{name:s,args:o}=xn(e),i=vn(s);if(!i)throw new kn(`unknown relation "${s}"`,t);if(o.length<2)throw new kn(`relation "${s}" needs at least two operands`,t);for(const e of o)if("string"==typeof e&&!n.has(e)&&$n.test(e))throw new kn(`relation "${s}" mentions "${e}", which is not a slot in the pattern`,t);r.push({name:s,args:o,fn:i.fn})}return r}(e,s,n),a=function(e,n,t){let r;try{r=W(e)}catch(n){throw new kn(`bad output "${e}": ${n.message}`,t)}const s=e=>P(e)?{kind:"op",op:e.op,args:e.args.map(s)}:U(e)?{kind:"const",node:e}:n.has(e.token)?{kind:"slot",name:e.token}:e.token.startsWith("=")?{kind:"const",node:B(e.token.slice(1))}:{kind:"const",node:e,free:!0};return s(r)}(String(e.output),s,n),u=e.commutative?On(t):[t],l=[],c=new Set;for(const e of u){const t=ln(e),r=cn(e).map(e=>Sn(e,n)),s=t+"\0"+r.map(e=>e.name??(void 0!==e.literal?`#${e.literal}`:`=${e.token}`)).join(",");c.has(s)||(c.add(s),l.push({key:t,slots:r}))}const f={id:String(n),name:e.name?String(e.name):String(n),pattern:String(e.pattern),patternTree:t,output:String(e.output),outputTemplate:a,explain:e.explain?String(e.explain).trim():"",mode:e.mode?String(e.mode):qn,tags:Array.isArray(e.tags)?e.tags.map(String):[],priority:Number.isFinite(e.priority)?e.priority:0,fold:!!e.fold,commutative:!!e.commutative,enabled:void 0===e.enabled||!!e.enabled,when:o,require:i,slots:[...s],depth:_(t),bindings:l,freeSymbols:Nn(a),source:e};for(const e of l)e.rule=f;return f}function In(e){const n={};for(const t of e.when)(n[t.slot]||=[]).push(t.args.length?[t.name,...t.args]:t.name);const t={id:e.id};return e.name!==e.id&&(t.name=e.name),e.mode!==qn&&(t.mode=e.mode),t.pattern=e.pattern,Object.keys(n).length&&(t.when=n),e.require.length&&(t.require=e.require.map(e=>[e.name,...e.args])),t.output=e.output,e.explain&&(t.explain=e.explain),e.fold&&(t.fold=!0),e.commutative&&(t.commutative=!0),e.priority&&(t.priority=e.priority),e.tags.length&&(t.tags=e.tags),e.enabled||(t.enabled=!1),t}class Mn extends Error{constructor(e,n){super(null==n?e:`${e} (line ${n+1})`),this.name="YamlError",this.line=n}}class En{constructor(e){this.records=e,this.i=0,this.pushed=[]}peek(){if(this.pushed.length)return this.pushed[this.pushed.length-1];for(;this.i<this.records.length&&this.records[this.i].blank;)this.i++;return this.i<this.records.length?this.records[this.i]:null}next(){if(this.pushed.length)return this.pushed.pop();const e=this.peek();return e&&this.i++,e}push(e){this.pushed.push(e)}}const Tn=e=>"-"===e||e.startsWith("- ");function jn(e){let n=null,t=0;for(let r=0;r<e.length;r++){const s=e[r];if(n)s===n?"'"===n&&"'"===e[r+1]?r++:n=null:'"'===n&&"\\"===s&&r++;else if('"'===s||"'"===s)n=s;else if("["===s||"{"===s)t++;else if("]"===s||"}"===s)t--;else if(":"===s&&0===t&&(r+1===e.length||" "===e[r+1])){const n=e.slice(0,r).trim();return""===n?null:{key:Zn(n),rest:e.slice(r+1).trim()}}}return null}function Zn(e){return e.length>=2&&'"'===e[0]&&'"'===e[e.length-1]?JSON.parse(e):e.length>=2&&"'"===e[0]&&"'"===e[e.length-1]?e.slice(1,-1).replace(/''/g,"'"):e}function zn(e){const n=new En(function(e){return String(e).split(/\r?\n/).map((e,n)=>{const t=e.search(/\S/);if(-1===t)return{raw:e,n:n,indent:0,text:"",blank:!0};const r=function(e){let n=null;for(let t=0;t<e.length;t++){const r=e[t];if(n)r===n?"'"===n&&"'"===e[t+1]?t++:n=null:'"'===n&&"\\"===r&&t++;else if('"'===r||"'"===r)n=r;else if("#"===r&&(0===t||/\s/.test(e[t-1])))return e.slice(0,t)}return e}(e.slice(t)).trimEnd();return{raw:e,n:n,indent:t,text:r,blank:""===r}})}(e));let t=n.peek();if(t&&"---"===t.text&&(n.next(),t=n.peek()),!t)return null;const r=Bn(n,t.indent),s=n.peek();if(s&&"..."!==s.text&&"---"!==s.text)throw new Mn(`unexpected content "${s.text}"`,s.n);return r}const Dn=/^[|>][-+]?\d*$/;function Bn(e,n){const t=e.peek();return!t||t.indent<n?null:Tn(t.text)?Cn(e,t.indent):jn(t.text)?function(e,n){const t={};for(;;){const r=e.peek();if(!r||r.indent!==n)break;const s=jn(r.text);if(!s)break;e.next();const{key:o,rest:i}=s;if(""===i){const r=e.peek();r&&r.indent>n?t[o]=Bn(e,r.indent):r&&r.indent===n&&Tn(r.text)?t[o]=Cn(e,n):t[o]=null}else Dn.test(i)?t[o]=Fn(e,i,n):t[o]=Vn(i,r.n)}return t}(e,t.indent):(e.next(),Dn.test(t.text)?Fn(e,t.text,t.indent-1):Vn(t.text,t.n))}function Cn(e,n){const t=[];for(;;){const r=e.peek();if(!r||r.indent!==n||!Tn(r.text))break;if(e.next(),"-"===r.text){const r=e.peek();t.push(r&&r.indent>n?Bn(e,r.indent):null);continue}if(Dn.test(r.text.slice(2).trim())){t.push(Fn(e,r.text.slice(2).trim(),n));continue}const s=r.text.slice(2),o=n+2+(s.length-s.trimStart().length);e.push({raw:r.raw,n:r.n,indent:o,text:s.trim(),blank:!1}),t.push(Bn(e,o))}return t}function Fn(e,n,t){const r=n[0],s=(n.match(/[-+]/)||[""])[0],o=(n.match(/\d+/)||[null])[0];let i=o?t+Number(o):null;const a=[];for(;e.i<e.records.length;){const n=e.records[e.i];if(""===n.raw.trim()){a.push(""),e.i++;continue}const r=n.raw.search(/\S/);if(r<=t)break;if(null===i&&(i=r),r<i)break;a.push(n.raw.slice(i)),e.i++}for(;a.length&&""===a[a.length-1];)a.pop();let u;if("|"===r)u=a.join("\n");else{const e=[];for(const n of a)""===n?e.push("\n"):e.length&&"\n"!==e[e.length-1]?e[e.length-1]+=" "+n:e.push(n);u=e.join("").replace(/\n(?!$)/g,"\n")}return"-"===s?u:"+"===s?u+"\n":""===u?"":u+"\n"}function Vn(e,n){const t=e.trim();return""===t||"~"===t||"null"===t||"Null"===t||"NULL"===t?null:"true"===t||"True"===t||"TRUE"===t||"false"!==t&&"False"!==t&&"FALSE"!==t&&("["===t[0]||"{"===t[0]?function(e,n){const t={text:e,i:0,line:n},r=Un(t);if(Rn(t),t.i<t.text.length)throw new Mn(`unexpected "${t.text.slice(t.i)}" in flow value`,n);return r}(t,n):'"'===t[0]||"'"===t[0]?Zn(t):/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(t)?Number(t):t)}const Rn=e=>{for(;e.i<e.text.length&&/\s/.test(e.text[e.i]);)e.i++};function Un(e){Rn(e);const n=e.text[e.i];return"["===n?function(e){e.i++;const n=[];for(;;){if(Rn(e),e.i>=e.text.length)throw new Mn("unterminated [",e.line);if("]"===e.text[e.i])return e.i++,n;if(n.push(Un(e)),Rn(e),","===e.text[e.i])e.i++;else if("]"!==e.text[e.i])throw new Mn(`expected , or ] near "${e.text.slice(e.i)}"`,e.line)}}(e):"{"===n?function(e){e.i++;const n={};for(;;){if(Rn(e),e.i>=e.text.length)throw new Mn("unterminated {",e.line);if("}"===e.text[e.i])return e.i++,n;const t=String(Un(e));if(Rn(e),":"!==e.text[e.i])throw new Mn(`expected : after "${t}"`,e.line);if(e.i++,n[t]=Un(e),Rn(e),","===e.text[e.i])e.i++;else if("}"!==e.text[e.i])throw new Mn(`expected , or } near "${e.text.slice(e.i)}"`,e.line)}}(e):Vn(function(e){const n=e.text[e.i];if('"'===n||"'"===n){const t=e.i;for(e.i++;e.i<e.text.length;)if("\\"===e.text[e.i]&&'"'===n)e.i+=2;else if(e.text[e.i]===n){if("'"!==n||"'"!==e.text[e.i+1])return e.i++,e.text.slice(t,e.i);e.i+=2}else e.i++;throw new Mn("unterminated quoted string",e.line)}const t=e.i;for(;e.i<e.text.length;){const n=e.text[e.i];if(","===n||"]"===n||"}"===n)break;if(":"===n){const n=e.text[e.i+1];if(void 0===n||/[\s,\]}]/.test(n))break}e.i++}return e.text.slice(t,e.i).trim()}(e),e.line)}const Pn=/^(true|false|null|yes|no|on|off|~)$/i;function Wn(e){if(null==e)return"null";if("boolean"==typeof e)return e?"true":"false";if("number"==typeof e){if(!Number.isFinite(e))throw new Mn(`cannot serialize ${e}`);return String(e)}const n=String(e);return function(e){return!!(""===e||/^\s|\s$/.test(e)||/[\u0000-\u001f\u007f]/.test(e)||/^[-?:,[\]{}#&*!|>'"%@`]/.test(e)||/: |\s#/.test(e)||Pn.test(e)||/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(e))}(n)?JSON.stringify(n):n}const Ln=e=>null==e||"object"!=typeof e;function _n(e){return Array.isArray(e)?`[${e.map(_n).join(", ")}]`:e&&"object"==typeof e?`{${Object.entries(e).map(([e,n])=>`${Wn(e)}: ${_n(n)}`).join(", ")}}`:Wn(e)}function Hn(e){return Array.isArray(e)?!!e.every(e=>Ln(e)||Array.isArray(e)&&e.every(Ln))&&_n(e).length<=72:!(!e||"object"!=typeof e)&&(Object.values(e).every(e=>Ln(e)||Array.isArray(e)&&e.every(Ln))&&_n(e).length<=72)}function Jn(e){const n=[];return Qn(e,0,n),n.length?n.join("\n")+"\n":""}function Qn(e,n,t){const r=" ".repeat(n);if(Array.isArray(e)){if(0===e.length)return void t.push(r+"[]");for(const r of e)Yn(r,n,t)}else{if(e&&"object"==typeof e){const s=Object.entries(e).filter(([,e])=>void 0!==e);if(0===s.length)return void t.push(r+"{}");for(const[e,r]of s)Kn(e,r,n,t);return}!function(e,n,t){if("string"==typeof e&&e.includes("\n")){t.push(n+"|-");for(const r of e.replace(/\n+$/,"").split("\n"))t.push(n+" "+r);return}t.push(n+Wn(e))}(e,r,t)}}function Yn(e,n,t){const r=" ".repeat(n);if(null!==e&&"object"==typeof e&&!Hn(e)){const s=[];if(Qn(e,n+2,s),0===s.length)return void t.push(r+"-");t.push(r+"- "+s[0].slice(n+2));for(let e=1;e<s.length;e++)t.push(s[e]);return}if(null===e||"object"!=typeof e)if("string"==typeof e&&e.includes("\n")){t.push(r+"- |-");for(const r of e.replace(/\n+$/,"").split("\n"))t.push(" ".repeat(n+4)+r)}else t.push(r+"- "+Wn(e));else t.push(r+"- "+_n(e))}function Kn(e,n,t,r){const s=" ".repeat(t),o=Wn(e);if("string"==typeof n&&n.includes("\n")){r.push(`${s}${o}: |-`);for(const e of n.replace(/\n+$/,"").split("\n"))r.push(" ".repeat(t+2)+e)}else{if(null!==n&&"object"==typeof n)return Hn(n)?void r.push(`${s}${o}: ${_n(n)}`):(r.push(`${s}${o}:`),void Qn(n,Array.isArray(n)?t:t+2,r));r.push(`${s}${o}: ${Wn(n)}`)}}class Gn{constructor(e=[]){this.index=new Map,this.rules=[],this.maxDepth=0,this.name="",this.views=new Map;for(const n of e)this.add(n)}add(e){const n=e&&e.bindings?e:An(e);if(this.rules.some(e=>e.id===n.id))throw new kn(`duplicate rule id "${n.id}"`);return this.rules.push(n),n.enabled&&this.link(n),n.depth>this.maxDepth&&(this.maxDepth=n.depth),this.views.clear(),n}view(e){if(!e)return this;let n=this.views.get(e);return n||(n=new Gn(this.rules.filter(n=>n.mode===e)),n.name=this.name,this.views.set(e,n)),n}modes(){return[...new Set(this.rules.map(e=>e.mode))].sort((e,n)=>e===qn?-1:n===qn?1:e.localeCompare(n))}link(e){for(const n of e.bindings){let e=this.index.get(n.key);e||this.index.set(n.key,e=[]),e.push(n),e.sort((e,n)=>n.rule.priority-e.rule.priority||n.rule.depth-e.rule.depth)}}remove(e){const n=this.rules.findIndex(n=>n.id===e);return-1!==n&&(this.rules.splice(n,1),this.reindex(),!0)}setEnabled(e,n){const t=this.get(e);return!!t&&(t.enabled=!!n,this.reindex(),!0)}reindex(){this.index=new Map,this.maxDepth=0,this.views.clear();for(const e of this.rules)e.enabled&&this.link(e),e.depth>this.maxDepth&&(this.maxDepth=e.depth)}get(e){return this.rules.find(n=>n.id===e)||null}candidates(e){return this.index.get(e)||null}get size(){return this.rules.length}static fromYaml(e,{strict:n=!0}={}){const t=zn(e);return Gn.fromSpecs(t,{strict:n})}static fromSpecs(e,{strict:n=!0}={}){let t=e,r="";if(e&&!Array.isArray(e)&&"object"==typeof e&&(t=e.rules,r=e.name?String(e.name):""),!Array.isArray(t))throw new kn('expected a list of rules, or a mapping with a "rules" list');const s=new Gn;s.name=r;const o=[];for(let e=0;e<t.length;e++)try{s.add(t[e])}catch(n){o.push(`#${e+1}: ${n.message}`)}if(o.length&&n)throw new kn(`${o.length} rule(s) failed to compile:\n ${o.join("\n ")}`);return s.errors=o,s}toSpecs(){return this.rules.map(In)}toYaml(){const e=this.toSpecs();return this.name?Jn({name:this.name,rules:e}):Jn(e)}keyReport(){return[...this.index.entries()].map(([e,n])=>({key:e,rules:n.map(e=>e.rule.id)})).sort((e,n)=>e.key.localeCompare(n.key))}}function Xn(e,n){const t=Object.create(null),r=e.slots;for(let e=0;e<r.length;e++){const s=r[e],o=n[e];if(void 0!==s.literal){if(!U(o)||o.value!==s.literal)return null;continue}if(void 0!==s.token){if(o.s!==s.token)return null;continue}const i=t[s.name];if(void 0!==i){if(i.s!==o.s)return null}else t[s.name]=o}return t}function et(e,n){for(const t of e.when){const e=n[t.slot];if(void 0===e)return!1;if(!t.fn(e,...t.args))return!1}for(const t of e.require){const e=t.args.map(e=>void 0!==n[e]?n[e]:e);if(!t.fn(...e))return!1}return!0}function nt(e,n){return n.rule.priority-e.rule.priority||n.rule.depth-e.rule.depth}function tt(e,n){const t=[];if(0===n.maxDepth)return t;for(const{key:r,slots:s}of function(e,n){const t=un(e,n),r=[];for(const e of t)e.key!==sn&&r.push(e);return r}(e,n.maxDepth)){const e=n.candidates(r);if(e)for(const n of e){const e=Xn(n,s);e&&(et(n.rule,e)&&t.push({rule:n.rule,binding:n,key:r,bound:e}))}}return t.sort(nt)}function rt(e,n){switch(e.kind){case"slot":{const t=n[e.name];if(!t)throw new Error(`output references unbound slot "${e.name}"`);return t}case"const":return e.node;case"op":return R(e.op,e.args.map(e=>rt(e,n)));default:throw new Error(`bad output template: ${JSON.stringify(e)}`)}}const st=4e5,ot=()=>new G("a number too large to approximate"),it=e=>e<0n?-e:e;class at{constructor(e){this.P=e,this.S=10n**BigInt(e),this.cache=new Map}fromQ(e){return e.n*this.S/e.d}mul(e,n){return e*n/this.S}div(e,n){if(0n===n)throw new G("division by zero");return e*this.S/n}sqrt(e){if(e<0n)throw new G("the square root of a negative number is not real");return oe(e*this.S,2)}series(e,n){let t=0n,r=e;for(let e=1;0n!==r;e++)if(t+=r,r=n(r,e),e>1e5)throw new G("a series did not converge");return t}atanhInv(e){const n=BigInt(e),t=n*n;let r=this.S/n,s=0n;for(let e=1n;0n!==r;e+=2n)s+=r/e,r/=t;return s}atanInv(e){const n=BigInt(e),t=n*n;let r=this.S/n,s=0n;for(let e=1n,n=1n;0n!==r;e+=2n,n=-n)s+=n*r/e,r/=t;return s}get pi(){return this.memo("pi",()=>16n*this.atanInv(5)-4n*this.atanInv(239))}get ln2(){return this.memo("ln2",()=>2n*this.atanhInv(3))}get e(){return this.memo("e",()=>this.exp(this.S))}memo(e,n){return this.cache.has(e)||this.cache.set(e,n()),this.cache.get(e)}exp(e){const n=(e+(e>=0n?this.ln2/2n:-this.ln2/2n))/this.ln2;if(n>BigInt(st))throw ot();if(n<-BigInt(st))return 0n;const t=e-n*this.ln2,r=this.series(this.S,(e,n)=>e*t/this.S/BigInt(n));return n>=0n?r<<n:r>>-n}ln(e){if(e<=0n)throw new G("the log of a number that is not positive is not real");let n=0n,t=e;for(;t>=this.S;)t>>=1n,n++;for(;t<this.S/2n;)t<<=1n,n--;const r=this.div(t-this.S,t+this.S),s=this.mul(r,r);let o=r,i=0n;for(let e=1n;0n!==o;e+=2n)i+=o/e,o=this.mul(o,s);return 2n*i+n*this.ln2}sin(e){const n=2n*this.pi;let t=e%n;t>this.pi&&(t-=n),t<-this.pi&&(t+=n);const r=this.mul(t,t);return this.series(t,(e,n)=>-e*r/this.S/BigInt(2*n*(2*n+1)))}cos(e){return this.sin(e+this.pi/2n)}atan(e){if(it(e)>this.S){const n=this.pi/2n;return(e>0n?n:-n)-this.atan(this.div(this.S,e))}let n=e;for(let e=0;e<2;e++)n=this.div(n,this.S+this.sqrt(this.S+this.mul(n,n)));const t=this.mul(n,n);let r=n,s=0n;for(let e=1n,n=1n;0n!==r;e+=2n,n=-n)s+=n*r/e,r=this.mul(r,t);return 4n*s}asin(e){if(it(e)>this.S)throw new G("arcsin of a number beyond ±1 is not real");return it(e)===this.S?e>0n?this.pi/2n:-this.pi/2n:this.atan(this.div(e,this.sqrt(this.S-this.mul(e,e))))}}function ut(e,n,t){if(t>0n)return e.atan(e.div(n,t));if(t<0n)return e.atan(e.div(n,t))+(n>=0n?e.pi:-e.pi);if(0n===n)throw new G("the argument of 0 is undefined");return n>0n?e.pi/2n:-e.pi/2n}const lt={add:(e,n)=>[e[0]+n[0],e[1]+n[1]],sub:(e,n)=>[e[0]-n[0],e[1]-n[1]],mul:(e,n,t)=>[e.mul(n[0],t[0])-e.mul(n[1],t[1]),e.mul(n[0],t[1])+e.mul(n[1],t[0])],div(e,n,t){const r=e.mul(t[0],t[0])+e.mul(t[1],t[1]);if(0n===r)throw new G("division by zero");return[e.div(e.mul(n[0],t[0])+e.mul(n[1],t[1]),r),e.div(e.mul(n[1],t[0])-e.mul(n[0],t[1]),r)]},abs:(e,n)=>e.sqrt(e.mul(n[0],n[0])+e.mul(n[1],n[1])),exp(e,n){const t=e.exp(n[0]);return[e.mul(t,e.cos(n[1])),e.mul(t,e.sin(n[1]))]},ln(e,n){const t=lt.abs(e,n);if(0n===t)throw new G("the log of 0 is undefined");return[e.ln(t),ut(e,n[1],n[0])]},pow(e,n,t,r){if(0n===n[0]&&0n===n[1])return[0n,0n];if(r&&r.isInteger){let t=r.n<0n?-r.n:r.n,s=[e.S,0n],o=n;for(;t>0n;)1n&t&&(s=lt.mul(e,s,o)),o=lt.mul(e,o,o),t>>=1n;return r.n<0n?lt.div(e,[e.S,0n],s):s}return lt.exp(e,lt.mul(e,t,lt.ln(e,n)))},sinh:(e,n)=>(e.exp(n)-e.exp(-n))/2n,cosh:(e,n)=>(e.exp(n)+e.exp(-n))/2n},ct={sin:(e,[n,t])=>[e.mul(e.sin(n),lt.cosh(e,t)),e.mul(e.cos(n),lt.sinh(e,t))],cos:(e,[n,t])=>[e.mul(e.cos(n),lt.cosh(e,t)),-e.mul(e.sin(n),lt.sinh(e,t))],tan:(e,n)=>lt.div(e,ct.sin(e,n),ct.cos(e,n)),ln:(e,n)=>lt.ln(e,n),sqrt:(e,n)=>lt.exp(e,lt.mul(e,[e.S/2n,0n],lt.ln(e,n))),sinh:(e,[n,t])=>[e.mul(lt.sinh(e,n),e.cos(t)),e.mul(lt.cosh(e,n),e.sin(t))],cosh:(e,[n,t])=>[e.mul(lt.cosh(e,n),e.cos(t)),e.mul(lt.sinh(e,n),e.sin(t))]},ft=e=>({q:e}),pt=([e,n])=>0n===n?{f:e}:{z:[e,n]};function dt(e,n,t){const r=e=>((e,n)=>n.z??[ht(e,n),0n])(t,n[e]);switch(e.op){case"+":return pt(lt.add(r(0),r(1)));case"-":return pt(lt.sub(r(0),r(1)));case"neg":return pt([-r(0)[0],-r(0)[1]]);case"*":return pt(lt.mul(t,r(0),r(1)));case"/":return pt(lt.div(t,r(0),r(1)));case"^":return pt(lt.pow(t,r(0),r(1),n[1].q));case"sqrt":return pt(ct.sqrt(t,r(0)));case"root":return pt(lt.pow(t,r(1),lt.div(t,[t.S,0n],r(0)),n[0].q?.inv()));case"abs":return{f:lt.abs(t,r(0))};case"arg":return{f:ut(t,r(0)[1],r(0)[0])};case"re":return{f:r(0)[0]};case"im":return{f:r(0)[1]};case"conj":return pt([r(0)[0],-r(0)[1]]);case"log":return pt(lt.div(t,lt.ln(t,r(1)),lt.ln(t,r(0))));default:{const s=ct[e.op];if(!s||1!==n.length)throw new G(`no complex value for ${e.op}`);return pt(s(t,r(0)))}}}function ht(e,n){return n.q?e.fromQ(n.q):n.f}const mt={sin:(e,n)=>e.sin(n),cos:(e,n)=>e.cos(n),tan:(e,n)=>e.div(e.sin(n),e.cos(n)),sec:(e,n)=>e.div(e.S,e.cos(n)),csc:(e,n)=>e.div(e.S,e.sin(n)),cot:(e,n)=>e.div(e.cos(n),e.sin(n)),arcsin:(e,n)=>e.asin(n),arccos:(e,n)=>e.pi/2n-e.asin(n),arctan:(e,n)=>e.atan(n),sinh:(e,n)=>(e.exp(n)-e.exp(-n))/2n,cosh:(e,n)=>(e.exp(n)+e.exp(-n))/2n,tanh:(e,n)=>{const t=e.exp(n),r=e.exp(-n);return e.div(t-r,t+r)},arcsinh:(e,n)=>e.ln(n+e.sqrt(e.mul(n,n)+e.S)),arccosh:(e,n)=>{if(n<e.S)throw new G("arccosh of a number below 1 is not real");return e.ln(n+e.sqrt(e.mul(n,n)-e.S))},arctanh:(e,n)=>{if(it(n)>=e.S)throw new G("arctanh of a number beyond ±1 is not real");return e.ln(e.div(e.S+n,e.S-n))/2n},ln:(e,n)=>e.ln(n),loglog:(e,n)=>e.ln(e.ln(n)),logloglog:(e,n)=>e.ln(e.ln(e.ln(n))),expm1:(e,n)=>e.exp(n)-e.S};function gt(e,n,t){if("num"===e.type)return ft(se(e.token));if("sym"===e.type){if("pi"===e.token||"π"===e.token)return{f:n.pi};if("e"===e.token)return{f:n.e};if("i"===e.token&&le.complex)return{z:[0n,n.S]};if(t&&e.token in t){const n=t[e.token],r="number"==typeof n||"string"==typeof n||"bigint"==typeof n?se(String(n)):null;if(!r)throw new G(`the value of ${e.token} is not a number`);return ft(r)}throw new G(`${e.token} has no value`)}le.complex&&e.op.startsWith("\\:")&&Ve[e.op.slice(2)]&&(e=R(Ve[e.op.slice(2)],e.args));const r=e.args.map(e=>gt(e,n,t));if(r.some(e=>e.z)||["re","im","conj","arg"].includes(e.op)||function(e,n){if(!le.complex)return!1;const t=e=>e.q?e.q.sign<0:void 0!==e.f&&e.f<0n;return"sqrt"===e.op||"ln"===e.op||"log"===e.op?t(n["log"===e.op?1:0])||"log"===e.op&&t(n[0]):"^"===e.op?t(n[0])&&!(n[1].q&&n[1].q.d%2n==1n):"root"===e.op&&t(n[1])&&!(n[0].q&&n[0].q.isInteger&&n[0].q.n%2n==1n)}(e,r))return dt(e,r,n);const s=r.every(e=>e.q),o=e=>ht(n,r[e]);switch(e.op){case"+":return s?ft(r[0].q.add(r[1].q)):{f:o(0)+o(1)};case"-":return s?ft(r[0].q.sub(r[1].q)):{f:o(0)-o(1)};case"neg":return r[0].q?ft(r[0].q.neg()):{f:-r[0].f};case"*":return s?ft(r[0].q.mul(r[1].q)):{f:n.mul(o(0),o(1))};case"/":return s?ft(r[0].q.div(r[1].q)):{f:n.div(o(0),o(1))};case"^":return bt(n,r[0],r[1]);case"sqrt":return bt(n,r[0],ft(re.HALF));case"root":return bt(n,r[1],r[0].q?ft(r[0].q.inv()):{f:n.div(n.S,r[0].f)});case"abs":return r[0].q?ft(r[0].q.abs()):{f:it(r[0].f)};case"floor":return ft(r[0].q?r[0].q.floor():new re(vt(r[0].f,n.S)));case"ceil":return ft(r[0].q?r[0].q.ceil():new re(-vt(-r[0].f,n.S)));case"log":return{f:n.div(n.ln(o(1)),n.ln(o(0)))};case"atan2":return{f:ut(n,o(0),o(1))};case"max":case"min":if(!r.length)throw new G(`${e.op} of nothing`);return s?ft(r.map(e=>e.q).reduce((n,t)=>("max"===e.op?t.sub(n).sign>0:t.sub(n).sign<0)?t:n)):{f:r.map((e,n)=>o(n)).reduce((n,t)=>"max"===e.op?t>n?t:n:t<n?t:n)};case"sum":return s?ft(r.reduce((e,n)=>e.add(n.q),re.ZERO)):{f:r.reduce((e,n,t)=>e+o(t),0n)};case"prod":return s?ft(r.reduce((e,n)=>e.mul(n.q),re.ONE)):{f:r.reduce((e,t,r)=>n.mul(e,o(r)),n.S)};case"mean":if(!r.length)throw new G("mean of nothing");return s?ft(r.reduce((e,n)=>e.add(n.q),re.ZERO).div(new re(BigInt(r.length)))):{f:r.reduce((e,n,t)=>e+o(t),0n)/BigInt(r.length)};case"mod":{if(s){if(r[1].q.isZero)throw new G("mod 0 is undefined");return ft(r[0].q.sub(r[1].q.mul(r[0].q.div(r[1].q).floor())))}const e=o(1);if(0n===e)throw new G("mod 0 is undefined");return{f:o(0)-n.mul(e,vt(n.div(o(0),e),n.S)*n.S)}}case"round":{if(!r[1].q?.isInteger)throw new G("round needs a whole number of places");const e=10n**it(r[1].q.n),t=r[0].q??new re(o(0),n.S),s=r[1].q.sign>=0,i=(s?t.mul(new re(e)):t.div(new re(e))).add(re.HALF).floor();return ft(s?i.div(new re(e)):i.mul(new re(e)))}case"!":{if(!r[0].q?.isInteger||r[0].q.sign<0)throw new G("factorial is only worked out for whole numbers");let e=1n;for(let n=2n;n<=r[0].q.n;n++)if(e*=n,0n==(255n&n)&&ne(e)>st)throw ot();return ft(new re(e))}default:{const t=mt[e.op];if(!t||1!==r.length)throw new G(`no numeric value for ${e.op}`);return{f:t(n,o(0))}}}}const vt=(e,n)=>{const t=e/n;return e<0n&&t*n!==e?t-1n:t};function bt(e,n,t){if(t.q&&t.q.isInteger){if(n.q)return ft(n.q.pow(t.q.n));let r=t.q.n;const s=r<0n;s&&(r=-r);let o=e.S,i=n.f;for(;r>0n;){if(1n&r&&(o=e.mul(o,i)),i=e.mul(i,i),ne(o)>st+4*e.P||ne(i)>8e5){if(s)return{f:0n};throw ot()}r>>=1n}return{f:s?e.div(e.S,o):o}}const r=ht(e,n);if(0n===r){if(t.q?t.q.sign>0:t.f>0n)return ft(re.ZERO);throw new G("0 to a power that is not positive is undefined")}if(r<0n){if(t.q&&t.q.d%2n==1n){const n=bt(e,{f:-r},t).f;return{f:t.q.n%2n==0n?n:-n}}throw new G("a negative number to a fractional power is not real")}if(t.q&&1n===it(t.q.n)&&t.q.d<=64n){const n=oe(r*e.S**(t.q.d-1n),Number(t.q.d));return{f:t.q.n<0n?e.div(e.S,n):n}}return{f:e.exp(e.mul(ht(e,t),e.ln(r)))}}function yt(e,n,t){const r=e<0n?"-":"",s=it(e);if(0n===s)return{sign:"",digits:"0",point:1};const o=s.toString(),i=o.length-n.P;let a=o.slice(0,t);o.length>t&&o[t]>="5"&&(a=(BigInt(a)+1n).toString());let u=i;return a.length>t&&(a=a.slice(0,t),u++),{sign:r,digits:a.replace(/0+$/,"")||"0",point:u}}function wt({sign:e,digits:n,point:t}){if("0"===n)return"0";if(t>21||t<-6){return`${e}${n.length>1?`${n[0]}.${n.slice(1)}`:n}e${t-1}`}return t<=0?`${e}0.${"0".repeat(-t)}${n}`:t>=n.length?`${e}${n}${"0".repeat(t-n.length)}`:`${e}${n.slice(0,t)}.${n.slice(t)}`}function xt(e){let n=0n,t=0n,r=e.d;for(;r%2n==0n;)r/=2n,n++;for(;r%5n==0n;)r/=5n,t++;const s=n>t?n:t;let o=it(e.n)*10n**s/e.d;if(0n===o)return 1;for(;o%10n==0n;)o/=10n;return o.toString().length}function qt(e){let n=e.d;for(;n%2n==0n;)n/=2n;for(;n%5n==0n;)n/=5n;return 1n===n}function kt(e){const n=/^(-?[\d.]+)e(-?\d+)$/.exec(e);return n?R("*",[C(n[1]),R("^",[C("10"),C(n[2])])]):C(e)}function $t(e,{digits:n=15,scope:t}={}){if(!Number.isInteger(n)||n<1||n>1e5)throw new G("digits must be a whole number from 1 to 100000");let r=n+25,s=null;for(let o=0;o<4;o++){const i=new at(r),a=gt(e,i,t);if(a.z){const e=Ot(a.z,i,n);if(e.retry&&o<3){r+=e.retry;continue}return void 0===e.real?e:St(e.real,i,n,null)}if(a.q&&a.q.isInteger&&it(a.q.n).toString().length<=n)return{text:a.q.n.toString(),node:C(a.q.n.toString()),number:Number(a.q.n),re:Number(a.q.n),im:0,exact:!0};const u=ht(i,a);if(0n===u&&(!a.q||!a.q.isZero)&&o<3){s=null,r*=4;continue}const l=yt(u,i,n);if(s&&l.point<-10&&s.point-l.point>=(r-s.P)/2)return{text:"0",node:C("0"),number:0,re:0,im:0,exact:!1};if(!(l.point<-10&&o<3)||s&&s.point===l.point)return St(u,i,n,a.q);s={point:l.point,P:r},r+=10-l.point}throw new G("could not approximate")}function St(e,n,t,r){const s=wt(yt(e,n,t));return{text:s,node:kt(s),number:Number(s),re:Number(s),im:0,exact:Boolean(r)&&qt(r)&&xt(r)<=t}}function Ot([e,n],t,r){const s=10n**BigInt(Math.max(0,t.P-r-12)),o=e=>it(e)>s;if(!o(n))return{real:e};const i=yt(n,t,r);if(i.point<-10&&o(n))return{retry:10-i.point};const a=wt(i),u="1"===a?"i":"-1"===a?"-i":`${a}i`,l="1"===a?B("i"):R("*",[kt(a.replace(/^-/,"")),B("i")]);if(!o(e))return{text:u,node:a.startsWith("-")?R("neg",[l]):l,number:NaN,re:0,im:Number(a),exact:!1};const c=wt(yt(e,t,r)),f=a.startsWith("-"),p="1"===a.replace(/^-/,"")?B("i"):R("*",[kt(a.replace(/^-/,"")),B("i")]);return{text:`${c} ${f?"-":"+"} ${u.replace(/^-/,"")}`,node:R(f?"-":"+",[kt(c),p]),number:NaN,re:Number(c),im:Number(a),exact:!1}}function Nt(e,n={}){const t=e=>(e=>0===nn(e).size)(e)?"num"===e.type&&/^-?\d+$/.test(e.token)?e:$t(e,n).node:P(e)?R(e.op,e.args.map(t)):e;return t(e)}const At={variable:null},It=(e,n)=>null!==n&&nn(e).has(n);function Mt(e){if("num"===e.type)return se(e.token);if(P(e)&&"/"===e.op&&e.args.every(e=>"num"===e.type)){const n=se(e.args[0].token),t=se(e.args[1].token);return n&&t&&!t.isZero?n.div(t):null}return null}const Et=e=>0===nn(e).size;function Tt(e,n,t){const r=function(e){const n=He(e);return"num"===n.k?n.q.isZero?n.q:null:"atom"===n.k&&"sym"===n.node.type&&"pi"===n.node.token?se("1"):"mul"===n.k&&1===n.fs.length&&"atom"===n.fs[0].b.k&&"pi"===n.fs[0].b.node.token&&"num"===n.fs[0].e.k&&n.fs[0].e.q.isOne?n.c:null}(e);if(!r)return!1;const[s,o="1"]=String(n).split("/");return t(r.compare(se(s).div(se(o))))}function jt(e){if(!Et(e))return NaN;try{const{number:n}=$t(e,{digits:30});return Math.sign(n)}catch{return NaN}}function Zt(){gn("hasVariable")||(hn("hasVariable",e=>It(e,At.variable),"mentions the variable being solved for"),hn("freeOfVariable",e=>null!==At.variable&&!It(e,At.variable),"does not mention the variable being solved for"),hn("isRational",e=>null!==Mt(e),"an exact number: 3, -2, 1/2"),hn("isWhole",e=>Mt(e)?.isInteger??!1,"a whole number (any size)"),hn("isEvenWhole",e=>{const n=Mt(e);return Boolean(n?.isInteger&&n.n%2n==0n)},"an even whole number"),hn("isOddWhole",e=>{const n=Mt(e);return Boolean(n?.isInteger&&n.n%2n!=0n)},"an odd whole number"),hn("isPositiveRational",e=>(Mt(e)?.sign??0)>0,"an exact number above 0"),hn("isNegativeRational",e=>(Mt(e)?.sign??0)<0,"an exact number below 0"),hn("isConstant",Et,"has no unknowns (numbers, π and e only)"),hn("notOne",e=>{const n=Mt(e);return!n||!n.isOne},"anything except the number 1"),hn("notMinusOne",e=>{const n=Mt(e);return!n||!n.equals(se("-1"))},"anything except the number -1"),hn("hasMinusSign",e=>function(e){const n=He(e);return"num"===n.k?n.q.sign<0:"mul"===n.k&&n.c.sign<0}(e),"written with a leading minus: -x, -2x, -π/6"),hn("piMultipleAtLeast",(e,n)=>Tt(e,n,e=>e>=0),"a multiple of π, at least k·π"),hn("piMultipleAbove",(e,n)=>Tt(e,n,e=>e>0),"a multiple of π, above k·π"),hn("piMultipleBelow",(e,n)=>Tt(e,n,e=>e<0),"a multiple of π, below k·π"),hn("piMultipleAtMost",(e,n)=>Tt(e,n,e=>e<=0),"a multiple of π, at most k·π"),hn("isPositiveConstant",e=>jt(e)>0,"no unknowns, and above 0 (e, π, √2, 3)"),hn("isNegativeConstant",e=>jt(e)<0,"no unknowns, and below 0"),hn("hasImaginaryPart",e=>{if(!le.complex)return!1;const n=Be(He(e));return Boolean(n)&&!("num"===n.im.k&&n.im.q.isZero)},"complex mode: has a nonzero imaginary part (unknowns count as real)"),hn("isSymbolNode",e=>"sym"===e.type&&!ue.has(e.token),"a single unknown such as x"))}function zt(e){const n=new Map;for(const t of e){const e=t.id??t.name;if(!e)throw new Error(`a rule needs an id (pattern ${t.pattern})`);n.set(String(e),{...n.get(String(e))??{},...t})}const t=[...n.values()].map(e=>{const n={...e};try{void 0!==n.pattern&&(n.pattern=function(e){const n=W(e),t=e=>"num"===e.type||("sym"===e.type?e.token.startsWith("="):e.args.every(t)),r=e=>"sym"===e.type?B(e.token.slice(1)):"num"===e.type?e:R(e.op,e.args.map(r)),s=e=>"sym"===e.type?B(`=${e.token}`):"num"===e.type?e:R(e.op,e.args.map(s)),o=e=>"op"!==e.type?e:t(e)?s(Je(r(e))):R(e.op,e.args.map(o));return o(n).s}(String(n.pattern)))}catch(e){throw new Error(`rule "${n.id}": bad pattern "${n.pattern}": ${e.message}`)}return"hidden"===n.step&&(n.tags=[...n.tags??[],"hidden"]),n});return Gn.fromSpecs(t,{strict:!0})}function Dt(e,n,t,r){return e.explain?e.explain.replace(/\{(\w+)\}/g,(e,s)=>"result"===s?t?r(t):e:n[s]?r(n[s]):e).trim():""}const Bt=e=>P(e)&&("+"===e.op||"-"===e.op),Ct=e=>P(e)&&("*"===e.op||"/"===e.op);function*Ft(e,n,{order:t="pre"}={}){for(const r of function(e,n,{order:t="post"}={}){const r=[];for(const{node:s,path:o}of Y(e,t))for(const e of tt(s,n))r.push({...e,node:s,path:o});return r}(e,n,{order:t})){const n=rt(r.rule.outputTemplate,r.bound);yield{rule:r.rule,bound:r.bound,path:r.path,before:r.node,after:n,next:()=>Je(K(e,r.path,n))}}for(const{node:r,path:s}of Y(e,t)){const t=Bt(r);if(!t&&!Ct(r))continue;const o=t?tn(He(r)):rn(He(r));if(o.length<3)continue;const i=t?Ae:Me;for(let t=0;t<o.length;t++)for(let r=t+1;r<o.length;r++){const a=Ge(i([o[t],o[r]]));for(const u of tt(a,n)){const n=rt(u.rule.outputTemplate,u.bound),l=o.filter((e,n)=>n!==t&&n!==r);yield{rule:u.rule,bound:u.bound,path:s,before:a,after:n,next:()=>Je(K(e,s,Ge(i([He(n),...l]))))}}}}}function Vt(e,n,{format:t,order:r="pre",maxSteps:s=200,variable:o=null}={}){const i=At.variable;At.variable=o;try{let o=Je(e);const i=new Set([o.s]),a=[];for(let e=0;e<s;e++){let e=null;for(const t of Ft(o,n,{order:r})){const n=t.next();if(n.s!==o.s&&!i.has(n.s)){e={c:t,next:n};break}}if(!e)break;const{c:s,next:u}=e;a.push({id:s.rule.id,name:s.rule.name,tags:s.rule.tags,from:o.s,to:u.s,path:s.path,before:s.before.s,after:s.after.s,explanation:Dt(s.rule,s.bound,Je(s.after),t)}),o=u,i.add(o.s)}return{node:o,steps:a}}finally{At.variable=i}}const Rt={full:[],normal:["hidden"],brief:["hidden","tidy","identity","value","split","base","arithmetic"]},Ut=(e,n)=>"all"===n||"*"===n||Array.isArray(n)&&n.some(n=>n===e.id||e.tags?.includes(n));function Pt(e){if(!1===e)return null;if(void 0===e||!0===e)return{show:"all",hide:Rt.normal,explain:!0};if("string"==typeof e){if(!Rt[e])throw new Error(`steps: "${e}" is not one of ${Object.keys(Rt).join(", ")}`);return{show:"all",hide:Rt[e],explain:!0}}const n=e.detail??"normal";if(!Rt[n])throw new Error(`steps.detail: "${n}" is not one of ${Object.keys(Rt).join(", ")}`);return{show:e.show??"all",hide:[...Rt[n],...e.hide??[]],explain:e.explain??!0}}function Wt(e,n){if(!n)return[];const t=[];let r=null;for(const s of e){if(!(Ut(s,n.show)&&!Ut(s,n.hide))){r=r??{from:s.from,ids:[]},r.ids.push(s.id);continue}const e={...s};r&&(e.from=r.from,e.also=r.ids,e.path=null,r=null);!0===n.explain||!1!==n.explain&&Ut(s,n.explain)||delete e.explanation,t.push(e)}if(r&&t.length){const n=t[t.length-1];n.to=e[e.length-1].to,n.also=[...n.also??[],...r.ids]}return t}const Lt=de(re.ONE),_t=(e,n)=>"atom"===e.k&&"sym"===e.node.type&&e.node.token===n;function Ht(e){switch(e.k){case"num":default:return e;case"atom":return"op"===e.node.type?Le(e.node.op,e.node.args.map(e=>Ht(He(e)))):e;case"add":return Ae(tn(e).map(Ht));case"mul":{let n=[de(e.c)];for(const t of e.fs){const e=Ht(t.b);if("add"===e.k&&ve(t.e)&&t.e.q.isInteger&&t.e.q.sign>0&&t.e.q.n<=BigInt(60))for(let r=0n;r<t.e.q.n;r++)n=Jt(n,tn(e));else n=Jt(n,[Te(e,t.e)])}return Ae(n)}}}function Jt(e,n){const t=[];for(const r of e)for(const e of n)t.push(Me([r,e]));return tn(Ae(t))}function Qt(e,n){const t=new Map;for(const r of tn(Ht(e))){const{coef:e,rest:s}=Ne(r);let o=0;const i=[de(e)];for(const e of s?rn(s):[]){const{b:t,e:r}="mul"===e.k&&1===e.fs.length&&e.c.isOne?e.fs[0]:{b:e,e:Lt};if(_t(t,n)){if(!ve(r)||!r.q.isInteger||r.q.sign<0)return null;o+=Number(r.q.n)}else{if(Yt(t,n)||Yt(r,n))return null;i.push(e)}}t.set(o,Ae([t.get(o)??de(re.ZERO),Me(i)]))}for(const[e,n]of t)ve(n)&&n.q.isZero&&t.delete(e);return t}const Yt=(e,n)=>nn(Ge(e)).has(n);function Kt(e){if(!e)return null;const n=Math.max(0,...e.keys());if(n>256)return null;const t=[];for(let r=0;r<=n;r++){const n=e.get(r)??de(re.ZERO);if(!ve(n))return null;t.push(n.q)}return t}function Gt(e,n){const t=He(B(n));return Ae(e.map((e,n)=>Me([de(e),Ee(t,de(re.of(n)))])))}const Xt=e=>{const n=e.slice();for(;n.length>1&&n[n.length-1].isZero;)n.pop();return n},er=(e,n)=>e.reduceRight((e,t)=>e.mul(n).add(t),re.ZERO);function nr(e,n){const t=e.length-1,r=new Array(t);let s=re.ZERO;for(let o=t;o>=1;o--)s=e[o].add(s.mul(n)),r[o-1]=s;return r}function tr(e){if(0n===(e=(e=>e<0n?-e:e)(e)))return null;if(e>10n**14n)return null;const n=[];let t=e;for(let e=2n;e*e<=t;e+=2n===e?1n:2n){if(t%e)continue;let r=0;for(;t%e===0n;)t/=e,r++;n.push([e,r])}t>1n&&n.push([t,1]);let r=[1n];for(const[e,t]of n){const n=[];for(const s of r)for(let r=0,o=1n;r<=t;r++,o*=e)n.push(s*o);if(r=n,r.length>2e4)return null}return r.sort((e,n)=>e<n?-1:e>n?1:0)}function rr(e){let n=Xt(e);const t=[];for(;n.length>1&&n[0].isZero;)t.push(re.ZERO),n=n.slice(1);if(n.length<=1)return{roots:t,rest:n};const r=n.reduce((e,n)=>e*n.d/te(e,n.d),1n),s=n.map(e=>e.n*r/e.d),o=tr(s[0]),i=tr(s[s.length-1]);if(!o||!i)return{roots:t,rest:n};const a=new Map;for(const e of o)for(const n of i)for(const t of[1n,-1n]){const r=new re(t*e,n);a.set(r.toString(),r)}const u=[...a.values()].sort((e,n)=>e.compare(n));for(const e of u)for(;n.length>1&&er(n,e).isZero;)t.push(e),n=nr(n,e);return{roots:t.sort((e,n)=>e.compare(n)),rest:n}}function sr(e){if("num"===e.k)return{coef:e.q,factors:[],notes:[]};if("atom"===e.k)return{coef:re.ONE,factors:[{base:e,exp:Lt}],notes:[]};if("mul"===e.k){let n=e.c;const t=[],r=[];for(const s of e.fs)if("add"===s.b.k&&ve(s.e)&&s.e.q.isInteger){const e=sr(s.b);n=n.mul(e.coef.pow(s.e.q.n));for(const n of e.factors)t.push({base:n.base,exp:Me([n.exp,s.e])});r.push(...e.notes)}else t.push({base:s.b,exp:s.e});return or(n,t,r)}return function(e){const n=tn(e),t=[],r=n.map(e=>{const{coef:n,rest:t}=Ne(e);return{coef:n,fs:t?rn(t).map(ar):[]}}),s=r.reduce((e,n)=>({n:te(e.n,n.coef.n),d:e.d*n.coef.d/te(e.d,n.coef.d)}),{n:0n,d:1n});let o=new re(s.n||1n,s.d);ir(e)<0&&(o=o.neg());const i=[];for(const e of r[0].fs){if(!ve(e.e)||e.e.q.sign<=0)continue;let n=e.e.q;const t=we(e.b);let s=!0;for(const e of r.slice(1)){const r=e.fs.find(e=>we(e.b)===t&&ve(e.e)&&e.e.q.sign>0);if(!r){s=!1;break}r.e.q.compare(n)<0&&(n=r.e.q)}s&&i.push({base:e.b,exp:de(n)})}let a=e;if(!o.isOne||i.length){const e=Me([de(o),...i.map(e=>Te(e.base,e.exp))]);a=Ae(n.map(n=>Me([n,Ee(e,de(re.MINUS_ONE))]))),t.push({id:"factor.common",values:{common:e}})}const u="add"===a.k?function(e,n){const t=[...ur(e)];for(const r of t){const s=Kt(Qt(e,r));if(!s||s.length<3)continue;if(1!==t.length)break;const{roots:o,rest:i}=rr(s);if(!o.length)break;const a=[];let u=i[i.length-1]??re.ONE;const l=i.map(e=>e.div(u)),c=[...o].sort((e,n)=>e.abs().compare(n.abs())||n.sign-e.sign);for(const e of c){const t=Gt([new re(-e.n),new re(e.d)],r);a.push({base:t,exp:Lt}),u=u.div(new re(e.d)),n.push({id:"factor.root",values:{root:de(e),factor:t}})}if(l.length>1){const e=l.reduce((e,n)=>e*n.d/te(e,n.d),1n),n=l.map(n=>n.mul(new re(e))),t=n.reduce((e,n)=>te(e,n.n),0n)||1n;u=u.mul(new re(t,e)),a.push({base:Gt(n.map(e=>e.div(new re(t))),r),exp:Lt})}return or(u,a,[])}const r=tn(e);if(2===r.length){const[e,t]=r;for(const r of[2,3]){const s=lr(e,r),o=lr(Re(t),r),i=3===r?lr(t,r):null;if(s&&o&&2===r){n.push({id:"factor.squares",values:{a:s,b:o}});const e=sr(Ae([s,Re(o)])),t=sr(Ae([s,o]));return or(e.coef.mul(t.coef),[...e.factors,...t.factors],[...e.notes,...t.notes])}if(3===r&&s&&(o||i)){const e=o??i,t=o?-1:1;n.push({id:t<0?"factor.cubes-difference":"factor.cubes-sum",values:{a:s,b:e}});const r=Ae(t<0?[s,Re(e)]:[s,e]),a=Ae([Ee(s,de(re.of(2))),t<0?Me([s,e]):Re(Me([s,e])),Ee(e,de(re.of(2)))]),u=sr(r);return or(u.coef,[...u.factors,{base:a,exp:Lt}],u.notes)}}}return{coef:re.ONE,factors:[{base:e,exp:Lt}],notes:[]}}(a,t):sr(a);return or(o.mul(u.coef),[...i,...u.factors],[...t,...u.notes.filter(e=>!t.includes(e))])}(e)}function or(e,n,t){const r=new Map;for(const e of n){const n=we(e.base),t=r.get(n);t?t.exp=Ae([t.exp,e.exp]):r.set(n,{...e})}return{coef:e,factors:[...r.values()].filter(e=>!(ve(e.exp)&&e.exp.q.isZero)),notes:t}}const ir=e=>Ne(tn(e)[0]).coef.sign;const ar=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length?{b:e.fs[0].b,e:e.fs[0].e}:{b:e,e:Lt},ur=e=>nn(Ge(e));function lr(e,n){const{coef:t,rest:r}=Ne(e);if(t.sign<0)return null;const s=function(e,n){const t=e=>{if(e<0n)return null;let t=0n,r=1n;for(;r**BigInt(n)<=e;)r*=2n;for(;t<r-1n;){const s=(t+r)/2n;s**BigInt(n)<=e?t=s:r=s}return t**BigInt(n)===e?t:null},r=t(e.n),s=t(e.d);return null!==r&&null!==s?new re(r,s):null}(t,n);if(!s)return null;const o=[de(s)];for(const e of r?rn(r).map(ar):[]){if(!ve(e.e))return null;const t=e.e.q.div(re.of(n));if(!t.isInteger)return null;o.push(Te(e.b,de(t)))}return Me(o)}function cr({coef:e,factors:n}){const t=[],r=[];for(const e of n){const n=ve(e.exp)&&e.exp.q.sign<0,s=n?de(e.exp.q.neg()):e.exp,o=Ge(Te(e.base,s));(n?r:t).push(o)}const s=e=>e.reduce((e,n)=>e?R("*",[e,n]):n,null),o=e.n<0n?-e.n:e.n;let i=t.length?s(1n===o?t:[Ge(de(new re(o))),...t]):Ge(de(new re(o)));return e.n<0n&&(i=R("neg",[i])),1n!==e.d&&r.unshift(Ge(de(new re(e.d)))),r.length?R("/",[i,s(r)]):i}function fr(e){if("mul"!==e.k)return{num:e,den:Lt};const n=[de(new re(e.c.n))],t=[de(new re(e.c.d))];for(const r of e.fs)ve(r.e)&&r.e.q.sign<0?t.push(Te(r.b,de(r.e.q.neg()))):n.push(Te(r.b,r.e));return{num:Me(n),den:Me(t)}}function pr(e){if("add"!==e.k)return fr(e);const n=tn(e).map(fr),t=new Map;let r=1n;for(const e of n){const{coef:n,rest:s}=Ne(e.den);r=r*n.n/te(r,n.n);for(const e of s?rn(s).map(ar):[]){const n=we(e.b),r=t.get(n);(!r||ve(e.e)&&ve(r.e)&&e.e.q.compare(r.e.q)>0)&&t.set(n,e)}}const s=Me([de(new re(r)),...[...t.values()].map(e=>Te(e.b,e.e))]);if(ve(s)&&s.q.isOne)return{num:e,den:Lt};return{num:Ht(Ae(n.map(e=>Me([e.num,s,Ee(e.den,de(re.MINUS_ONE))])))),den:s}}function dr(e){const{num:n,den:t}=pr(e);if(ve(t)&&t.q.isOne)return null;const r=sr(n),s=sr(t),o=new Set(r.factors.map(e=>we(e.base))),i=s.factors.filter(e=>o.has(we(e.base))),a=[...r.factors,...s.factors.map(e=>({base:e.base,exp:Re(e.exp)}))];return{...or(r.coef.div(s.coef),a,[...r.notes,...s.notes]),canceled:i.map(e=>e.base)}}const hr=(e,n)=>R("=",[e,n]),mr=Je(R("+",[B("x"),R("neg",[B("x")])])),gr=e=>P(e)&&"="===e.op;function vr(e,n,t,r={}){const s=[],o=(n,t,r,o,i,a={})=>s.push(e.step(n,t,r,o,i,a));o.raw=e=>s.push(e);const i=gr(n)?n:hr(n,mr),a=hr(Je(i.args[0]),Je(i.args[1]));a.s!==i.s&&o("normal","Work out each side",["tidy","arithmetic"],i,a);const u=[],l=[],c=new Set;u.numeric=c,kr(e,a,t,r,o,u,l,0);const f=[],p=new Set;for(const n of u.map(n=>c.has(n)?n:(n=>Vt(n,e.set.view("simplify"),{format:e.format}).node)(n))){const e=n.s;if(p.has(e))continue;p.add(e);const r=c.has(n)?null:wr(i,t,n);r?o("solve.reject","Check the answer",["check"],hr(B(t),n),hr(B(t),n),{value:n,reason:r}):f.push(n)}return f.sort(br),{solutions:f,unsolved:l,steps:s,always:l.some(e=>e.always)}}function br(e,n){const t=yr(e),r=yr(n);return null===t||null===r?e.s<n.s?-1:1:(Math.abs(t.im)>0)-(Math.abs(r.im)>0)||t.re-r.re||t.im-r.im}function yr(e){if(nn(e).size)return null;try{const{re:n,im:t}=$t(e,{digits:20});return{re:n,im:t}}catch{return null}}function wr(e,n,t){const[r,s]=e.args,o=new Set([...nn(r),...nn(s),...nn(t)]);if(o.delete(n),o.size)return null;const i=e=>xr(e,n,t);try{const e=$t(i(r),{digits:40}),n=$t(i(s),{digits:40}),t=Math.max(1,Math.hypot(e.re,e.im),Math.hypot(n.re,n.im));return Math.hypot(e.re-n.re,e.im-n.im)>1e-12*t?"it does not make the two sides equal":null}catch(e){return`the original equation has no value there (${e.message})`}}function xr(e,n,t){return"sym"===e.type?e.token===n?t:e:P(e)?R(e.op,e.args.map(e=>xr(e,n,t))):e}const qr=24;function kr(e,n,t,r,s,o,i,a){if(a>qr)return Mr(e,n,t,r,s,o,i);const u=function(e){const n=[],t=e=>{if(P(e)&&"|"===e.op)return void e.args.forEach(t);if(!gr(e))return void n.push(e);const r=e.args[1],s=Y(r,"pre").find(({node:e})=>P(e)&&"pm"===e.op);if(!s)return void n.push(e);const o=s.node.args[0],i=Je(K(r,s.path,o)),a=Je(K(r,s.path,R("neg",[o])));t(hr(e.args[0],i)),a.s!==i.s&&t(hr(e.args[0],a))};return t(e),n}(n);if(u.length>1){s("solve.split","Two cases",["split"],n,u.reduce((e,n)=>e?R("|",[e,n]):n,null));for(const n of u)kr(e,n,t,r,s,o,i,a+1);return}if(1===u.length&&u[0].s!==n.s)return kr(e,u[0],t,r,s,o,i,a+1);const[l,c]=n.args;if("sym"===l.type&&l.token===t&&!Yt(He(c),t))return void o.push(c);const f=Ae([He(l),Re(He(c))]);if(!Yt(f,t))return ve(f)&&f.q.isZero?(s("solve.always","Always true",["check"],n,n,{v:t}),void i.push(Object.assign(Object.create(n),{always:!0}))):void s("solve.never","No solution",["check"],n,n,{v:t});const p=tn(f).filter(e=>Yt(e,t)),d=tn(f).filter(e=>!Yt(e,t)),h=Ae(p),m=Re(Ae(d));if(le.complex){const u=Qt(f,t);if(u&&[...u.values()].every(e=>!Yt(e,t))&&Math.max(...u.keys())>=2){const l=hr(Ge(f),mr);return l.s!==n.s&&s("solve.one-side","Everything on one side",["move"],n,l,{v:t}),Ar(e,f,u,t,r,s,o,i,a,l)}}if(1===p.length)return $r(e,n,h,m,t,r,s,o,i,a);const g=hr(Ge(f),mr),v=Qt(f,t);if(v&&[...v.values()].every(e=>!Yt(e,t))&&Math.max(...v.keys())>=2)return g.s!==n.s&&s("solve.one-side","Everything on one side",["move"],n,g,{v:t}),Ar(e,f,v,t,r,s,o,i,a,g);const b=sr(f),y=b.factors.filter(e=>Yt(e.base,t)&&!(ve(e.exp)&&e.exp.q.sign<0));if(y.length>=2||1===y.length&&b.factors.length>1){const u=hr(cr(b),mr);g.s!==n.s&&s("solve.one-side","Everything on one side",["move"],n,g,{v:t}),u.s!==g.s&&s("solve.factor","Factor",["factor"],g,u,{});const l=y.map(e=>hr(Ge(e.base),mr));l.length>1&&s("solve.zero-product","A product is zero when a factor is",["split"],u,l.reduce((e,n)=>e?R("|",[e,n]):n,null),{});for(const n of l)kr(e,n,t,r,s,o,i,a+1);return}const w=pr(f);if(Yt(w.den,t)){const u=hr(Ge(w.num),mr);return s("solve.clear-denominator","Clear the denominator",["move"],n,u,{den:Ge(w.den)}),kr(e,u,t,r,s,o,i,a+1)}const x=p.filter(e=>!Nr(e,t));if(1===x.length&&/\b(sqrt|root|abs)\b/.test(Ge(x[0]).s))return $r(e,n,x[0],Re(Ae(tn(f).filter(e=>e!==x[0]))),t,r,s,o,i,a);const q=function(e,n){const t=Ge(e),r=new Map;for(const{node:e}of Y(t,"pre"))if(P(e)&&nn(e).has(n))if("^"!==e.op||nn(e.args[0]).has(n))["sin","cos","tan","ln","sqrt","abs"].includes(e.op)&&e.args[0].s===n&&r.set(e.s,e);else{const t=He(e.args[1]),{coef:s,rest:o}=Ne(t);if(o&&s.isInteger&&Ge(o).s===n){const t=Ge(Ee(He(e.args[0]),He(B(n))));r.set(t.s,t)}}const s="u"===n?"w":"u";for(const e of r.values()){const r=Ir(t,e,n,s);if(!r||nn(r).has(n))continue;const o=He(r),i=Qt(o,s);if(i&&Math.max(...i.keys())>=1)return{kernel:He(e),poly:o,symbol:s}}return null}(f,t);if(q){const n=q.symbol;s("solve.substitute","Substitute",["substitute"],g,hr(Ge(q.poly),mr),{u:B(n),kernel:Ge(q.kernel)});const u=[];kr(e,hr(Ge(q.poly),mr),n,r,s,u,i,a+1);for(const n of u)kr(e,hr(Ge(q.kernel),n),t,r,s,o,i,a+1);return}return Mr(e,g,t,r,s,o,i)}function $r(e,n,t,r,s,o,i,a,u,l){let c=hr(Ge(t),Ge(r));c.s!==n.s&&i("solve.move","Move the terms",["move"],n,c,{v:s});const{coef:f,rest:p}=Ne(t),d=p?rn(p):[],h=Me([de(f),...d.filter(e=>!Yt(e,s))]);if(!ve(h)||!h.q.isOne){const e=Me(d.filter(e=>Yt(e,s))),n=hr(Ge(e),Ge(Ue(r,h))),t=ve(h)&&!h.q.isInteger&&(1n===h.q.n||-1n===h.q.n);i(t?"solve.multiply":"solve.divide",t?"Multiply both sides":"Divide both sides",["move"],c,n,{by:Ge(t?de(h.q.inv()):h),v:s}),c=n}if("sym"===c.args[0].type&&c.args[0].token===s)return void a.push(c.args[1]);const m=He(c.args[1]);if(ve(m)&&m.q.isZero){const n=He(c.args[0]),t=rn(n).filter(e=>Yt(e,s)&&!Sr(e));if(t.length>1||t.length<rn(n).filter(e=>Yt(e,s)).length){const n=t.map(e=>hr(Ge(Or(e)),mr));i("solve.zero-product","A product is zero when a factor is",["split"],c,n.reduce((e,n)=>e?R("|",[e,n]):n,null),{});for(const t of n)kr(e,t,s,o,i,a,u,l+1);return}}const g=Vt(c,e.set.view("isolate"),{format:e.format,maxSteps:1,variable:s});return g.steps.length?(function(e,n){for(const t of n)e.raw(t)}(i,g.steps),kr(e,g.node,s,o,i,a,u,l+1)):Mr(e,c,s,o,i,a,u)}const Sr=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&ve(e.fs[0].e)&&e.fs[0].e.q.sign<0,Or=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&ve(e.fs[0].e)&&e.fs[0].e.q.sign>0?e.fs[0].b:e,Nr=(e,n)=>{const t=Qt(e,n);return Boolean(t)&&[...t.values()].every(e=>!Yt(e,n))};function Ar(e,n,t,r,s,o,i,a,u,l){const c=Math.max(...t.keys()),f=Kt(t);if(le.complex&&c>=3&&c<=64&&f&&f.every((e,n)=>0===n||n===c||e.isZero)&&!f[0].isZero){const n=f[0].neg().div(f[c]),t=Ee(de(n.abs()),de(new re(1n,BigInt(c)))),s=[];for(let r=0;r<c;r++){const o=Me([de(new re(BigInt((n.sign<0?1:0)+2*r),BigInt(c))),He(B("pi"))]),i=R("*",[Ge(t),R("+",[R("cos",[Ge(o)]),R("*",[B("i"),R("sin",[Ge(o)])])])]);s.push(Vt(i,e.set.view("simplify"),{format:e.format}).node)}return o("solve.roots","All n roots",["complex"],l,s.map(e=>hr(B(r),e)).reduce((e,n)=>e?R("|",[e,n]):n),{v:r,n:String(c),last:String(c-1),r:Ge(de(n))}),void i.push(...s)}if(f){const{roots:t}=rr(f);if(t.length){const t=sr(n),c=hr(cr(t),mr);if(t.factors.length>1||t.factors.some(e=>!(ve(e.exp)&&e.exp.q.isOne))){o("solve.factor","Factor",["factor"],l,c,{});const n=t.factors.filter(e=>Yt(e.base,r)).map(e=>hr(Ge(e.base),mr));n.length>1&&o("solve.zero-product","A product is zero when a factor is",["split"],c,n.reduce((e,n)=>e?R("|",[e,n]):n,null),{});for(const t of n)kr(e,t,r,s,o,i,a,u+1);return}}}if(2===c){const e=t.get(2),n=t.get(1)??de(re.ZERO),s=t.get(0)??de(re.ZERO),a=Ae([Ee(n,de(re.of(2))),Me([de(re.of(-4)),e,s])]);if(ve(a)&&a.q.sign<0&&!le.complex)return void o("solve.no-real","No real solutions",["quadratic"],l,l,{D:Ge(a)});const u=Me([de(re.of(2)),e]),c=Ee(a,de(re.HALF)),f=Ge(Ue(Ae([Re(n),c]),u)),p=Ge(Ue(Ae([Re(n),Re(c)]),u)),d=f.s===p.s?hr(B(r),f):R("|",[hr(B(r),f),hr(B(r),p)]);return o(le.complex&&ve(a)&&a.q.sign<0?"solve.quadratic-complex":"solve.quadratic","The quadratic formula",["quadratic"],l,d,{a:Ge(e),b:Ge(n),c:Ge(s),D:Ge(a),root:Ge(c),v:r}),i.push(f),void(p.s!==f.s&&i.push(p))}return Mr(e,l,r,s,o,i,a)}function Ir(e,n,t,r){if(e.s===n.s)return B(r);if(!P(e))return e;if("^"===e.op&&"^"===n.op&&e.args[0].s===n.args[0].s){const n=He(e.args[1]),{coef:s,rest:o}=Ne(n);if(o&&Ge(o).s===t&&s.isInteger)return R("^",[B(r),Ge(de(s))])}return R(e.op,e.args.map(e=>Ir(e,n,t,r)))}function Mr(e,n,t,r,s,o,i){if(r.approximate){const e="number"==typeof r.approximate?r.approximate:15,i=He(R("-",[n.args[0],n.args[1]])),a=le.complex?Kt(Qt(i,t)):null,u=a&&a.length>2?function(e,n){const t=e.length-1,r=e[t],s=e.map(e=>e/r),o=(e,n)=>{let r=1,o=0;for(let i=t-1;i>=0;i--)[r,o]=[r*e-o*n+s[i],r*n+o*e];return[r,o]};let i=Array.from({length:t},(e,n)=>[1.3*Math.cos(2*Math.PI*n/t+.4),1.3*Math.sin(2*Math.PI*n/t+.4)]);for(let e=0;e<500;e++){let e=0;if(i=i.map(([n,r],s)=>{let[a,u]=o(n,r);for(let e=0;e<t;e++){if(e===s)continue;const t=n-i[e][0],o=r-i[e][1],l=t*t+o*o;[a,u]=[(a*t+u*o)/l,(u*t-a*o)/l]}return e=Math.max(e,Math.hypot(a,u)),[n-a,r-u]}),e<1e-15)break}const a=e=>Math.abs(e)<1e-12?0:Number(e.toPrecision(n));return i.map(([e,n])=>[a(e),a(n)]).sort((e,n)=>(0!==e[1])-(0!==n[1])||e[0]-n[0]||e[1]-n[1]).map(([e,n])=>{const t=Er(e);if(0===n)return t;const r=R("*",[Er(Math.abs(n)),B("i")]);return 0===e?n<0?R("neg",[r]):r:R(n<0?"-":"+",[t,r])})}(a.map(e=>e.toNumber()),Math.min(e,14)):function(e,n,t){const r=He(R("-",[e.args[0],e.args[1]])),s=Ge(r),o=e=>{try{return $t(xr(s,n,Tr(e)),{digits:30}).number}catch{return NaN}},i=[],a=[];for(let e=-400;e<=400;e++)a.push(Math.sign(e)*(Math.abs(e)/20)**2);for(let e=0;e+1<a.length;e++){let n=a[e],r=a[e+1],s=o(n);const u=o(r);if(Number.isNaN(s)||Number.isNaN(u))continue;if(0===s){i.push(Tr(n));continue}if(s*u>0)continue;for(let e=0;e<200&&r-n>1e-16*Math.abs(n);e++){const e=(n+r)/2,t=o(e);if(Number.isNaN(t))break;s*t<=0?r=e:(n=e,s=t)}const l=(n+r)/2;Math.abs(o(l))<1e-6&&i.push(Tr(Number(l.toPrecision(Math.min(t,15)))))}return i}(n,t,e);for(const e of u)o.numeric?.add(e);return s("solve.numeric","Numeric solutions",["numeric"],n,u.length?u.map(e=>hr(B(t),e)).reduce((e,n)=>e?R("|",[e,n]):n):n,{v:t,count:String(u.length)}),void o.push(...u)}s("solve.unsolved","No exact method",["unsolved"],n,n,{v:t}),i.push(n)}const Er=e=>C(String(e).includes("e")?e.toFixed(20):String(e)),Tr=e=>C(Number.isInteger(e)?String(e):e.toFixed(17));const jr=(e,n)=>R("int",[e,"string"==typeof n?B(n):n]);function Zr(e,n,t,r=0){if(r>6)throw new G("integration went too deep");const s=[],o=e.set.view("integrate"),i=Vt(n,e.set.view("simplify"),{format:e.format});s.push(...i.steps);let a=Je(jr(i.node,t));for(let n=0;n<40;n++){const n=Vt(a,o,{format:e.format});s.push(...n.steps),a=n.node;const t=Y(a,"pre").find(({node:e})=>{return P(n=e)&&"int"===n.op&&2===n.args.length;var n});if(!t)return{node:a,steps:s};const i=zr(e,t.node,r);if(!i)throw new G(`no rule for ∫ ${e.format(t.node.args[0])} d${t.node.args[1].token}`);s.push(...i.steps),a=Je(K(a,t.path,i.node))}throw new G("integration did not finish")}function zr(e,n,t){const[r,s]=n.args,o=s.token,i=He(r),a=function(e,n){const{num:t,den:r}=pr(e),s=sr(t),o=sr(r),i=s.coef.div(o.coef);if(i.isOne||!Yt(e,n))return null;const a=Me([...s.factors.map(e=>Te(e.base,e.exp)),...o.factors.map(e=>Te(e.base,Re(e.exp)))]);return{c:i,rest:a}}(i,o);if(a){const t=R("*",[Ge(de(a.c)),jr(Ge(a.rest),s)]);return{node:t,steps:[e.step("integrate.constant","Take the number out",["split"],n,t,{c:Ge(de(a.c))})]}}const u=Ht(i);if(Ge(u).s!==r.s&&"add"===u.k){const t=jr(Ge(u),s);return{node:t,steps:[e.step("integrate.expand","Multiply out",["expand"],n,t,{})]}}const l=function(e,n){const t=new Map;for(const{node:r}of Y(e,"pre")){if(!P(r))continue;const e="^"===r.op?r.args:"/"===r.op?[r.args[1]]:"der"===r.op||"int"===r.op?[]:1===r.args.length||"root"===r.op?[r.args[r.args.length-1]]:[];for(const r of e){if("sym"===r.type||!nn(r).has(n))continue;const e=Qt(He(r),n);if(!e||1!==Math.max(...e.keys()))continue;const s=e.get(1);Yt(s,n)||ve(s)&&s.q.isZero||t.set(r.s,{node:r,a:s})}}for(const r of t.values()){if(!nn(Dr(e,r.node,B("§"))).has(n))return r}return null}(r,o);if(l){const s="u"===o?"t":"u",i=Dr(r,l.node,B(s));if(!nn(i).has(o)){const r=Zr(e,Je(i),s,t+1),a=Je(xr(r.node,s,l.node)),u=Ge(Ue(He(a),l.a));return{node:u,steps:[e.step("integrate.substitute","Substitute",["substitute"],n,Je(jr(i,s)),{u:B(s),inside:l.node,a:Ge(l.a),v:o}),...r.steps,e.step("integrate.back","Substitute back",["substitute"],r.node,u,{u:B(s),inside:l.node})]}}}const c=function(e,n,t,r){const{num:s,den:o}=pr(t);if(!Yt(o,r))return null;const i=Kt(Qt(s,r)),a=Kt(Qt(o,r));if(!i||!a||a.length<2)return null;const u=He(B(r)),l=e=>Gt(e,r);if(i.length>=a.length){const{q:t,r:s}=function(e,n){const t=Xt(n);let r=Xt(e);const s=t[t.length-1];if(s.isZero)throw new G("division by the zero polynomial");const o=new Array(Math.max(1,r.length-t.length+1)).fill(re.ZERO);for(;r.length>=t.length&&(1!==r.length||!r[0].isZero);){const e=r.length-t.length,n=r[r.length-1].div(s);if(o[e]=n,r=Xt(r.map((r,s)=>s>=e&&s-e<t.length?r.sub(n.mul(t[s-e])):r)),r.length-1<e+t.length-1&&r[r.length-1].isZero)break;if(r.length<t.length)break}return{q:Xt(o),r:r}}(i,a),o=jr(Ge(Ae([l(t),Ue(l(s),l(a))])),B(r));return{node:o,steps:[e.step("integrate.divide","Divide the polynomials",["divide"],n,o,{})]}}const{roots:c,rest:f}=rr(a),p=new Set(c.map(String)).size===c.length;if(!c.length||!p||1!==f.length)return null;const d=(e=>e.length<=1?[re.ZERO]:e.slice(1).map((e,n)=>e.mul(re.of(n+1))))(a),h=c.map(e=>Ue(de(er(i,e).div(er(d,e))),Ae([u,de(e.neg())]))),m=jr(Ge(Ae(h)),B(r));return{node:m,steps:[e.step("integrate.partial-fractions","Partial fractions",["partial-fractions"],n,m,{})]}}(e,n,i,o);return c||function(e,n,t,r,s){if(s>=6)return null;const o=rn(t),i=o.filter(e=>Br(e,r)||!Yt(e,r)),a=o.filter(e=>!i.includes(e));if(1!==a.length)return null;const u=Me(i),l=a[0];if(!Yt(u,r))return null;const c=Ge(l),f=P(c)?c.op:"";let p,d,h;"ln"===f||"arctan"===f||"arcsin"===f?(p=l,d=u):(p=u,d=l);try{h=Zr(e,Ge(d),r,s+1)}catch{return null}const m=He(e.differentiate(Ge(p),r)),g=Me([p,He(h.node)]),v=jr(Ge(Me([m,He(h.node)])),B(r)),b=Je(R("-",[Ge(g),v]));return{node:b,steps:[e.step("integrate.parts","Integration by parts",["parts"],n,b,{u:Ge(p),dv:Ge(d),V:h.node,du:Ge(m),v:r})]}}(e,n,i,o,t)}function Dr(e,n,t){return e.s===n.s?t:P(e)?R(e.op,e.args.map(e=>Dr(e,n,t))):e}const Br=(e,n)=>{const t=Qt(e,n);return Boolean(t)&&[...t.values()].every(e=>!Yt(e,n))&&Math.max(...t.keys())>=1};function Cr(e,n,t,r,s,o){for(const e of[r,s])if(nn(e).has("∞")||/∞|infinity/.test(e.s))throw new G("integrals to infinity need limits, which this CAS does not do yet");if(o&&!nn(r).size&&!nn(s).size){const i=$t(r,{digits:20}).number,a=$t(s,{digits:20}).number,u=[...nn(o)].filter(e=>e!==t);if(!u.length){const[r,s]=i<=a?[i,a]:[a,i];for(const i of function(e,n){const t=[],r={tan:"cos",sec:"cos",csc:"sin",cot:"sin"};return Y(e,"pre").forEach(({node:e})=>{if(!P(e))return;let s=null;"/"===e.op?s=e.args[1]:"^"===e.op&&"num"===e.args[1].type&&e.args[1].value<0||"^"===e.op&&P(e.args[1])&&"neg"===e.args[1].op?s=e.args[0]:r[e.op]&&(s=R(r[e.op],[e.args[0]])),s&&nn(s).has(n)&&!t.some(e=>e.s===s.s)&&t.push(s)}),t}(o,t)){let o=[];try{o=e.solve(R("=",[i,C("0")]),t,{steps:!1}).solutions}catch{continue}for(const i of o){const o=$t(i,{digits:20});if(!Number.isFinite(o.number)||o.im||o.number<r||o.number>s)continue;if(o.number>r&&o.number<s)throw new G(`the integrand has no value at ${t} = ${e.format(i)}, between the limits, so F(b) - F(a) would be wrong`);let a=NaN;try{a=$t(Je(xr(n,t,i)),{digits:15}).number}catch{}if(!Number.isFinite(a))throw new G(`the integral diverges at ${t} = ${e.format(i)}: F has no value at that limit`)}}}for(let e=0;!u.length&&e<=64;e++){const n=i+(a-i)*(e+.5)/65;try{const e=$t(xr(o,t,C(n.toFixed(15))),{digits:15}).number;if(!Number.isFinite(e))throw new G("not finite")}catch(e){throw new G(`the integrand has no value at ${t} = ${n.toPrecision(6)}, between the limits, so F(b) - F(a) would be wrong`)}}}const i=e=>Je(xr(n,t,e)),a=Je(R("-",[i(s),i(r)])),u=R("-",[i(s),i(r)]);return{value:a,step:e.step("integrate.evaluate","Between the limits",["evaluate"],n,u,{a:r,b:s,F:n,v:t})}}const Fr={"=":1,"≠":1,"<":1,">":1,"≤":1,"≥":1,"+":2,"-":2,"±":2,"*":3,"/":3,neg:4,pm:4,"^":5},Vr={pi:"π","≤":"≤","≥":"≥"};function Rr(e){return _r(e).text}function Ur(e,n,t=!1){return e.prec<n||t&&e.prec===n?`(${e.text})`:e.text}const Pr=e=>"op"===e.type?e.op:null,Wr=e=>e.text.startsWith("-"),Lr={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]};function _r(e){if("num"===e.type)return{text:e.token,prec:e.token.startsWith("-")?4:9};if("sym"===e.type)return{text:Vr[e.token]??e.token,prec:9};const n=e.args.map(_r),t=Fr[e.op];switch(e.op){case"+":case"-":case"±":{const r="+"===e.op&&["+","-"].includes(Pr(e.args[1])),s=Wr(n[1])?`(${n[1].text})`:r?n[1].text:Ur(n[1],t,!0);return{text:`${Ur(n[0],t)} ${"±"===e.op?"±":e.op} ${s}`,prec:t}}case"*":{const r=Ur(n[0],t),s=Wr(n[1])?`(${n[1].text})`:"*"===Pr(e.args[1])?n[1].text:Ur(n[1],t,!0);return{text:"num"===e.args[0].type&&"num"!==e.args[1].type&&!/^[\d(-]/.test(s)||"sym"===e.args[1].type&&"i"===e.args[1].token&&!/[\dA-Za-z]$/.test(r)?`${r}${s}`:`${r}·${s}`,prec:t}}case"/":return{text:`${Ur(n[0],t)}/${Ur(n[1],t,!0)}`,prec:t};case"^":return{text:`${Ur(n[0],t+1)}^${Ur(n[1],t)}`,prec:t};case"neg":return{text:`-${Ur(n[0],3)}`,prec:4};case"pm":return{text:`±${Ur(n[0],4)}`,prec:4};case"!":return{text:`${Ur(n[0],9)}!`,prec:6};case"abs":return{text:`|${n[0].text}|`,prec:9};case"root":return{text:`root(${n[0].text}, ${n[1].text})`,prec:9};case"der":return"op"===e.args[1].type&&"="===e.args[1].op?{text:`d/d${n[1].text.split(" = ")[0]} (${n[0].text}) at ${n[1].text}`,prec:1}:{text:`d/d${n[1].text} (${n[0].text})`,prec:6};case"int":return{text:4===n.length?`∫ from ${n[2].text} to ${n[3].text} of ${n[0].text} d${n[1].text}`:`∫ ${n[0].text} d${n[1].text}`,prec:1};case"|":return{text:`${n[0].text} or ${n[1].text}`,prec:0};case"_":return{text:`${Ur(n[0],9)}_${n[1].prec>=9&&!/\s/.test(n[1].text)?n[1].text:`(${n[1].text})`}`,prec:9};case"()":case"[]":case"{}":case"(]":case"[)":return{text:`${Lr[e.op][0]}${n.map(e=>e.text).join(", ")}${Lr[e.op][1]}`,prec:9};case"&":return{text:`${n[0].text} and ${n[1].text}`,prec:0};default:return void 0!==t?{text:`${Ur(n[0],t)} ${e.op} ${Ur(n[1],t,!0)}`,prec:t}:{text:`${e.op.replace(/^\\:?/,"")}(${n.map(e=>e.text).join(", ")})`,prec:9}}}const Hr=['name: Differentiation\n\n# `u v der` means d(u)/dv (MathZetta\'s postfix: mathzetta/docs/postfix.md). Every rule here rewrites one derivative into smaller\n# derivatives, so differentiating always terminates: the expressions sitting\n# under a `D` get strictly smaller at every step.\n#\n# The variable is a slot, not a fixed letter, so these rules work for d/dx,\n# d/dt or anything else. That is what freeOf and dependsOn are for: they ask\n# whether one operand mentions whatever the variable slot bound to.\n#\n# Where two rules share a structure key, requirements keep them apart and\n# priority picks the one that reads better. The constant-multiple rule outranks\n# the product rule for exactly that reason.\n\nrules:\n # ---- the two base cases ----------------------------------------------\n - id: d-constant\n name: Derivative of a constant\n mode: differentiate\n pattern: c v der\n require:\n - [freeOf, c, v]\n output: "0"\n priority: 10\n explain: "{c} does not change when {v} changes, so its rate of change is 0."\n tags: [base]\n\n - id: d-variable\n name: Derivative of the variable\n mode: differentiate\n pattern: u v der\n require:\n - [sameAs, u, v]\n output: "1"\n priority: 10\n explain: "{v} changes exactly as fast as itself, so the rate is 1."\n tags: [base]\n\n # ---- splitting a derivative into smaller ones ------------------------\n - id: d-sum\n name: Sum rule\n mode: differentiate\n pattern: u w + v der\n output: u v der w v der +\n explain: "Differentiate {u} and {w} separately, then add the two results."\n tags: [split]\n\n - id: d-difference\n name: Difference rule\n mode: differentiate\n pattern: u w - v der\n output: u v der w v der -\n explain: "Differentiate {u} and {w} separately, then subtract the second from the first."\n tags: [split]\n\n - id: d-negate\n name: Derivative of a negative\n mode: differentiate\n pattern: u neg v der\n output: u v der neg\n explain: "The minus sign just carries through to the derivative of {u}."\n tags: [split]\n\n - id: d-constant-multiple\n name: Constant multiple rule\n mode: differentiate\n pattern: c u * v der\n commutative: true\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n output: c u v der *\n priority: 5\n explain: "{c} is only a scale factor, so it comes along unchanged while {u} is differentiated."\n tags: [split]\n\n - id: d-constant-divisor\n name: Dividing by a constant\n mode: differentiate\n pattern: u c / v der\n require:\n - [freeOf, c, v]\n output: u v der c /\n priority: 5\n explain: "Dividing by {c} is only a scale factor, so differentiate {u} and keep the division."\n tags: [split]\n\n - id: d-product\n name: Product rule\n mode: differentiate\n pattern: u w * v der\n require:\n - [dependsOn, u, v]\n - [dependsOn, w, v]\n output: u v der w * u w v der * +\n explain: "Differentiate {u} and keep {w}, then keep {u} and differentiate {w}, and add the two."\n tags: [split]\n\n - id: d-quotient\n name: Quotient rule\n mode: differentiate\n pattern: u w / v der\n output: u v der w * u w v der * - w 2 ^ /\n explain: "Bottom times the derivative of the top, minus top times the derivative of the bottom, all over {w} squared."\n tags: [split]\n\n # ---- powers -----------------------------------------------------------\n - id: d-power-of-variable\n name: Power rule\n mode: differentiate\n pattern: u n ^ v der\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n output: n u n 1 - ^ *\n fold: true\n priority: 6\n explain: "Bring the {n} down in front and drop the power by one."\n tags: [power]\n\n - id: d-power-chain\n name: Power rule with the chain rule\n mode: differentiate\n pattern: u n ^ v der\n require:\n - [freeOf, n, v]\n - [dependsOn, u, v]\n output: n u n 1 - ^ * u v der *\n fold: true\n explain: "Bring the {n} down and drop the power by one, then multiply by the derivative of {u}."\n tags: [power, chain]\n\n - id: d-exponential-base\n name: Derivative of a constant to a power\n mode: differentiate\n pattern: a u ^ v der\n require:\n - [freeOf, a, v]\n - [dependsOn, u, v]\n output: a u ^ a ln * u v der *\n explain: "A constant base gives itself back, multiplied by the natural log of {a} and the derivative of {u}."\n tags: [power, chain]\n\n # ---- the standard functions, each with its chain-rule factor ---------\n # e^u is `=e u ^`: the base is the literal symbol e. Outranks the general\n # a^u rule (which would give e^u · ln e · u\').\n - id: d-exp\n name: Derivative of e to a power\n mode: differentiate\n pattern: =e u ^ v der\n require:\n - [dependsOn, u, v]\n output: =e u ^ u v der *\n priority: 7\n explain: "e to a power is its own derivative, times the derivative of {u}."\n tags: [chain]\n\n - id: d-ln\n name: Derivative of a natural log\n mode: differentiate\n pattern: u ln v der\n output: u v der u /\n explain: "The derivative of {u} over {u} itself."\n tags: [chain]\n\n - id: d-sqrt\n name: Derivative of a square root\n mode: differentiate\n pattern: u sqrt v der\n output: u v der 2 u sqrt * /\n explain: "The derivative of {u}, over twice the square root of {u}."\n tags: [chain]\n\n - id: d-sin\n name: Derivative of sine\n mode: differentiate\n pattern: u sin v der\n output: u cos u v der *\n explain: "Sine differentiates to cosine, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-cos\n name: Derivative of cosine\n mode: differentiate\n pattern: u cos v der\n output: u sin u v der * neg\n explain: "Cosine differentiates to minus sine, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-tan\n name: Derivative of tangent\n mode: differentiate\n pattern: u tan v der\n output: u v der u cos 2 ^ /\n explain: "The derivative of {u}, over cosine squared of {u}."\n tags: [chain, trig]\n\n # ---- the rest of the standard functions -----------------------------\n - id: d-csc\n name: Derivative of cosecant\n mode: differentiate\n pattern: u csc v der\n output: u csc u cot * u v der * neg\n explain: "Cosecant differentiates to minus cosecant times cotangent, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-sec\n name: Derivative of secant\n mode: differentiate\n pattern: u sec v der\n output: u sec u tan * u v der *\n explain: "Secant differentiates to secant times tangent, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-cot\n name: Derivative of cotangent\n mode: differentiate\n pattern: u cot v der\n output: u v der u sin 2 ^ / neg\n explain: "Minus the derivative of {u}, over sine squared of {u}."\n tags: [chain, trig]\n\n - id: d-arcsin\n name: Derivative of arcsine\n mode: differentiate\n pattern: u arcsin v der\n output: u v der 1 u 2 ^ - sqrt /\n explain: "The derivative of {u}, over the square root of 1 minus {u} squared."\n tags: [chain, trig]\n\n - id: d-arccos\n name: Derivative of arccosine\n mode: differentiate\n pattern: u arccos v der\n output: u v der 1 u 2 ^ - sqrt / neg\n explain: "Minus the derivative of {u}, over the square root of 1 minus {u} squared."\n tags: [chain, trig]\n\n - id: d-arctan\n name: Derivative of arctangent\n mode: differentiate\n pattern: u arctan v der\n output: u v der 1 u 2 ^ + /\n explain: "The derivative of {u}, over 1 plus {u} squared."\n tags: [chain, trig]\n\n - id: d-sinh\n name: Derivative of hyperbolic sine\n mode: differentiate\n pattern: u sinh v der\n output: u cosh u v der *\n explain: "Hyperbolic sine differentiates to hyperbolic cosine, times the derivative of {u}."\n tags: [chain, hyperbolic]\n\n - id: d-cosh\n name: Derivative of hyperbolic cosine\n mode: differentiate\n pattern: u cosh v der\n output: u sinh u v der *\n explain: "Hyperbolic cosine differentiates to hyperbolic sine — no minus sign, unlike cosine — times the derivative of {u}."\n tags: [chain, hyperbolic]\n\n - id: d-tanh\n name: Derivative of hyperbolic tangent\n mode: differentiate\n pattern: u tanh v der\n output: u v der u cosh 2 ^ /\n explain: "The derivative of {u}, over hyperbolic cosine squared of {u}."\n tags: [chain, hyperbolic]\n\n - id: d-arcsinh\n name: Derivative of inverse hyperbolic sine\n mode: differentiate\n pattern: u arcsinh v der\n output: u v der u 2 ^ 1 + sqrt /\n explain: "The derivative of {u}, over the square root of {u} squared plus 1."\n tags: [chain, hyperbolic]\n\n - id: d-arccosh\n name: Derivative of inverse hyperbolic cosine\n mode: differentiate\n pattern: u arccosh v der\n output: u v der u 2 ^ 1 - sqrt /\n explain: "The derivative of {u}, over the square root of {u} squared minus 1."\n tags: [chain, hyperbolic]\n\n - id: d-arctanh\n name: Derivative of inverse hyperbolic tangent\n mode: differentiate\n pattern: u arctanh v der\n output: u v der 1 u 2 ^ - /\n explain: "The derivative of {u}, over 1 minus {u} squared."\n tags: [chain, hyperbolic]\n\n # log base a: `a u log` in MathZetta\'s postfix\n - id: d-log\n name: Derivative of a logarithm\n mode: differentiate\n pattern: a u log v der\n require:\n - [freeOf, a, v]\n output: u v der u a ln * /\n explain: "The derivative of {u}, over {u} times the natural log of {a}."\n tags: [chain]\n\n - id: d-abs\n name: Derivative of an absolute value\n mode: differentiate\n pattern: u abs v der\n output: u u abs / u v der *\n explain: "The absolute value keeps the sign of {u}: {u} over its absolute value, times the derivative of {u}."\n tags: [chain]\n\n # n-th root: `n u root`\n - id: d-root\n name: Derivative of a root\n mode: differentiate\n pattern: n u root v der\n require:\n - [freeOf, n, v]\n output: u v der n n u root n 1 - ^ * /\n fold: true\n explain: "The derivative of {u}, over {n} times the {n}th root of {u} to the power {n} minus 1."\n tags: [chain]\n','name: More derivatives\n\n# Derivative rules the CAS adds to rules/calculus.yaml (which calcvidnew also uses).\n\nrules:\n - id: d-general-power\n name: A power with the variable in both places\n mode: differentiate\n pattern: u w ^ v der\n require:\n - [dependsOn, u, v]\n - [dependsOn, w, v]\n output: u w ^ w v der u ln * w u v der * u / + *\n explain: "Write {u}^{w} as e^({w} ln {u}) and use the chain rule: the derivative is {u}^{w} times the derivative of {w} ln {u}."\n tags: [chain]\n','name: Integrals\n\n# mode: integrate. `f v 2 int` is ∫ f dv (MathZetta\'s postfix; the 2 counts f and v).\n# Each rule turns one integral into smaller ones, or into an answer. The CAS also\n# tries, when no rule fits: multiplying out, a linear substitution (∫ f(ax + b) dx\n# from the rule for ∫ f(u) du), and integration by parts for polynomial × e^, sin,\n# cos, ln, arctan. Definite integrals are the antiderivative between the limits.\n#\n# Patterns see the normal form: 1/x is "1 x /", x^-2 is "1 x 2 ^ /", √x is "x sqrt",\n# 1/√(1 - x²) is "1 x 2 ^ neg 1 + sqrt /".\n\nrules:\n # ---- splitting -----------------------------------------------------------\n - id: i-sum\n name: Sum rule\n mode: integrate\n pattern: u w + v 2 int\n output: u v 2 int w v 2 int +\n explain: "Integrate {u} and {w} separately, and add."\n tags: [split]\n\n - id: i-difference\n name: Difference rule\n mode: integrate\n pattern: u w - v 2 int\n output: u v 2 int w v 2 int -\n explain: "Integrate {u} and {w} separately, and subtract."\n tags: [split]\n\n - id: i-negate\n name: A minus sign\n mode: integrate\n pattern: u neg v 2 int\n output: u v 2 int neg\n explain: "The minus sign comes out of the integral."\n tags: [split]\n\n - id: i-constant-multiple\n name: Constant multiple\n mode: integrate\n pattern: c u * v 2 int\n commutative: true\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n output: c u v 2 int *\n priority: 5\n explain: "{c} doesn\'t change with {v}, so it comes out of the integral."\n tags: [split]\n\n - id: i-constant-divisor\n name: Dividing by a constant\n mode: integrate\n pattern: u c / v 2 int\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n output: u v 2 int c /\n priority: 5\n explain: "Dividing by {c} comes out of the integral."\n tags: [split]\n\n - id: i-constant-over\n name: A constant over something\n mode: integrate\n pattern: c u / v 2 int\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n when:\n c: [notOne]\n output: c 1 u / v 2 int *\n priority: 4\n explain: "{c} comes out of the integral, leaving ∫ 1/{u}."\n tags: [split]\n\n # ---- the table -----------------------------------------------------------\n - id: i-constant\n name: Integral of a constant\n mode: integrate\n pattern: c v 2 int\n require:\n - [freeOf, c, v]\n output: c v *\n priority: 10\n explain: "A constant {c} integrates to {c}·{v}."\n tags: [base]\n\n - id: i-variable\n name: Integral of the variable\n mode: integrate\n pattern: u v 2 int\n require:\n - [sameAs, u, v]\n output: v 2 ^ 2 /\n priority: 10\n explain: "∫ {v} d{v} = {v}²/2."\n tags: [base]\n\n - id: i-power\n name: Power rule\n mode: integrate\n pattern: u n ^ v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n when:\n n: [notMinusOne]\n output: v n 1 + ^ n 1 + /\n explain: "Add 1 to the power and divide by the new power: {result}."\n tags: [power]\n\n - id: i-reciprocal\n name: Integral of 1/x\n mode: integrate\n pattern: 1 u / v 2 int\n require:\n - [sameAs, u, v]\n output: v abs ln\n explain: "∫ 1/{v} d{v} = ln|{v}| (the power rule can\'t divide by 0 here)."\n tags: [log]\n\n - id: i-reciprocal-power\n name: Power rule (a power below)\n mode: integrate\n pattern: 1 u n ^ / v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n when:\n n: [notOne]\n output: v 1 n - ^ 1 n - /\n explain: "1/{v}^{n} is {v}^(-{n}): add 1 to the power and divide by it."\n tags: [power]\n\n - id: i-sqrt\n name: Integral of a square root\n mode: integrate\n pattern: u sqrt v 2 int\n require:\n - [sameAs, u, v]\n output: 2 v 3 2 / ^ * 3 /\n explain: "√{v} is {v}^(1/2): add 1 to the power and divide by 3/2."\n tags: [power]\n\n - id: i-reciprocal-sqrt\n name: Integral of 1/√x\n mode: integrate\n pattern: 1 u sqrt / v 2 int\n require:\n - [sameAs, u, v]\n output: 2 v sqrt *\n explain: "1/√{v} is {v}^(-1/2): add 1 to the power and divide by 1/2."\n tags: [power]\n\n - id: i-root\n name: Integral of a root\n mode: integrate\n pattern: n u root v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n output: v 1 n / 1 + ^ 1 n / 1 + /\n explain: "The {n}th root of {v} is {v}^(1/{n}): add 1 to the power and divide by it."\n tags: [power]\n\n - id: i-exp\n name: Integral of e^x\n mode: integrate\n pattern: =e u ^ v 2 int\n require:\n - [sameAs, u, v]\n output: =e v ^\n explain: "e^{v} is its own integral."\n tags: [exp]\n\n - id: i-exponential\n name: Integral of a^x\n mode: integrate\n pattern: a u ^ v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, a, v]\n output: a v ^ a ln /\n explain: "∫ {a}^{v} d{v} = {a}^{v} / ln {a}."\n tags: [exp]\n\n - id: i-ln\n name: Integral of ln x\n mode: integrate\n pattern: u ln v 2 int\n require:\n - [sameAs, u, v]\n output: v v ln * v -\n explain: "By parts: ∫ ln {v} d{v} = {v} ln {v} - {v}."\n tags: [log]\n\n - { id: i-sin, name: Integral of sin, mode: integrate, pattern: u sin v 2 int, require: [[sameAs, u, v]], output: v cos neg, tags: [trig], explain: "The derivative of -cos {v} is sin {v}." }\n - { id: i-cos, name: Integral of cos, mode: integrate, pattern: u cos v 2 int, require: [[sameAs, u, v]], output: v sin, tags: [trig], explain: "The derivative of sin {v} is cos {v}." }\n - { id: i-tan, name: Integral of tan, mode: integrate, pattern: u tan v 2 int, require: [[sameAs, u, v]], output: v cos abs ln neg, tags: [trig], explain: "tan = sin/cos, and -ln|cos {v}| differentiates to it." }\n - { id: i-sec-squared, name: Integral of sec², mode: integrate, pattern: 1 u cos 2 ^ / v 2 int, require: [[sameAs, u, v]], output: v tan, tags: [trig], explain: "The derivative of tan {v} is 1/cos²{v}." }\n - { id: i-sec-squared-written, name: Integral of sec², mode: integrate, pattern: u sec 2 ^ v 2 int, require: [[sameAs, u, v]], output: v tan, tags: [trig], explain: "The derivative of tan {v} is sec²{v}." }\n - { id: i-csc-squared, name: Integral of csc², mode: integrate, pattern: 1 u sin 2 ^ / v 2 int, require: [[sameAs, u, v]], output: v cot neg, tags: [trig], explain: "The derivative of -cot {v} is 1/sin²{v}." }\n - { id: i-sin-squared, name: Integral of sin², mode: integrate, pattern: u sin 2 ^ v 2 int, require: [[sameAs, u, v]], output: v 2 / 2 v * sin 4 / -, tags: [trig], explain: "sin²{v} = (1 - cos 2{v})/2, which integrates term by term." }\n - { id: i-cos-squared, name: Integral of cos², mode: integrate, pattern: u cos 2 ^ v 2 int, require: [[sameAs, u, v]], output: v 2 / 2 v * sin 4 / +, tags: [trig], explain: "cos²{v} = (1 + cos 2{v})/2, which integrates term by term." }\n - { id: i-sinh, name: Integral of sinh, mode: integrate, pattern: u sinh v 2 int, require: [[sameAs, u, v]], output: v cosh, tags: [trig], explain: "The derivative of cosh {v} is sinh {v}." }\n - { id: i-cosh, name: Integral of cosh, mode: integrate, pattern: u cosh v 2 int, require: [[sameAs, u, v]], output: v sinh, tags: [trig], explain: "The derivative of sinh {v} is cosh {v}." }\n - { id: i-arctan, name: Integral of 1/(1 + x²), mode: integrate, pattern: 1 u 2 ^ 1 + / v 2 int, require: [[sameAs, u, v]], output: v arctan, tags: [trig], explain: "The derivative of arctan {v} is 1/(1 + {v}²)." }\n - { id: i-arcsin, name: Integral of 1/√(1 - x²), mode: integrate, pattern: 1 u 2 ^ neg 1 + sqrt / v 2 int, require: [[sameAs, u, v]], output: v arcsin, tags: [trig], explain: "The derivative of arcsin {v} is 1/√(1 - {v}²)." }\n','name: Values and identities\n\n# The CAS\'s simplify rules (mode: simplify). They see expressions in normal form\n# (src/cas/form.js), as drawn: x/2, 2x - 3, -x, √x is "x sqrt",\n# ∛x is "3 x root", π/6 is "=pi 6 /", 2π/3 is "2 =pi * 3 /", e^x is "=e x ^".\n#\n# - a word is a slot (u, v, n …); a fixed symbol is written =pi, =e\n# - a number is itself; "1 2 /" is ½\n# - arithmetic (2 + 3, x + x, √8 = 2√2) is done for you before and after every rule\n# - a rule for a sum or product of two parts also fires on any two parts of a longer one\n# - tags pick what a step list shows (steps: \'brief\' hides value, identity, tidy …)\n#\n# To change one: copy it into a file of your own with the same id and edit it;\n# to turn one off: give its id with enabled: false. createCAS({ rules: [yours] }).\n\nrules:\n # ---- logs and exponentials -------------------------------------------\n - id: ln-one\n name: Log of 1\n pattern: 1 ln\n output: "0"\n explain: "e^0 = 1, so ln 1 = 0."\n tags: [value]\n\n - id: ln-e\n name: Log of e\n pattern: =e ln\n output: "1"\n explain: "e^1 = e, so ln e = 1."\n tags: [value]\n\n - id: ln-exp\n name: Log undoes e to a power\n pattern: =e u ^ ln\n output: u\n explain: "ln and e^ undo each other: ln(e^{u}) = {u}."\n tags: [inverse]\n\n - id: exp-ln\n name: e to a power undoes the log\n pattern: =e u ln ^\n output: u\n explain: "e^ and ln undo each other: e^(ln {u}) = {u} (for {u} > 0)."\n tags: [inverse]\n\n - id: exp-multiple-ln\n name: A multiple of a log in a power\n pattern: =e n u ln * ^\n when:\n n: [isRational]\n output: u n ^\n explain: "e^({n} ln {u}) = (e^(ln {u}))^{n} = {result}."\n tags: [inverse]\n\n - id: log-same-base\n name: Log of its own base\n pattern: b b log\n output: "1"\n explain: "{b}^1 = {b}, so the log of {b} to base {b} is 1."\n tags: [value]\n\n - id: log-of-power\n name: Log undoes a power of its base\n pattern: b b u ^ log\n output: u\n explain: "log base {b} and {b}^ undo each other."\n tags: [inverse]\n\n - id: power-of-log\n name: A power undoes the log to its base\n pattern: b b u log ^\n output: u\n explain: "{b}^(log base {b} of {u}) = {u}."\n tags: [inverse]\n\n # ---- roots and absolute value --------------------------------------------\n - id: sqrt-of-square\n name: Square root of a square\n pattern: u 2 ^ sqrt\n output: u abs\n explain: "√({u}²) is the size of {u}, whatever its sign: |{u}|."\n tags: [identity]\n\n - id: abs-squared\n name: Absolute value squared\n pattern: u abs 2 ^\n output: u 2 ^\n explain: "Squaring removes the sign anyway: |{u}|² = {u}²."\n tags: [identity]\n\n - id: abs-of-abs\n name: Absolute value twice\n pattern: u abs abs\n output: u abs\n explain: "|{u}| is never negative, so its absolute value is itself."\n tags: [identity]\n\n - id: abs-positive\n name: Absolute value of a positive number\n pattern: u abs\n when:\n u: [isPositiveConstant]\n output: u\n explain: "{u} is positive, so |{u}| = {u}."\n tags: [value]\n\n - id: abs-negative\n name: Absolute value of a negative number\n pattern: u abs\n when:\n u: [isNegativeConstant]\n output: u neg\n explain: "{u} is negative, so |{u}| = -({u})."\n tags: [value]\n\n - id: abs-of-exp\n name: e to a power is positive\n pattern: =e u ^ abs\n output: =e u ^\n explain: "e to any power is positive, so the absolute value changes nothing."\n tags: [identity]\n\n # ---- trigonometry: signs and turns ---------------------------------------\n - id: sin-odd\n name: Sine of a negative angle\n pattern: u sin\n when:\n u: [hasMinusSign]\n output: u neg sin neg\n explain: "sin(-θ) = -sin θ."\n tags: [symmetry]\n\n - id: cos-even\n name: Cosine of a negative angle\n pattern: u cos\n when:\n u: [hasMinusSign]\n output: u neg cos\n explain: "cos(-θ) = cos θ."\n tags: [symmetry]\n\n - id: tan-odd\n name: Tangent of a negative angle\n pattern: u tan\n when:\n u: [hasMinusSign]\n output: u neg tan neg\n explain: "tan(-θ) = -tan θ."\n tags: [symmetry]\n\n - id: sin-full-turn\n name: A full turn\n pattern: u sin\n when:\n u: [[piMultipleAtLeast, 2]]\n output: u 2 =pi * - sin\n explain: "Turning a full 2π brings you back: sin({u}) = sin({u} - 2π)."\n tags: [symmetry]\n\n - id: cos-full-turn\n name: A full turn\n pattern: u cos\n when:\n u: [[piMultipleAtLeast, 2]]\n output: u 2 =pi * - cos\n explain: "Turning a full 2π brings you back: cos({u}) = cos({u} - 2π)."\n tags: [symmetry]\n\n - id: tan-half-turn\n name: Tangent repeats every π\n pattern: u tan\n when:\n u: [[piMultipleAtLeast, 1]]\n output: u =pi - tan\n explain: "tan repeats every π: tan({u}) = tan({u} - π)."\n tags: [symmetry]\n\n - id: sin-half-turn\n name: A half turn\n pattern: u sin\n when:\n u: [[piMultipleAbove, 1], [piMultipleBelow, 2]]\n output: u =pi - sin neg\n explain: "Half a turn flips the sign: sin({u}) = -sin({u} - π)."\n tags: [symmetry]\n\n - id: cos-half-turn\n name: A half turn\n pattern: u cos\n when:\n u: [[piMultipleAbove, 1], [piMultipleBelow, 2]]\n output: u =pi - cos neg\n explain: "Half a turn flips the sign: cos({u}) = -cos({u} - π)."\n tags: [symmetry]\n\n - id: sin-second-quarter\n name: The second quarter turn\n pattern: u sin\n when:\n u: [[piMultipleAbove, 1/2], [piMultipleAtMost, 1]]\n output: =pi u - sin\n explain: "sin({u}) = sin(π - {u})."\n tags: [symmetry]\n\n - id: cos-second-quarter\n name: The second quarter turn\n pattern: u cos\n when:\n u: [[piMultipleAbove, 1/2], [piMultipleAtMost, 1]]\n output: =pi u - cos neg\n explain: "cos({u}) = -cos(π - {u})."\n tags: [symmetry]\n\n - id: tan-second-quarter\n name: The second quarter turn\n pattern: u tan\n when:\n u: [[piMultipleAbove, 1/2], [piMultipleBelow, 1]]\n output: =pi u - tan neg\n explain: "tan({u}) = -tan(π - {u})."\n tags: [symmetry]\n\n # ---- trigonometry: the standard angles -------------------------------------\n - { id: sin-0, name: Sine of 0, pattern: 0 sin, output: "0", tags: [value], explain: "sin 0 = 0." }\n - { id: sin-pi-6, name: Sine of π/6, pattern: =pi 6 / sin, output: 1 2 /, tags: [value], explain: "sin(π/6) = 1/2." }\n - { id: sin-pi-4, name: Sine of π/4, pattern: =pi 4 / sin, output: 2 sqrt 2 /, tags: [value], explain: "sin(π/4) = √2/2." }\n - { id: sin-pi-3, name: Sine of π/3, pattern: =pi 3 / sin, output: 3 sqrt 2 /, tags: [value], explain: "sin(π/3) = √3/2." }\n - { id: sin-pi-2, name: Sine of π/2, pattern: =pi 2 / sin, output: "1", tags: [value], explain: "sin(π/2) = 1." }\n - { id: sin-pi, name: Sine of π, pattern: =pi sin, output: "0", tags: [value], explain: "sin π = 0." }\n - { id: cos-0, name: Cosine of 0, pattern: 0 cos, output: "1", tags: [value], explain: "cos 0 = 1." }\n - { id: cos-pi-6, name: Cosine of π/6, pattern: =pi 6 / cos, output: 3 sqrt 2 /, tags: [value], explain: "cos(π/6) = √3/2." }\n - { id: cos-pi-4, name: Cosine of π/4, pattern: =pi 4 / cos, output: 2 sqrt 2 /, tags: [value], explain: "cos(π/4) = √2/2." }\n - { id: cos-pi-3, name: Cosine of π/3, pattern: =pi 3 / cos, output: 1 2 /, tags: [value], explain: "cos(π/3) = 1/2." }\n - { id: cos-pi-2, name: Cosine of π/2, pattern: =pi 2 / cos, output: "0", tags: [value], explain: "cos(π/2) = 0." }\n - { id: cos-pi, name: Cosine of π, pattern: =pi cos, output: "-1", tags: [value], explain: "cos π = -1." }\n - { id: tan-0, name: Tangent of 0, pattern: 0 tan, output: "0", tags: [value], explain: "tan 0 = 0." }\n - { id: tan-pi-6, name: Tangent of π/6, pattern: =pi 6 / tan, output: 3 sqrt 3 /, tags: [value], explain: "tan(π/6) = √3/3." }\n - { id: tan-pi-4, name: Tangent of π/4, pattern: =pi 4 / tan, output: "1", tags: [value], explain: "tan(π/4) = 1." }\n - { id: tan-pi-3, name: Tangent of π/3, pattern: =pi 3 / tan, output: 3 sqrt, tags: [value], explain: "tan(π/3) = √3." }\n - { id: arcsin-0, name: Arcsine of 0, pattern: 0 arcsin, output: "0", tags: [value], explain: "sin 0 = 0, so arcsin 0 = 0." }\n - { id: arcsin-half, name: Arcsine of 1/2, pattern: 1 2 / arcsin, output: =pi 6 /, tags: [value], explain: "sin(π/6) = 1/2, so arcsin(1/2) = π/6." }\n - { id: arcsin-1, name: Arcsine of 1, pattern: 1 arcsin, output: =pi 2 /, tags: [value], explain: "sin(π/2) = 1, so arcsin 1 = π/2." }\n - { id: arccos-0, name: Arccosine of 0, pattern: 0 arccos, output: =pi 2 /, tags: [value], explain: "cos(π/2) = 0, so arccos 0 = π/2." }\n - { id: arccos-half, name: Arccosine of 1/2, pattern: 1 2 / arccos, output: =pi 3 /, tags: [value], explain: "cos(π/3) = 1/2, so arccos(1/2) = π/3." }\n - { id: arccos-1, name: Arccosine of 1, pattern: 1 arccos, output: "0", tags: [value], explain: "cos 0 = 1, so arccos 1 = 0." }\n - { id: arccos-minus-1, name: Arccosine of -1, pattern: -1 arccos, output: =pi, tags: [value], explain: "cos π = -1, so arccos(-1) = π." }\n - { id: arctan-0, name: Arctangent of 0, pattern: 0 arctan, output: "0", tags: [value], explain: "tan 0 = 0, so arctan 0 = 0." }\n - { id: arctan-1, name: Arctangent of 1, pattern: 1 arctan, output: =pi 4 /, tags: [value], explain: "tan(π/4) = 1, so arctan 1 = π/4." }\n - { id: sinh-0, name: sinh of 0, pattern: 0 sinh, output: "0", tags: [value], explain: "sinh 0 = 0." }\n - { id: cosh-0, name: cosh of 0, pattern: 0 cosh, output: "1", tags: [value], explain: "cosh 0 = 1." }\n - { id: tanh-0, name: tanh of 0, pattern: 0 tanh, output: "0", tags: [value], explain: "tanh 0 = 0." }\n\n - { id: arctan-sqrt3, name: Arctangent of √3, pattern: 3 sqrt arctan, output: =pi 3 /, tags: [value], explain: "tan(π/3) = √3, so arctan √3 = π/3." }\n - { id: arctan-sqrt3-over-3, name: Arctangent of √3/3, pattern: 3 sqrt 3 / arctan, output: =pi 6 /, tags: [value], explain: "tan(π/6) = √3/3, so arctan(√3/3) = π/6." }\n\n # atan2(y, x): the angle of the point (x, y), in (-π, π]\n - id: atan2-right\n name: The angle of a point to the right\n pattern: y x atan2\n when:\n x: [isPositiveConstant]\n output: y x / arctan\n explain: "For x > 0, atan2(y, x) = arctan(y/x)."\n tags: [value]\n - id: atan2-left-up\n name: The angle of a point to the left\n pattern: y x atan2\n when:\n x: [isNegativeConstant]\n y: [isPositiveConstant]\n output: y x / arctan =pi +\n explain: "For x < 0 and y > 0, atan2(y, x) = arctan(y/x) + π."\n tags: [value]\n - id: atan2-left-down\n name: The angle of a point to the left\n pattern: y x atan2\n when:\n x: [isNegativeConstant]\n y: [isNegativeConstant]\n output: y x / arctan =pi -\n explain: "For x < 0 and y < 0, atan2(y, x) = arctan(y/x) - π."\n tags: [value]\n - { id: atan2-negative-axis, name: The angle of a point on the negative axis, pattern: 0 x atan2, when: { x: [isNegativeConstant] }, output: =pi, tags: [value], explain: "A point on the negative x-axis is at angle π." }\n - { id: atan2-up, name: Straight up, pattern: y 0 atan2, when: { y: [isPositiveConstant] }, output: =pi 2 /, tags: [value], explain: "A point straight up is at angle π/2." }\n - { id: atan2-down, name: Straight down, pattern: y 0 atan2, when: { y: [isNegativeConstant] }, output: =pi 2 / neg, tags: [value], explain: "A point straight down is at angle -π/2." }\n\n # the odd inverses take the sign out; arccos(-u) = π - arccos u\n - id: arcsin-odd\n name: Arcsine of a negative\n pattern: u arcsin\n when:\n u: [hasMinusSign]\n output: u neg arcsin neg\n explain: "arcsin(-x) = -arcsin x."\n tags: [symmetry]\n\n - id: arctan-odd\n name: Arctangent of a negative\n pattern: u arctan\n when:\n u: [hasMinusSign]\n output: u neg arctan neg\n explain: "arctan(-x) = -arctan x."\n tags: [symmetry]\n\n - id: arccos-negative\n name: Arccosine of a negative\n pattern: u arccos\n when:\n u: [hasMinusSign]\n output: =pi u neg arccos -\n explain: "arccos(-x) = π - arccos x."\n tags: [symmetry]\n\n # ---- trigonometry: identities --------------------------------------------\n - id: pythagorean\n name: sin² + cos² = 1\n pattern: u sin 2 ^ u cos 2 ^ +\n commutative: true\n output: "1"\n explain: "sin²{u} + cos²{u} = 1 for every angle."\n tags: [identity]\n\n - id: pythagorean-multiple\n name: sin² + cos² = 1\n pattern: a u sin 2 ^ * a u cos 2 ^ * +\n commutative: true\n output: a\n explain: "{a}·sin²{u} + {a}·cos²{u} = {a}(sin²{u} + cos²{u}) = {a}."\n tags: [identity]\n\n - id: one-minus-sin-squared\n name: 1 - sin² = cos²\n pattern: u sin 2 ^ neg 1 +\n output: u cos 2 ^\n explain: "1 - sin²{u} = cos²{u}."\n tags: [identity]\n\n - id: one-minus-cos-squared\n name: 1 - cos² = sin²\n pattern: u cos 2 ^ neg 1 +\n output: u sin 2 ^\n explain: "1 - cos²{u} = sin²{u}."\n tags: [identity]\n\n - id: sin-over-cos\n name: sin/cos is tan\n pattern: u sin u cos /\n output: u tan\n explain: "sin {u} / cos {u} = tan {u}."\n tags: [identity]\n\n - id: cos-over-sin\n name: cos/sin is cot\n pattern: u cos u sin /\n output: u cot\n explain: "cos {u} / sin {u} = cot {u}."\n tags: [identity]\n\n - id: sin-arcsin\n name: sin undoes arcsin\n pattern: u arcsin sin\n output: u\n explain: "sin(arcsin {u}) = {u}."\n tags: [inverse]\n\n - id: cos-arccos\n name: cos undoes arccos\n pattern: u arccos cos\n output: u\n explain: "cos(arccos {u}) = {u}."\n tags: [inverse]\n\n - id: tan-arctan\n name: tan undoes arctan\n pattern: u arctan tan\n output: u\n explain: "tan(arctan {u}) = {u}."\n tags: [inverse]\n\n - id: cosh-squared-minus-sinh-squared\n name: cosh² - sinh² = 1\n pattern: u cosh 2 ^ u sinh 2 ^ -\n output: "1"\n explain: "cosh²{u} - sinh²{u} = 1."\n tags: [identity]\n\n # ---- logs: opt-in rewrites (run with cas.rewrite(x, \'expand-log\') or \'combine-log\') ----\n - id: ln-product\n name: Log of a product\n mode: expand-log\n pattern: a b * ln\n output: a ln b ln +\n explain: "ln({a}·{b}) = ln {a} + ln {b} (for positive {a}, {b})."\n tags: [log]\n\n - id: ln-quotient\n name: Log of a quotient\n mode: expand-log\n pattern: a b / ln\n output: a ln b ln -\n explain: "ln({a}/{b}) = ln {a} - ln {b} (for positive {a}, {b})."\n tags: [log]\n\n - id: ln-power\n name: Log of a power\n mode: expand-log\n pattern: a n ^ ln\n output: n a ln *\n explain: "ln({a}^{n}) = {n}·ln {a} (for positive {a})."\n tags: [log]\n\n - id: ln-root\n name: Log of a square root\n mode: expand-log\n pattern: a sqrt ln\n output: a ln 2 /\n explain: "ln √{a} = ½ ln {a}."\n tags: [log]\n\n - id: ln-sum-combine\n name: Sum of logs\n mode: combine-log\n pattern: a ln b ln +\n commutative: true\n output: a b * ln\n explain: "ln {a} + ln {b} = ln({a}·{b})."\n tags: [log]\n\n - id: ln-difference-combine\n name: Difference of logs\n mode: combine-log\n pattern: a ln b ln -\n output: a b / ln\n explain: "ln {a} - ln {b} = ln({a}/{b})."\n tags: [log]\n\n - id: ln-multiple-combine\n name: A multiple of a log\n mode: combine-log\n pattern: n a ln *\n when:\n n: [isRational]\n output: a n ^ ln\n explain: "{n}·ln {a} = ln({a}^{n})."\n tags: [log]\n','name: Solving by undoing\n\n# mode: isolate. Each rule undoes the outermost function on the side with the\n# unknown: ln u = r → u = e^r. The predicates hasVariable and freeOfVariable mean\n# "mentions / doesn\'t mention the unknown being solved for".\n#\n# The CAS does the rest itself: it moves terms without the unknown to the other\n# side, divides by a coefficient, and when the unknown appears in several places\n# it uses the polynomial methods (factoring, the quadratic formula) or splits a\n# product equal to 0. Every answer is checked in the original equation, so a\n# rule may give extra candidates (squaring both sides does): the wrong ones are\n# dropped, with a step saying so.\n#\n# An output can give several answers: `pm` (±) splits into two, and so does\n# `|` (or): "u r arcsin = u =pi r arcsin - = |".\n\nrules:\n - id: iso-swap\n name: Unknown on the left\n mode: isolate\n pattern: l r =\n when:\n l: [freeOfVariable]\n r: [hasVariable]\n output: r l =\n priority: 20\n explain: "Swap the sides so the unknown is on the left."\n tags: [tidy]\n\n - id: iso-ln\n name: Undo the log\n mode: isolate\n pattern: u ln r =\n when:\n u: [hasVariable]\n output: u =e r ^ =\n explain: "Raise e to each side: e^(ln {u}) = {u}."\n tags: [inverse]\n\n - id: iso-log\n name: Undo the log\n mode: isolate\n pattern: b u log r =\n when:\n u: [hasVariable]\n b: [freeOfVariable]\n output: u b r ^ =\n explain: "Raise {b} to each side: {b}^(log base {b} of {u}) = {u}."\n tags: [inverse]\n\n - id: iso-exp\n name: Undo e to a power\n mode: isolate\n pattern: =e u ^ r =\n when:\n u: [hasVariable]\n output: u r ln =\n explain: "Take ln of each side: ln(e^{u}) = {u}."\n tags: [inverse]\n\n - id: iso-exponential\n name: Undo a power of a number\n mode: isolate\n pattern: b u ^ r =\n when:\n u: [hasVariable]\n b: [freeOfVariable]\n output: u b r log =\n explain: "Take the log to base {b} of each side."\n tags: [inverse]\n\n - id: iso-square\n name: Undo the square\n mode: isolate\n pattern: u 2 ^ r =\n when:\n u: [hasVariable]\n output: u r sqrt pm =\n priority: 1\n explain: "Take the square root of each side; {u} can be positive or negative."\n tags: [inverse]\n\n - id: iso-even-power\n name: Undo an even power\n mode: isolate\n pattern: u n ^ r =\n when:\n u: [hasVariable]\n n: [isEvenWhole]\n output: u r 1 n / ^ pm =\n explain: "Take the root of each side (the {n}th root); {u} can be positive or negative."\n tags: [inverse]\n\n - id: iso-odd-power\n name: Undo an odd power\n mode: isolate\n pattern: u n ^ r =\n when:\n u: [hasVariable]\n n: [isOddWhole]\n output: u r 1 n / ^ =\n explain: "Take the root of each side (the {n}th root)."\n tags: [inverse]\n\n - id: iso-fractional-power\n name: Undo a power\n mode: isolate\n pattern: u n ^ r =\n when:\n u: [hasVariable]\n n: [isRational]\n output: u r 1 n / ^ =\n priority: -1\n explain: "Raise each side to the power 1/{n}."\n tags: [inverse]\n\n - id: iso-sqrt\n name: Undo the square root\n mode: isolate\n pattern: u sqrt r =\n when:\n u: [hasVariable]\n output: u r 2 ^ =\n explain: "Square each side (this can add answers, so each one is checked at the end)."\n tags: [inverse]\n\n - id: iso-root\n name: Undo the root\n mode: isolate\n pattern: n u root r =\n when:\n u: [hasVariable]\n n: [freeOfVariable]\n output: u r n ^ =\n explain: "Raise each side to the power {n}."\n tags: [inverse]\n\n - id: iso-reciprocal\n name: Undo the fraction\n mode: isolate\n pattern: c u / r =\n when:\n u: [hasVariable]\n c: [freeOfVariable]\n output: u c r / =\n explain: "{c}/{u} = {r}, so {u} = {c}/{r}."\n tags: [inverse]\n\n - id: iso-abs\n name: Undo the absolute value\n mode: isolate\n pattern: u abs r =\n when:\n u: [hasVariable]\n output: u r pm =\n explain: "|{u}| = {r} means {u} is {r} or -{r}."\n tags: [inverse]\n\n - id: iso-sin\n name: Undo the sine\n mode: isolate\n pattern: u sin r =\n when:\n u: [hasVariable]\n output: u r arcsin = u =pi r arcsin - = |\n explain: "Two angles in a turn have sine {r}: arcsin {r} and π - arcsin {r} (add any whole number of turns, 2πk, for the rest)."\n tags: [inverse, trig]\n\n - id: iso-cos\n name: Undo the cosine\n mode: isolate\n pattern: u cos r =\n when:\n u: [hasVariable]\n output: u r arccos pm =\n explain: "Two angles in a turn have cosine {r}: ±arccos {r} (add 2πk for the rest)."\n tags: [inverse, trig]\n\n - id: iso-tan\n name: Undo the tangent\n mode: isolate\n pattern: u tan r =\n when:\n u: [hasVariable]\n output: u r arctan =\n explain: "Take arctan of each side (add πk for the rest)."\n tags: [inverse, trig]\n\n - { id: iso-arcsin, name: Undo arcsin, mode: isolate, pattern: u arcsin r =, when: { u: [hasVariable] }, output: u r sin =, tags: [inverse], explain: "Take sin of each side." }\n - { id: iso-arccos, name: Undo arccos, mode: isolate, pattern: u arccos r =, when: { u: [hasVariable] }, output: u r cos =, tags: [inverse], explain: "Take cos of each side." }\n - { id: iso-arctan, name: Undo arctan, mode: isolate, pattern: u arctan r =, when: { u: [hasVariable] }, output: u r tan =, tags: [inverse], explain: "Take tan of each side." }\n - { id: iso-sinh, name: Undo sinh, mode: isolate, pattern: u sinh r =, when: { u: [hasVariable] }, output: u r arcsinh =, tags: [inverse], explain: "Take arcsinh of each side." }\n - { id: iso-tanh, name: Undo tanh, mode: isolate, pattern: u tanh r =, when: { u: [hasVariable] }, output: u r arctanh =, tags: [inverse], explain: "Take arctanh of each side." }\n - { id: iso-cosh, name: Undo cosh, mode: isolate, pattern: u cosh r =, when: { u: [hasVariable] }, output: u r arccosh pm =, tags: [inverse], explain: "Two numbers have cosh {r}: ±arccosh {r}." }\n - { id: iso-arcsinh, name: Undo arcsinh, mode: isolate, pattern: u arcsinh r =, when: { u: [hasVariable] }, output: u r sinh =, tags: [inverse], explain: "Take sinh of each side." }\n - { id: iso-arccosh, name: Undo arccosh, mode: isolate, pattern: u arccosh r =, when: { u: [hasVariable] }, output: u r cosh =, tags: [inverse], explain: "Take cosh of each side." }\n - { id: iso-arctanh, name: Undo arctanh, mode: isolate, pattern: u arctanh r =, when: { u: [hasVariable] }, output: u r tanh =, tags: [inverse], explain: "Take tanh of each side." }\n'],Jr=['name: Complex numbers\n\n# Loaded only by createCAS({ complex: true }), where i is the imaginary unit.\n# The arithmetic (i² = -1, √-4 = 2i, (2 + 3i)(1 - i) = 5 + i, 1/(1 + i) = (1 - i)/2)\n# and Re, Im, conj, arg, |z| are the normal form\'s (src/cas/form.js); unknowns\n# count as real, so Re(x + 3i) = x. Write a complex unknown as a + bi.\n\noperators:\n - { symbol: re, arity: 1, label: real part }\n - { symbol: im, arity: 1, label: imaginary part }\n - { symbol: conj, arity: 1, label: complex conjugate }\n - { symbol: arg, arity: 1, label: argument }\n\nrules:\n - id: euler\n name: Euler\'s formula\n pattern: =e u ^\n when:\n u: [hasImaginaryPart, isConstant]\n output: =e u re ^ u im cos =i u im sin * + *\n explain: "e^(a + bi) = e^a (cos b + i sin b)."\n tags: [complex]\n\n - id: ln-negative\n name: Log of a negative number\n pattern: u ln\n when:\n u: [isNegativeConstant]\n output: u neg ln =i =pi * +\n explain: "{u} = |{u}|·e^(iπ), so ln {u} = ln |{u}| + iπ (the principal value)."\n tags: [complex]\n\n - id: ln-complex\n name: Log of a complex number\n pattern: u ln\n when:\n u: [hasImaginaryPart, isConstant]\n output: u abs ln u arg =i * +\n explain: "ln z = ln |z| + i arg z (the principal value)."\n tags: [complex]\n\n - id: i-to-the-i\n name: i to the power i\n pattern: =i =i ^\n output: =e =pi 2 / neg ^\n explain: "i = e^(iπ/2), so i^i = e^(i·iπ/2) = e^(-π/2) (the principal value)."\n tags: [complex]\n'],Qr={normal:"Work out the numbers and collect like terms.","simplify.cancel":"Cancel the factors the top and bottom share.","simplify.expand":"Multiplying out gives something shorter.","simplify.factor":"Factoring gives something shorter.",expand:"Multiply out the brackets.",factor:"Write it as a product of factors.","factor.common":"Take out the common factor {common}.","factor.polynomial":"Factor what is left: {roots}.",together:"Write it as one fraction over a common denominator.",cancel:"Cancel the factors the top and bottom share: {canceled}.","solve.move":"Keep the terms with {v} on the left and move the others to the right.","solve.divide":"Divide both sides by {by}.","solve.multiply":"Multiply both sides by {by}.","solve.one-side":"Move everything to one side, so the equation reads … = 0.","solve.factor":"Factor the left side.","solve.zero-product":"A product is 0 exactly when one of its factors is 0.","solve.split":"There are two cases; solve each.","solve.quadratic":"The quadratic formula with a = {a}, b = {b}, c = {c}: {v} = (-b ± √(b² - 4ac)) / 2a, and b² - 4ac = {D}.","solve.no-real":"b² - 4ac = {D} is negative, so there are no real solutions.","solve.quadratic-complex":"The quadratic formula with a = {a}, b = {b}, c = {c}: {v} = (-b ± √(b² - 4ac)) / 2a. b² - 4ac = {D} is negative, so its square root is imaginary: √({D}) = {root}.","solve.roots":"{v}^{n} = {r} has {n} solutions, spaced evenly round a circle: |{r}|^(1/{n})·(cos θ + i sin θ), with θ = (arg {r} + 2πk)/{n} for k = 0 … {last}.","solve.clear-denominator":"Multiply both sides by {den} (an answer that makes it 0 is not allowed).","solve.substitute":"Write {u} for {kernel}: this is a polynomial in {u}.","solve.reject":"{value} is not a solution: {reason}.","solve.always":"This is true for every {v}.","solve.never":"This is never true, so there is no solution.","solve.unsolved":"There is no exact method here for solving for {v}; try { approximate: true }.","solve.numeric":"Found {count} solution(s) numerically.","system.eliminate":"Use one equation to remove {v} from the others.","integrate.expand":"Multiply out, then integrate term by term.","integrate.substitute":"Let {u} = {inside}, so d{u} = {a} d{v}.","integrate.back":"Put {inside} back for {u}.","integrate.parts":"By parts with u = {u} and dv = {dv} d{v}: ∫ u dv = u·v - ∫ v du, where v = {V} and du = {du} d{v}.","integrate.constant":"The number {c} comes out of the integral.","integrate.divide":"The top has at least the degree of the bottom: divide first.","integrate.partial-fractions":"Split the fraction into simple fractions, one for each factor below.","integrate.evaluate":"Evaluate {F} at {b} and at {a}, and subtract.",substitute:"Put in the values."},Yr=["normal","rewrite","simplify","expand","factor","cancel","diff","differentiate","integrate","solve","solveSystem","substitute","approximate","equivalent"];class Kr{constructor(e,n,t,r,s){this.set=e,this.messages=n,this.format=t,this.read=r,this.complex=s;for(const e of Yr){const n=Kr.prototype[e];this[e]=(...e)=>ce(s,()=>n.apply(this,e))}}node(e){return this.atPoints(this.read_(e))}read_(e){if(e&&"object"==typeof e&&!Array.isArray(e)&&e.type)return e;if(Array.isArray(e))return L(e);if("string"!=typeof e)throw new G("expected an expression");if(this.read){const n=this.read(e);return Array.isArray(n)?L(n):"string"==typeof n?W(n):n}return W(e)}atPoints(e){if(!e||!P(e)||!e.s.includes("= der"))return e;const n=e.args.map(e=>this.atPoints(e)),[t,r]=n;if("der"===e.op&&P(r)&&"="===r.op&&"sym"===r.args[0].type){const e=r.args[0].token;return this.substitute(this.diff(t,e).result,{[e]:r.args[1].s}).result}return R(e.op,n)}step(e,n,t,r,s,o={}){return function(e,n,t,r,s,o,i,a,u=[]){const l=(o??"").replace(/\{(\w+)\}/g,(e,n)=>{const t=i?.[n];return void 0===t?e:"string"==typeof t?t:a(t)});return{id:e,name:n,tags:t,from:r.s,to:s.s,path:u,before:r.s,after:s.s,explanation:l}}(e,n,t,r,s,this.messages[e]??"",o,this.format)}result(e,n,t,r={}){let s=e;if(t.approximate&&s){s=Nt(s,{digits:"number"==typeof t.approximate?t.approximate:15})}return{result:s,text:s?this.format(s):"",steps:Wt(n,Pt(t.steps)),...r}}variable(e,n){if(n&&!/^\\?[A-Za-z\u0370-\u03FF][A-Za-z0-9_\u0370-\u03FF′]*$/.test(n))throw new G(`"${n}" is not a variable name; for a derivative at a point write der(f, x = a)`);if(n)return n;const t=[...nn(e)];return 1===t.length?t[0]:t.includes("x")?"x":t[0]??"x"}tidyStep(e,n){return e.s===n.s?[]:[this.step("normal","Work out and collect",["tidy","arithmetic"],e,n)]}normal(e){return Je(this.node(e))}rewrite(e,n,t={}){const r=this.node(e),s=this.set.view(n);if(!s.size)throw new G(`no rules in mode "${n}" (modes: ${this.set.modes().join(", ")})`);const o=Vt(r,s,{format:this.format,order:t.order,variable:t.variable});return this.result(o.node,[...this.tidyStep(r,Je(r)),...o.steps],t)}simplify(e,n={}){const t=this.node(e),r=[...this.tidyStep(t,Je(t))],s=Vt(t,this.set.view("simplify"),{format:this.format});r.push(...s.steps);let o=s.node,i=null;const a=He(o),u=[],l=0===nn(o).size,c=l?null:dr(a);c&&u.push({node:cr(c),id:"simplify.cancel",name:"Cancel"});const f=Vt(Ge(Ht(a)),this.set.view("simplify"),{format:this.format});u.push({node:f.node,id:"simplify.expand",name:"Multiply out"}),"add"!==a.k||l||u.push({node:cr(sr(a)),id:"simplify.factor",name:"Factor"});for(const e of u)H(e.node)<H(o)&&(i=this.step(e.id,e.name,["shorter"],o,e.node),o=e.node);return i&&r.push(i),this.result(o,r,n)}expand(e,n={}){const t=this.node(e),r=Ge(Ht(He(t)));return this.result(r,t.s===r.s?[]:[this.step("expand","Multiply out",["expand"],t,r)],n)}factor(e,n={}){const t=this.node(e),r=sr(He(t)),s=cr(r),o=[],i=r.notes.find(e=>"factor.common"===e.id);return s.s!==Je(t).s&&o.push(this.step(i?"factor.common":"factor","Factor",["factor"],t,s,i?{common:Ge(i.values.common)}:{})),this.result(s,o,n)}cancel(e,n={}){const t=this.node(e),r=He(t),s=dr(r);if(!s)return this.result(Je(t),this.tidyStep(t,Je(t)),n);const o=cr(s),i=pr(r),a=R("/",[Ge(i.num),Ge(i.den)]),u=[];return"/"===t.op&&a.s===Je(t).s||u.push(this.step("together","One fraction",["together"],t,a)),o.s!==a.s&&u.push(this.step("cancel","Cancel",["cancel"],a,o,{canceled:s.canceled.length?s.canceled.map(e=>this.format(Ge(e))).join(", "):"numbers"})),this.result(o,u,n)}diff(e,n,t={}){const r=this.node(e),s=this.variable(r,n);let o=r;const i=[];for(let e=0;e<(t.order??1);e++){const e=Vt(R("der",[o,B(s)]),this.set.view("differentiate"),{format:this.format,order:"pre"}),n=Vt(e.node,this.set.view("simplify"),{format:this.format});i.push(...e.steps,...n.steps),o=n.node}return this.result(o,i,t,{variable:s})}differentiate(e,n){const t=Vt(R("der",[e,B(n)]),this.set.view("differentiate"),{format:this.format,order:"pre"});return Vt(t.node,this.set.view("simplify"),{format:this.format}).node}integrate(e,n,t={}){let r=this.node(e);const s=e=>void 0===e?null:this.node("number"==typeof e?String(e):e);let o=s(t.from),i=s(t.to);if(P(r)&&"int"===r.op){const[e,t,s,a]=r.args;n=t.token,s&&a&&(o=s,i=a),r=e}const a=this.variable(r,n),u=Zr(this,r,a),l=Vt(u.node,this.set.view("simplify"),{format:this.format}),c=[...u.steps,...l.steps];if(o&&i){const e=Cr(this,l.node,a,o,i,r);c.push(e.step);const n=Vt(e.value,this.set.view("simplify"),{format:this.format});return c.push(...n.steps),this.result(n.node,c,t,{antiderivative:l.node,variable:a})}let f=l.node;return t.constant&&(f=R("+",[f,B(String(t.constant))])),this.result(f,c,t,{variable:a})}solve(e,n,t={}){const r=this.node(e),s=this.variable(r,n),o=vr(this,r,s,t);let i=o.solutions;if(t.approximate){const e="number"==typeof t.approximate?t.approximate:15;i=i.map(n=>Nt(n,{digits:e}))}const a=i.map(e=>R("=",[B(s),e])),u=a.length?a.reduce((e,n)=>e?R("|",[e,n]):n,null):null;return{solutions:i,result:u,variable:s,text:o.always?`true for every ${s}`:u?this.format(u):o.unsolved.length?`no exact solution found for ${s}`:"no solution",unsolved:o.unsolved.filter(e=>!e.always),always:o.always,steps:Wt(o.steps,Pt(t.steps))}}solveSystem(e,n,t={}){const r=e.map(e=>this.node(e)),s=n??[...new Set(r.flatMap(e=>[...nn(e)]))].sort(),o=function(e,n,t){const r=[],s=n.map(n=>{const r=gr(n)?Ae([He(n.args[0]),Re(He(n.args[1]))]):He(n),s=t.map(n=>{const t=Qt(r,n);if(!t||Math.max(0,...t.keys())>1)throw new G(`not linear in ${n}`);const s=t.get(1)??de(re.ZERO);if(!ve(s))throw new G(`the coefficient of ${n} must be a number (it is ${e.format(Ge(s))})`);return s.q});let o=r;for(let e=0;e<t.length;e++)o=Ae([o,Me([de(s[e].neg()),He(B(t[e]))])]);for(const e of t)if(Yt(o,e))throw new G(`not linear in ${e}`);return{coeffs:s,rhs:Re(o)}}),o=()=>s.map(e=>hr(Ge(Ae(e.coeffs.map((e,n)=>Me([de(e),He(B(t[n]))])))),Ge(e.rhs))).reduce((e,n)=>e?R("&",[e,n]):n,null);let i=0;const a=[];for(let n=0;n<t.length&&i<s.length;n++){const u=s.findIndex((e,t)=>t>=i&&!e.coeffs[n].isZero);if(u<0)continue;[s[i],s[u]]=[s[u],s[i]];const l=o(),c=s[i],f=c.coeffs[n];c.coeffs=c.coeffs.map(e=>e.div(f)),c.rhs=Me([de(f.inv()),c.rhs]);for(let e=0;e<s.length;e++){if(e===i||s[e].coeffs[n].isZero)continue;const t=s[e].coeffs[n];s[e].coeffs=s[e].coeffs.map((e,n)=>e.sub(t.mul(c.coeffs[n]))),s[e].rhs=Ae([s[e].rhs,Me([de(t.neg()),c.rhs])])}r.push(e.step("system.eliminate","Eliminate",["eliminate"],l,o(),{v:B(t[n])})),a.push(n),i++}for(const e of s.slice(i))if(!ve(e.rhs)||!e.rhs.q.isZero)return{solution:null,steps:r,status:"none"};if(a.length<t.length)return{solution:null,steps:r,status:"many"};const u=new Map;return a.forEach((e,n)=>u.set(t[e],Ge(s[n].rhs))),{solution:u,steps:r,status:"one"}}(this,r,s),i=o.solution?Object.fromEntries([...o.solution].map(([e,n])=>[e,n])):null,a="one"===o.status?s.map(e=>`${e} = ${this.format(i[e])}`).join(", "):"none"===o.status?"no solution":"infinitely many solutions";return{solution:i,status:o.status,text:a,steps:Wt(o.steps,Pt(t.steps))}}substitute(e,n,t={}){const r=this.node(e);let s=r;for(const[e,t]of Object.entries(n))s=xr(s,e,"number"==typeof t?this.node(String(t)):this.node(t));const o=this.simplify(s,t),i=[this.step("substitute","Substitute",["substitute"],r,s)];return{...o,steps:[...Wt(i,Pt(t.steps)),...o.steps]}}defined(e){const n=this.set.view("define");return n.size?Vt(e,n,{format:this.format}).node:e}approximate(e,n={}){const t=this.defined(this.node(e));if(nn(t).size&&!n.scope){const e=Nt(Je(t),n);return{result:e,text:this.format(e),number:null,exact:!1}}const r=$t(t,n);return{result:r.node,text:r.text,number:r.number,re:r.re,im:r.im,exact:r.exact}}equivalent(e,n){const t=this.node(e),r=this.node(n),s=this.defined(R("-",[t,r])),o=this.simplify(s,{steps:!1}).result;if("num"===o.type&&"0"===o.token)return{equal:!0,how:"exact"};const i=[...nn(s)];if(!i.length)try{return{equal:Math.abs($t(s,{digits:30}).number)<1e-25,how:"numeric"}}catch{return{equal:!1,how:"numeric"}}const a=[.31,1.7,2.9,-.83,.57];let u=0;for(let e=0;e<a.length;e++){const n=Object.fromEntries(i.map((n,t)=>[n,String(a[(e+t)%a.length]+t/7)]));let t;try{t=$t(s,{digits:30,scope:n}).number}catch{continue}if(u++,Math.abs(t)>1e-20)return{equal:!1,how:"numeric"}}return{equal:u>0,how:"numeric"}}modes(){return this.set.modes()}}function Gr(e={}){const n=!1===e.defaults?[]:[...Hr,...e.complex?Jr:[]],{specs:t,messages:r}=function(e){Zt();const n=[],t={};for(const r of e){const e="string"==typeof r?zn(r):r,s=Array.isArray(e)?e:e?.rules??[];for(const n of(Array.isArray(e)?[]:e?.operators)??[]){if(!n?.symbol)throw new Error("an operator needs a symbol");A(n.symbol)||S({symbol:String(n.symbol),arity:"any"===n.arity?q:Number(n.arity),label:n.label})}Object.assign(t,(Array.isArray(e)?null:e?.messages)??{});for(const e of s)n.push(e)}return{specs:n,messages:t}}([...n,...e.rules??[]]),s=ce(e.complex,()=>zt(t));return new Kr(s,{...Qr,...r},e.format??Rr,e.read??null,Boolean(e.complex))}function Xr(n){const t=n=>e("op"===n.type?ts(n,t):function(e){const n=e.value;return"symbol"!==e.type?n:c[n]?c[n]:"\\+"===n||"\\-"===n?n[1]:n}(n));return t(n)}const es={"+":"+","-":"-","*":"*","/":"/","^":"^",mod:"mod","±":"±","=":"=","===":"===","≠":"≠","≠=":"≠","<":"<",">":">","≤":"≤","≥":"≥","∈":"∈","∉":"∉","→":"→","≈":"≈","∪":"∪","∩":"∩","≡":"≡","&":"∧","|":"∨","\\xor":"⊕","\\nand":"↑","\\nor":"↓"},ns={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]};function ts(e,c){const{op:m,args:g}=e,[v,b]=g,y=(e,n)=>a(m,u(e),n)?`(${c(e)})`:c(e),w=()=>g.map(c).join(", "),x=e=>h(m,e)?`(${c(e)})`:c(e);if("*"===m&&n(e))return ts({...e,op:"neg",args:[b]},c);if("+"===m&&n(b))return ts({...e,op:"-",args:[v,b.args[1]]},c);if("-"===m&&n(b))return ts({...e,op:"+",args:[v,b.args[1]]},c);if("^"===m){const e=y(v,"left");return`${e.startsWith("-")?`(${e})`:e}^${y(b,"right")}`}if("*"===m&&e.written)return`${y(v,"left")} ${"cross"===e.written?"×":"·"} ${y(b,"right")}`;if(es[m])return`${y(v,"left")} ${es[m]} ${y(b,"right")}`;if(t[m])return`${m}(${r(e).map(e=>`[${e.map(c).join(", ")}]`).join(", ")})`;if(ns[m])return ns[m][0]+w()+ns[m][1];if(s(m))return`${o(m)}(${w()})`;switch(m){case"neg":return"-"+x(v);case"pmod":return`${c(v)} (mod ${c(b)})`;case"pm":return"±"+x(v);case"!":return x(v)+"!";case"\\not":return"¬"+x(v);case"sqrt":return`√(${c(v)})`;case"root":{const e="number"===v.type?{3:"∛",4:"∜"}[v.value]:null;return e?`${e}(${c(b)})`:`root(${c(v)}, ${c(b)})`}case"abs":return`|${c(v)}|`;case"floor":return`⌊${c(v)}⌋`;case"ceil":return`⌈${c(v)}⌉`;case"log":return`log_${"op"===v.type?`(${c(v)})`:c(v)}(${c(b)})`;case"loglog":return`ln(ln(${c(v)}))`;case"logloglog":return`ln(ln(ln(${c(v)})))`;case"perm":return`perm(${c(v)}, ${c(b)})`;case"comb":return`comb(${c(v)}, ${c(b)})`;case"_":return`${c(v)}_${c(b)}`;case"?:":return`${l(v)?`(${c(v)})`:c(v)} ? ${c(b)} : ${c(g[2])}`;case"sum":return g.map((e,n)=>a("+",u(e),n?"right":"left")?`(${c(e)})`:c(e)).join(" + ");case"prod":return g.map((e,n)=>a("*",u(e),n?"right":"left")?`(${c(e)})`:c(e)).join(" * ");case"der":{const{n:n,body:t,by:r,at:s,variable:o}=i(e);if(s)return`der(${c(t)}, ${c(r)} = ${c(s)}${n>1?`, ${n}`:""})`;const a=n>1?`^${n}`:"";return o?`d${a}${c(t)}/d${c(r)}${a}`:`d${a}/d${c(r)}${a}(${c(t)})`}case"int":return function(e,n){const[t,r,s,o]=e,i=e.length>=2&&d(r)?n(r):f(t)||"x",a=`${n(t)} d${i}`;return 1===e.length||2===e.length&&d(r)?`∫ ${a}`:`int(${e.map(n).join(", ")})`}(g,c);case"lim":return function(e,n){const[t,r,s,o]=e;return 4===e.length?`lim(${n(t)}, ${n(r)}, ${n(s)}, ${p(o).toLowerCase().startsWith("r")?"r":"l"})`:`lim(${e.map(n).join(", ")})`}(g,c);case"\\sumidx":return rs("∑",g,c);case"\\prodidx":return rs("∏",g,c)}return`${m}(${w()})`}function rs(e,n,t){const[r,s,o]=n,i="∑"===e?"sum":"prod";if(3===n.length&&"op"===s.type&&"="===s.op)return`${i}(${t(r)}, ${t(s)}, ${t(o)})`;if(2===n.length&&"op"===s.type&&"∈"===s.op)return`${i}(${t(r)}, ${t(s)})`;const a=f(r);return 3===n.length&&a?`${i}(${t(r)}, ${a} = ${t(s)}, ${t(o)})`:1===n.length?`${e} ${t(r)}`:2===n.length?`${e}[${t(s)}] ${t(r)}`:`${e}[${t(s)}, ${t(o)}] ${t(r)}`}for(const e of[es,ns])Object.setPrototypeOf(e,null);const ss=Symbol.for("inlinemath.expressions"),os=new Map,is={re:"Re",im:"Im",conj:"overline"},as=["Re","Im","re","im","conj","arg"];function us(e){const n=[],t=e=>{"op"===e.type?(e.args.forEach(t),b(e.op)?(-1===b(e.op).arity&&n.push(String(e.args.length)),n.push(e.op)):n.push(String(e.args.length),`\\:${is[e.op]??e.op}`)):n.push(e.token)};return t(e),n}function ls(e={}){const n=e.rules||e.names?null:e.complex?"complex":"default";if(n&&os.has(n))return os.get(n);const t=[...e.names??[],...e.complex?as:[]],r=Gr({...e,read:e=>v(e,t.length?{names:t}:{}),format:Rr});return n&&os.set(n,r),r}const cs=new Set(["simplify","expand","factor","cancel","diff","integrate","solve","approx"]),fs={integral:"integrate",differentiate:"diff",approximate:"approx",simp:"simplify"};function ps(e={}){const n=e.cas??ls(),t=void 0===e.steps?{}:{steps:e.steps},r=(e,s)=>{let o;try{o=n.read(e)}catch{return y(e,s)}const i=s&&s[ss];i&&(o=o.flatMap(e=>Object.hasOwn(i,e)?i[e]:[e]));const a=o[o.length-1],u=a?.startsWith("\\:")?fs[a.slice(2)]??a.slice(2):null,l=u&&cs.has(u),c="der"===a||"int"===a;if(!l&&!c)return y(e,s);const f=n.node(o),p=c&&f.op!==a,d=l?f.args:[f],h=e=>e?e.s:void 0,v=(e,r,s)=>{if(!r||"="!==r.op)return n.diff(e,h(r),{...t,order:s});const o=r.args[0].s,i=n.diff(e,o,{...t,order:s}),a=n.substitute(i.result,{[o]:r.args[1].s},t);return{...a,steps:[...i.steps??[],...a.steps??[]]}};let b;try{switch(p?"simplify-read":l?u:"der"===a?"derivative":"antiderivative"){case"simplify-read":b=n.simplify(f,t);break;case"simplify":b=n.simplify(d[0],t);break;case"expand":b=n.expand(d[0],t);break;case"factor":b=n.factor(d[0],t);break;case"cancel":b=n.cancel(d[0],t);break;case"diff":b=v(d[0],d[1],d[2]?Number(d[2].s):1);break;case"integrate":b=n.integrate(d[0],h(d[1]),{...t,...d[3]?{from:d[2].s,to:d[3].s}:{}});break;case"solve":b=n.solve(d[0],h(d[1]),t);break;case"approx":b=n.approximate(d[0],{...t,digits:d[1]?Number(d[1].s):15});break;case"derivative":b=v(f.args[0],f.args[1],1);break;default:b=n.integrate(f,void 0,t)}}catch(n){return`(${e})`}if(r.last=b,!b.result)return`"${b.text}"`;const w=(x=us(b.result),m(x)?"":Xr(g(x)));var x;return/^-?\d+(\.\d+)?$/.test(w)?w:`(${w})`};return r}const ds=e=>String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function hs(e,n={}){return`<ol class="mv-steps">${e.map(e=>{const t=us(W(e.from)),r=w(t,{...n,highlight:e.path&&e.path.length?{path:e.path}:void 0}),s=e.to===e.from?"":`<span class="mv-step-arrow" aria-label="becomes">⟶</span>${w(us(W(e.to)),n)}`,o=e.explanation?`<p class="mv-step-why">${ds(e.explanation)}</p>`:"";return`<li class="mv-step" data-rule="${ds(e.id)}"><span class="mv-step-name">${ds(e.name)}</span><div class="mv-step-maths">${r}${s}</div>${o}</li>`}).join("")}</ol>`}export{ps as casBlocks,ls as mathCAS,hs as stepsHTML,us as tokensOf};
1
+ /* Inline Math 0.4.1 — MIT license; includes mathzetta (and @mathzetta/cas, for the CAS) */
2
+ import{B as e,C as n,M as t,E as s,F as i,G as r,H as o,I as a,J as u,K as l,L as c,h as f,N as p,O as h,Q as d,R as m,j as g,S as v,T as b,U as w,z as y}from"./chunks/lite-OfhVrBim.js";import{c as x}from"./chunks/calculate-HWNd7HTQ.js";import{a as q}from"./chunks/html-hyetRykq.js";const k=new Map,$=-1,S="\\:",M=e=>"string"==typeof e&&e.startsWith(S)&&e.length>2;function N(e){if(!e||!e.symbol)throw new Error("operator needs a symbol");if(!Number.isInteger(e.arity)||e.arity<0&&e.arity!==$)throw new Error(`operator "${e.symbol}" needs an integer arity >= 0, or VARIADIC`);if(e.commutative&&2!==e.arity)throw new Error(`only binary operators can be commutative ("${e.symbol}")`);const n={symbol:e.symbol,arity:e.arity,commutative:!!e.commutative,fold:"function"==typeof e.fold?e.fold:null,label:e.label||e.symbol};return k.set(n.symbol,n),n}const O=Object.freeze({symbol:S,arity:$,commutative:!1,fold:null,label:"function"});function A(e){const n=k.get(e);return n||(M(e)?{...O,symbol:e,label:e.slice(2)}:null)}function I(e){return k.has(e)||M(e)}const E=e=>Number.isFinite(e)&&Number.isInteger(e)?e:null,T=e=>Number.isFinite(e)?e:null;!function(){N({symbol:"+",arity:2,commutative:!0,label:"add",fold:(e,n)=>T(e+n)}),N({symbol:"-",arity:2,label:"subtract",fold:(e,n)=>T(e-n)}),N({symbol:"*",arity:2,commutative:!0,label:"multiply",fold:(e,n)=>T(e*n)}),N({symbol:"/",arity:2,label:"divide",fold:(e,n)=>0===n?null:E(e/n)}),N({symbol:"^",arity:2,label:"power",fold:(e,n)=>Number.isInteger(n)&&Math.abs(n)<=64?T(e**n):null}),N({symbol:"neg",arity:1,label:"negate",fold:e=>T(-e)}),N({symbol:"pm",arity:1,label:"plus or minus"}),N({symbol:"±",arity:2,label:"plus or minus"}),N({symbol:"mod",arity:2,label:"modulo",fold:(e,n)=>0===n?null:E((e%n+n)%n)}),N({symbol:"!",arity:1,label:"factorial",fold:e=>Number.isInteger(e)&&e>=0&&e<=18?[...Array(e).keys()].reduce((e,n)=>e*(n+1),1):null}),N({symbol:"_",arity:2,label:"subscript"}),N({symbol:"der",arity:2,label:"derivative"}),N({symbol:"evaluated",arity:4,label:"evaluated from a to b"}),N({symbol:"setbuilder",arity:2,label:"the set of … such that"}),N({symbol:"int",arity:$,label:"integral"}),N({symbol:"lim",arity:$,label:"limit"}),N({symbol:"\\sumidx",arity:$,label:"sum over an index"}),N({symbol:"\\prodidx",arity:$,label:"product over an index"}),N({symbol:"abs",arity:1,label:"absolute value",fold:e=>T(Math.abs(e))}),N({symbol:"floor",arity:1,label:"floor",fold:e=>T(Math.floor(e))}),N({symbol:"ceil",arity:1,label:"ceiling",fold:e=>T(Math.ceil(e))}),N({symbol:"round",arity:2,label:"round",fold:(e,n)=>Number.isInteger(n)?T(Math.round(e*10**n)/10**n):null}),N({symbol:"fixed",arity:2,label:"fixed",fold:()=>null}),N({symbol:"sqrt",arity:1,label:"square root",fold:e=>E(Math.sqrt(e))}),N({symbol:"root",arity:2,label:"nth root",fold:(e,n)=>E(Math.round(n**(1/e))**e===n?Math.round(n**(1/e)):NaN)});for(const e of["sin","cos","tan","csc","sec","cot","sinh","cosh","tanh","arcsin","arccos","arctan","arcsec","arccsc","arccot","arcsinh","arccosh","arctanh","ln","loglog","logloglog","expm1"])N({symbol:e,arity:1,label:e});N({symbol:"log",arity:2,label:"log to a base"}),N({symbol:"atan2",arity:2,label:"atan2"}),N({symbol:"perm",arity:2,label:"permutations"}),N({symbol:"comb",arity:2,label:"combinations"}),N({symbol:"random",arity:0,label:"random"});for(const e of["max","min","gcd","mean","sum","prod"])N({symbol:e,arity:$,label:e});for(const e of["()","[]","{}","(]","[)"])N({symbol:e,arity:$,label:"group"});for(const e of["pmatrix","bmatrix","vmatrix"])N({symbol:e,arity:$,label:"matrix"});N({symbol:"det",arity:1,label:"determinant"});for(const e of["=","===","≠","≠=","<",">","≤","≥","∈","∉","∪","∩","≈","≡","→","pmod","&","|","\\xor","\\nand","\\nor","\\implies","\\iff"])N({symbol:e,arity:2,label:e});N({symbol:"\\not",arity:1,label:"not"}),N({symbol:"?:",arity:3,label:"if then else"})}();const j="num",Z="sym",z="op",F=Object.freeze([]);class B extends Error{constructor(e){super(e),this.name="ExprError"}}function C(e){if("number"!=typeof e||!Number.isFinite(e))throw new B(`not a finite number: ${e}`);const n=(t=e,Object.is(t,-0)?"0":String(t));var t;return Object.freeze({type:j,token:n,value:e,args:F,s:n})}function D(e){if("string"!=typeof e||""===e)throw new B("symbol needs a non-empty token");return Object.freeze({type:Z,token:e,value:null,args:F,s:e})}function P(e){const n=/^(-?)0*(\d+?)(?:\.(\d*?)0*)?$/.exec(String(e));if(!n)throw new B(`not an exact decimal: ${e}`);const[,t,s,i=""]=n,r=i?`${s}.${i}`:s,o=/^0(\.0*)?$/.test(r)?"0":t+r;return Object.freeze({type:j,token:o,value:Number(o),args:F,s:o})}const R=/^-?\d+(\.\d+)?$/;function U(e){const n=String(e);if(R.test(n))return P(n);if(""!==n&&!/\s/.test(n)){const e=Number(n);if(Number.isFinite(e))return C(e)}return D(n)}function V(e,n){const t=A(e);if(!t)throw new B(`unknown operator "${e}"`);if(t.arity!==$&&n.length!==t.arity)throw new B(`"${e}" takes ${t.arity} operand(s), got ${n.length}`);const s=Object.freeze(n.slice()),i=t.arity===$?` ${s.length}`:"",r=`${s.length?s.map(e=>e.s).join(" "):""}${s.length,""}${i} ${e}`.trimStart();return Object.freeze({type:z,op:e,token:e,value:null,args:s,s:r})}const L=e=>e.type===j,W=e=>e.type===z;function _(e){return H(function(e){const n=String(e).trim();return""===n?[]:n.split(/\s+/)}(e))}function H(e){if(!Array.isArray(e))throw new B("fromPostfix needs an array of tokens");if(0===e.length)throw new B("empty expression");const n=[];for(let t=0;t<e.length;t++){const s=String(e[t]);if(I(s)){let e=A(s).arity;if(e===$){const i=n.pop();if(e=i&&i.type===j&&Number.isInteger(i.value)&&i.value>=0?i.value:-1,e<0)throw new B(`"${s}" at position ${t+1} takes any number of operands, so a count must come before it`)}if(n.length<e)throw new B(`"${s}" at position ${t+1} needs ${e} operand(s), only ${n.length} on the stack`);const i=n.splice(n.length-e,e);n.push(V(s,i))}else n.push(U(s))}if(1!==n.length){const t=[...new Set(e.filter(e=>!I(e)))];throw new B(`expression leaves ${n.length} values on the stack; it should leave exactly 1. Read as operands: ${t.join(", ")} — is one of those meant to be an operator?`)}return n[0]}function Q(e){if(e.type!==z)return 0;let n=0;for(const t of e.args)n=Math.max(n,Q(t));return n+1}function J(e){if(e.type!==z)return 1;let n=1;for(const t of e.args)n+=J(t);return n}function K(e,n=[]){if(e.type!==z)n.push(e.token);else for(const t of e.args)K(t,n);return n}function Y(e){return e.type===j||e.type!==Z&&e.args.every(Y)}function G(e,n="pre",t=[],s=[]){"pre"===n&&s.push({node:e,path:t});for(let i=0;i<e.args.length;i++)G(e.args[i],n,t.concat(i),s);return"post"===n&&s.push({node:e,path:t}),s}function X(e,n,t){if(0===n.length)return t;const[s,...i]=n,r=e.args.slice();return r[s]=X(r[s],i,t),V(e.op,r)}class ee extends Error{constructor(e){super(e),this.name="CasError"}}const ne=1e5,te=e=>e<0n?-e:e,se=e=>0n===e?0:te(e).toString(2).length;function ie(e,n){for(e=te(e),n=te(n);n;)[e,n]=[n,e%n];return e}class re{constructor(e,n=1n){if(0n===n)throw new ee("division by zero");n<0n&&(e=-e,n=-n);const t=ie(e,n)||1n;if(this.n=e/t,this.d=n/t,se(this.n)>ne||se(this.d)>ne)throw new ee("a number too large to keep exactly")}static of(e){return new re(BigInt(e))}add(e){return new re(this.n*e.d+e.n*this.d,this.d*e.d)}sub(e){return new re(this.n*e.d-e.n*this.d,this.d*e.d)}mul(e){return new re(this.n*e.n,this.d*e.d)}div(e){if(0n===e.n)throw new ee("division by zero");return new re(this.n*e.d,this.d*e.n)}neg(){return new re(-this.n,this.d)}abs(){return this.n<0n?this.neg():this}inv(){return re.ONE.div(this)}pow(e){if((e=BigInt(e))<0n)return this.inv().pow(-e);if((0n===this.n||1n===te(this.n))&&1n===this.d)return 0n===e||-1n===this.n&&e%2n==0n?re.ONE:this;if(BigInt(Math.max(se(this.n),se(this.d)))*e>BigInt(ne))throw new ee("a power too large to work out exactly");return new re(this.n**e,this.d**e)}get isZero(){return 0n===this.n}get isOne(){return 1n===this.n&&1n===this.d}get isInteger(){return 1n===this.d}get sign(){return this.n<0n?-1:this.n>0n?1:0}equals(e){return this.n===e.n&&this.d===e.d}compare(e){const n=this.n*e.d,t=e.n*this.d;return n<t?-1:n>t?1:0}floor(){const e=this.n/this.d;return new re(this.n<0n&&e*this.d!==this.n?e-1n:e)}ceil(){return this.neg().floor().neg()}toNumber(){const e=Number(this.n),n=Number(this.d);if(Number.isFinite(e)&&Number.isFinite(n))return e/n;const t=BigInt(Math.max(se(this.n),se(this.d))-1e3);return Number(this.n>>t)/Number(this.d>>t)}toString(){return 1n===this.d?String(this.n):`${this.n}/${this.d}`}}function oe(e){const n=/^(-?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(String(e));if(!n||""===n[2]&&!n[3])return null;const[,t,s,i="",r="0"]=n;let o=new re(BigInt((s||"0")+i),10n**BigInt(i.length));const a=Number(r);return a&&(o=o.mul(re.of(10).pow(a))),t?o.neg():o}function ae(e,n){if(e<2n)return e;if(n>=se(e))return 1n;const t=BigInt(n);let s=1n<<BigInt(Math.ceil(se(e)/n));for(;;){const n=((t-1n)*s+e/s**(t-1n))/t;if(n>=s)break;s=n}for(;s**t>e;)s--;for(;(s+1n)**t<=e;)s++;return s}re.ZERO=new re(0n),re.ONE=new re(1n),re.MINUS_ONE=new re(-1n),re.HALF=new re(1n,2n);const ue=(()=>{const e=[],n=new Uint8Array(1e4);for(let t=2;t<n.length;t++)if(!n[t]){e.push(BigInt(t));for(let e=t*t;e<n.length;e+=t)n[e]=1}return e})();function le(e,n){const t=BigInt(n);let s=1n,i=1n,r=e;for(const e of ue){if(e*e>r)break;if(r%e)continue;let n=0n;for(;r%e===0n;)r/=e,n++;s*=e**(n/t),i*=e**(n%t)}if(r>1n){const e=function(e,n){if(e<0n)return null;if(e<2n)return e;const t=ae(e,n);return t**BigInt(n)===e?t:null}(r,n);null!==e?s*=e:i*=r}return{outside:s,inside:i}}const ce=new Set(["pi","e","π"]),fe={complex:!1};function pe(e,n){const t=fe.complex;fe.complex=Boolean(e);try{return n()}finally{fe.complex=t}}const he=e=>ce.has(e)||fe.complex&&"i"===e,de=e=>fe.complex&&"atom"===e.k&&"sym"===e.node.type&&"i"===e.node.token,me=e=>({k:"num",q:e}),ge=me(re.ONE),ve=me(re.ZERO),be=me(re.HALF),we=e=>"num"===e.k,ye=e=>({k:"atom",node:e}),xe=new WeakMap;function qe(e){let n=xe.get(e);return void 0===n&&xe.set(e,n=en(e).s),n}function ke(e){if("num"===e.k)return 0;if("atom"===e.k)return"sym"===e.node.type&&he(e.node.token)?0:1;if("add"===e.k)return Math.max(...e.terms.map(e=>ke(e.x)));let n=0;for(const t of e.fs){const e=ke(t.b);e&&(n+=e*(we(t.e)?t.e.q.toNumber():1))}return n}function $e(e,n){return"num"===e.k?n&&!we(n)?3:0:de(e)?1.5:"atom"===e.k&&"sym"===e.node.type?he(e.node.token)?n&&!we(n)?3:1:2:"atom"===e.k?3:4}const Se=(e,n)=>e<n?-1:e>n?1:0;function Me(e){const n=new Map,t=(e,t)=>{"atom"!==e.k||"sym"!==e.node.type||he(e.node.token)||n.set(e.node.token,(n.get(e.node.token)??0)+t)};if("mul"===e.k)for(const n of e.fs)t(n.b,we(n.e)?n.e.q.toNumber():1);else t(e,1);return n}function Ne(e,n){const t=ke(n.x)-ke(e.x);if(t)return t;const s=Me(e.x),i=Me(n.x);for(const e of[...new Set([...s.keys(),...i.keys()])].sort()){const n=(i.get(e)??0)-(s.get(e)??0);if(n)return n}return Se(qe(e.x),qe(n.x))}function Oe(e,n){return e.isOne?n:e.isZero?ve:Te([me(e),n])}function Ae(e){if("num"===e.k)return{coef:e.q,rest:null};if("mul"!==e.k||e.c.isOne)return{coef:re.ONE,rest:e};const n=1===e.fs.length&&we(e.fs[0].e)&&e.fs[0].e.q.isOne?e.fs[0].b:{k:"mul",c:re.ONE,fs:e.fs};return{coef:e.c,rest:n}}function Ie(e){let n=re.ZERO;const t=new Map,s=(e,n)=>{const s=qe(n),i=t.get(s);i?i.coef=i.coef.add(e):t.set(s,{coef:e,x:n})};for(const t of e)if("num"===t.k)n=n.add(t.q);else if("add"===t.k){n=n.add(t.c);for(const e of t.terms)s(e.coef,e.x)}else{const{coef:e,rest:n}=Ae(t);s(e,n)}const i=[...t.values()].filter(e=>!e.coef.isZero);return i.length?n.isZero&&1===i.length?Oe(i[0].coef,i[0].x):(i.sort(Ne),{k:"add",c:n,terms:i}):me(n)}function Ee(e,n){if(!we(n))return e.isOne?{coef:re.ONE,fs:[]}:{coef:re.ONE,fs:[{b:me(e),e:n}]};const t=n.q;if(t.isInteger)return{coef:e.pow(t.n),fs:[]};if(e.isZero){if(t.sign<0)throw new ee("division by zero");return{coef:re.ZERO,fs:[]}}if(e.isOne)return{coef:re.ONE,fs:[]};if(e.sign<0){if(t.d%2n==1n){const{coef:s,fs:i}=Ee(e.neg(),n);return{coef:t.n%2n==0n?s:s.neg(),fs:i}}if(fe.complex&&2n===t.d){const{coef:s,fs:i}=Ee(e.neg(),n);return{coef:s,fs:[...i,{b:ze,e:me(new re(t.n))}]}}return{coef:re.ONE,fs:[{b:me(e),e:n}]}}if(!e.isInteger){const s=Ee(new re(e.n),n),i=Ee(new re(e.d),me(t.neg()));return{coef:s.coef.mul(i.coef),fs:[...s.fs,...i.fs]}}const s=t.floor(),i=t.sub(s);if(BigInt(se(e.n))*i.n>BigInt(ne)||i.d>1000n)return{coef:re.ONE,fs:[{b:me(e),e:n}]};let r=s.isZero?re.ONE:e.pow(s.n);const{outside:o,inside:a}=le(e.n**i.n,Number(i.d));r=r.mul(new re(o));return{coef:r,fs:a>1n?[{b:me(new re(a)),e:me(new re(1n,i.d))}]:[]}}function Te(e){let n=re.ONE;const t=new Map,s=(e,n)=>{const s=qe(e),i=t.get(s);i?i.e=Ie([i.e,n]):t.set(s,{b:e,e:n})};for(const t of e)if("num"===t.k)n=n.mul(t.q);else if("mul"===t.k){n=n.mul(t.c);for(const e of t.fs)s(e.b,e.e)}else s(t,ge);if(n.isZero)return ve;const i=[],r=new Map;for(const e of t.values())if(!we(e.e)||!e.e.q.isZero){if("num"===e.b.k){if(we(e.e)&&!e.e.q.isInteger&&e.b.q.sign>0&&e.b.q.isInteger){const n=e.e.q.toString(),t=r.get(n);t?t.n*=e.b.q.n:r.set(n,{n:e.b.q.n,e:e.e});continue}const t=Ee(e.b.q,e.e);n=n.mul(t.coef),i.push(...t.fs);continue}if("mul"===e.b.k&&we(e.e)&&e.e.q.isInteger){const t=je(e.b,e.e);"mul"===t.k?(n=n.mul(t.c),i.push(...t.fs)):"num"===t.k?n=n.mul(t.q):i.push({b:t,e:ge});continue}i.push(e)}for(const{n:e,e:t}of r.values()){const s=Ee(new re(e),t);n=n.mul(s.coef),i.push(...s.fs)}if(n.isZero)return ve;const o=new Map;for(const e of i){const n=qe(e.b),t=o.get(n);t?t.e=Ie([t.e,e.e]):o.set(n,{...e})}let a=[...o.values()].filter(e=>!(we(e.e)&&e.e.q.isZero));if(fe.complex){a=a.flatMap(e=>{if(!de(e.b)||!we(e.e)||!e.e.q.isInteger)return[e];const t=(e.e.q.n%4n+4n)%4n;return t>=2n&&(n=n.neg()),t%2n?[{b:e.b,e:ge}]:[]});const e=a.filter(e=>"add"===e.b.k&&we(e.e)&&e.e.q.isInteger&&Be(e.b)),t=a.some(e=>de(e.b)),s=e.every(e=>(e.e.q.sign<0?-e.e.q.n:e.e.q.n)<=60n);if(e.length&&s&&(e.length>1||t||!e[0].e.q.isOne)){const s=a.filter(n=>!e.includes(n)&&!de(n.b));let i=t?[ze]:[ge];for(const n of e){const e=n.e.q.sign<0?Pe(n.b):n.b;for(let t=0n;t<(n.e.q.sign<0?-n.e.q.n:n.e.q.n);t++)i=Ce(i,rn(e))}return Te([me(n),Ie(i),...s.map(e=>Ze(e.b,e.e))])}}if(a.some(e=>"num"===e.b.k&&we(e.e)&&e.e.q.compare(re.ONE)>=0))return Te([me(n),...a.map(e=>"num"===e.b.k?je(e.b,e.e):{k:"mul",c:re.ONE,fs:[e]})]);if(!a.length)return me(n);if(1===a.length&&!n.isOne&&"add"===a[0].b.k&&we(a[0].e)&&a[0].e.q.isOne){const e=a[0].b;return Ie([me(n.mul(e.c)),...e.terms.map(e=>Oe(n.mul(e.coef),e.x))])}return n.isOne&&1===a.length&&we(a[0].e)&&a[0].e.q.isOne?a[0].b:(a=a.sort((e,n)=>$e(e.b,e.e)-$e(n.b,n.e)||Se(qe(e.b),qe(n.b))),{k:"mul",c:n,fs:a})}function je(e,n){if(fe.complex&&we(n)&&n.q.isInteger){if(de(e))return Te([{k:"mul",c:re.ONE,fs:[{b:e,e:n}]}]);if("add"===e.k&&Be(e)&&!n.q.isOne)return Te([{k:"mul",c:re.ONE,fs:[{b:e,e:n}]}])}if(we(n)){if(n.q.isZero){if(we(e)&&e.q.isZero)throw new ee("0^0 is undefined");return ge}if(n.q.isOne)return e}if(we(e)){const t=Ee(e.q,n);if(!t.fs.length)return me(t.coef);if(t.fs.some(e=>de(e.b)))return Te([me(t.coef),...t.fs.map(e=>({k:"mul",c:re.ONE,fs:[e]}))]);const s={k:"mul",c:t.coef,fs:t.fs};return t.coef.isOne&&1===t.fs.length&&we(t.fs[0].e)&&t.fs[0].e.q.isOne?t.fs[0].b:s}if(fe.complex&&we(n)&&2n===n.q.d&&Be(e)){const t=De(e);if(t&&we(t.im)&&!t.im.q.isZero){const e=e=>je(e,me(re.of(2))),s=je(Ie([e(t.re),e(t.im)]),be),i=je(Te([Ie([s,t.re]),me(re.HALF)]),be),r=je(Te([Ie([s,Ve(t.re)]),me(re.HALF)]),be);return je(Ie([i,Te([me(re.of(t.im.q.sign)),r,ze])]),me(new re(n.q.n)))}}if("mul"===e.k){if(we(n)&&n.q.isInteger)return Te([me(e.c.pow(n.q.n)),...e.fs.map(e=>Ze(e.b,Te([e.e,n])))]);if(!e.c.isOne&&e.c.sign>0)return Te([je(me(e.c),n),je({k:"mul",c:re.ONE,fs:e.fs},n)]);if(e.c.isOne&&1===e.fs.length){const[t]=e.fs;if(we(t.e)&&we(n)&&1n===t.e.q.n&&t.e.q.d%2n==1n)return Ze(t.b,Te([t.e,n]))}}return{k:"mul",c:re.ONE,fs:[{b:e,e:n}]}}function Ze(e,n){return we(n)&&n.q.isZero?ge:we(e)?je(e,n):we(n)&&n.q.isOne?e:{k:"mul",c:re.ONE,fs:[{b:e,e:n}]}}const ze=ye(D("i")),Fe=e=>fe.complex&&en(e).s.split(" ").includes("i");function Be(e){return fe.complex&&Fe(e)&&0===sn(en(e)).size}function Ce(e,n){const t=[];for(const s of e)for(const e of n)t.push(Te([s,e]));return rn(Ie(t))}function De(e){const n=[],t=[];for(const s of rn(e)){const{coef:e,rest:i}=Ae(s),r=i?on(i):[],o=r.filter(e=>de(e)),a=r.filter(e=>!de(e));if(a.some(e=>Fe(e)))return null;(o.length?t:n).push(Te([me(e),...a]))}return{re:Ie(n),im:Ie(t)}}function Pe(e){const n=De(e);if(!n)return je(e,me(re.MINUS_ONE));const t=Ie([je(n.re,me(re.of(2))),je(n.im,me(re.of(2)))]);return Te([Ie([n.re,Te([me(re.MINUS_ONE),n.im,ze])]),je(t,me(re.MINUS_ONE))])}const Re={re:([e])=>De(e)?.re??null,im:([e])=>De(e)?.im??null,conj:([e])=>{const n=De(e);return n?Ie([n.re,Te([me(re.MINUS_ONE),n.im,ze])]):null},arg:([e])=>{const n=De(e);return n?He("atan2",[n.im,n.re]):null},abs:([e])=>{const n=De(e);return!n||we(n.im)&&n.im.q.isZero?null:je(Ie([je(n.re,me(re.of(2))),je(n.im,me(re.of(2)))]),be)}},Ue={Re:"re",re:"re",Im:"im",im:"im",conj:"conj",overline:"conj",bar:"conj",arg:"arg"},Ve=e=>Te([me(re.MINUS_ONE),e]),Le=(e,n)=>Te([e,je(n,me(re.MINUS_ONE))]),We=3000n,_e={abs:([e])=>we(e)?me(e.q.abs()):"mul"!==e.k||e.c.isOne?null:Te([me(e.c.abs()),He("abs",[Ae(e).rest])]),floor:([e])=>we(e)?me(e.q.floor()):null,ceil:([e])=>we(e)?me(e.q.ceil()):null,"!":([e])=>{if(!we(e)||!e.q.isInteger||e.q.sign<0||e.q.n>We)return null;let n=1n;for(let t=2n;t<=e.q.n;t++)n*=t;return me(new re(n))},mod:([e,n])=>we(e)&&we(n)&&!n.q.isZero?me(e.q.sub(n.q.mul(e.q.div(n.q).floor()))):null,max:e=>e.every(we)&&e.length?e.reduce((e,n)=>n.q.compare(e.q)>0?n:e):null,min:e=>e.every(we)&&e.length?e.reduce((e,n)=>n.q.compare(e.q)<0?n:e):null,gcd:e=>e.length&&e.every(e=>we(e)&&e.q.isInteger)?me(new re(e.reduce((e,n)=>ie(e,n.q.n),0n))):null,log:([e,n])=>{if(!we(e)||!we(n)||e.q.sign<=0||n.q.sign<=0||e.q.isOne)return null;if(n.q.isOne)return ve;const t=Math.log(n.q.toNumber())/Math.log(e.q.toNumber());if(!Number.isFinite(t))return null;for(let s=1;s<=12;s++){const i=Math.round(t*s);if(!(Math.abs(t*s-i)>1e-9||0===i)&&(Math.abs(i)<=256&&e.q.pow(BigInt(i)).equals(n.q.pow(BigInt(s)))))return me(new re(BigInt(i),BigInt(s)))}return null},comb:([e,n])=>we(e)&&we(n)&&e.q.isInteger&&n.q.isInteger&&e.q.sign>=0&&n.q.sign>=0&&e.q.n<=We?me(function(e,n){if(n>e)return re.ZERO;n>e-n&&(n=e-n);let t=1n;for(let s=1n;s<=n;s++)t=t*(e-n+s)/s;return new re(t)}(e.q.n,n.q.n)):null,perm:([e,n])=>{if(!(we(e)&&we(n)&&e.q.isInteger&&n.q.isInteger&&e.q.sign>=0&&n.q.sign>=0&&e.q.n<=We))return null;if(n.q.n>e.q.n)return ve;let t=1n;for(let s=0n;s<n.q.n;s++)t*=e.q.n-s;return me(new re(t))}};function He(e,n){if(fe.complex&&Re[e]){const t=Re[e](n);if(t)return t}const t=_e[e];if(t){const e=t(n);if(e)return e}return ye(V(e,n.map(en)))}const Qe=new Map;function Je(e){const n=fe.complex?`ℂ ${e.s}`:e.s,t=Qe.get(n);if(t)return t;const s=function(e){if("num"===e.type){const n=oe(e.token);if(!n)throw new ee(`not an exact number: ${e.token}`);return me(n)}if("sym"===e.type)return"π"===e.token?ye(D("pi")):ye(e);const n=e.args.map(Je);switch(e.op){case"+":return Ie(n);case"-":return((e,n)=>Ie([e,Ve(n)]))(n[0],n[1]);case"neg":return Ve(n[0]);case"*":return Te(n);case"/":return Le(n[0],n[1]);case"^":return je(n[0],n[1]);case"sqrt":return je(n[0],be);case"root":return je(n[1],je(n[0],me(re.MINUS_ONE)));default:{const t=e.op.startsWith("\\:")?e.op.slice(2):null;return t&&fe.complex&&Ue[t]&&1===n.length?He(Ue[t],n):t&&I(t)&&A(t).arity===n.length?He(t,n):He(e.op,n)}}}(e);return Qe.size>2e4&&Qe.clear(),Qe.set(n,s),s}const Ke=e=>en(Je(e)),Ye=e=>P(String(e));function Ge(e){return e.isInteger?Ye(e.n):V("/",[Ye(e.n),Ye(e.d)])}const Xe=new WeakMap;function en(e){let n=Xe.get(e);return n||Xe.set(e,n=function(e){switch(e.k){case"num":return Ge(e.q);case"atom":return e.node;case"mul":return function(e,n){const t=[],s=[];for(const e of n)we(e.e)&&e.e.q.sign<0?s.push(nn(e.b,me(e.e.q.neg()))):t.push(nn(e.b,e.e));let i=1n!==e.n&&-1n!==e.n||!t.length?tn([Ye(e.n),...t]):tn(t);-1n===e.n&&t.length&&(i=V("neg",[i]));1n!==e.d&&s.unshift(Ye(e.d));return s.length?V("/",[i,tn(s)]):i}(e.c,e.fs);case"add":return function(e){let n=null;const t=e=>fe.complex&&Fe(e.x)&&0===sn(en(e.x)).size,s=[...e.terms.filter(e=>!t(e)),...e.terms.filter(t)],i=e.c,r=()=>{i.isZero||(n=n?i.sign<0?V("-",[n,Ge(i.neg())]):V("+",[n,Ge(i)]):Ge(i))};let o=!1;for(const e of s)!o&&t(e)&&(r(),o=!0),n=n?e.coef.sign<0?V("-",[n,en(Oe(e.coef.neg(),e.x))]):V("+",[n,en(Oe(e.coef,e.x))]):en(Oe(e.coef,e.x));o||r();return n}(e);default:throw new Error(`bad form ${e.k}`)}}(e)),n}function nn(e,n){const t=en(e);if(we(n)){const e=n.q;if(e.isOne)return t;if(1n===e.n&&2n===e.d)return V("sqrt",[t]);if(1n===e.n)return V("root",[Ye(e.d),t])}return V("^",[t,en(n)])}const tn=e=>e.reduce((e,n)=>e?V("*",[e,n]):n,null);function sn(e,n=new Set){if("sym"===e.type)he(e.token)||n.add(e.token);else if(W(e))for(const t of e.args)sn(t,n);return n}function rn(e){if("add"!==e.k)return[e];const n=e.terms.map(e=>Oe(e.coef,e.x));return e.c.isZero||n.push(me(e.c)),n}function on(e){if("num"===e.k)return[e];if("mul"!==e.k)return[e];const n=e.c.isOne?[]:[me(e.c)];for(const t of e.fs)n.push(Ze(t.b,t.e));return n}const an="_",un=new WeakMap;function ln(e,n){return[...n,...A(e.op)?.arity===$?[String(e.args.length)]:[],e.op].join(" ")}function cn(e,n){let t=un.get(e);t||un.set(e,t=new Map);const s=t.get(n);if(s)return s;const i=function(e,n){const t={key:an,slots:[e]};if(e.type!==z||n<=0)return[t];const s=e.args.map(e=>cn(e,n-1)),i=[t],r=new Array(s.length).fill(0);for(;;){const n=[],t=[];for(let e=0;e<s.length;e++){const i=s[e][r[e]];n.push(i.key);for(const e of i.slots)t.push(e)}if(i.push({key:ln(e,n),slots:t}),i.length>=4096)break;let o=s.length-1;for(;o>=0&&!(++r[o]<s[o].length);o--)r[o]=0;if(o<0)break}return i}(e,n);return t.set(n,i),i}function fn(e){return e.type!==z?an:ln(e,e.args.map(fn))}function pn(e,n=[]){if(e.type!==z)n.push(e);else for(const t of e.args)pn(t,n);return n}const hn=new Map,dn=new Map;class mn extends Error{constructor(e){super(e),this.name="RequirementError"}}function gn(e,n,t=""){hn.set(e,{name:e,fn:n,doc:t,arity:Math.max(0,n.length-1)})}function vn(e,n,t=""){dn.set(e,{name:e,fn:n,doc:t})}function bn(e){return hn.get(e)||null}function wn(e){return dn.get(e)||null}const yn=e=>e.type===j;function xn(e,n){return e.type===z&&(e.op===n||e.args.some(e=>xn(e,n)))}gn("always",()=>!0,"matches anything"),gn("never",()=>!1,"matches nothing"),gn("isLeaf",e=>e.type!==z,"a bare operand, not an operation"),gn("isCompound",e=>e.type===z,"an operation, not a bare operand"),gn("isSymbol",e=>e.type===Z,"a non-numeric operand such as x"),gn("isOperation",(e,n)=>e.type===z&&e.op===n,"is this specific operation"),gn("notOperation",(e,n)=>!(e.type===z&&e.op===n),"is anything except this operation"),gn("isNumber",yn,"a numeric literal"),gn("isInteger",e=>yn(e)&&Number.isInteger(e.value),"a whole number"),gn("isPositive",e=>yn(e)&&e.value>0,"greater than zero"),gn("isNegative",e=>yn(e)&&e.value<0,"less than zero"),gn("isNonNegative",e=>yn(e)&&e.value>=0,"zero or greater"),gn("isZero",e=>yn(e)&&0===e.value,"exactly 0"),gn("isOne",e=>yn(e)&&1===e.value,"exactly 1"),gn("isNonZero",e=>yn(e)&&0!==e.value,"a number that is provably not 0"),gn("isNotZeroLiteral",e=>!(yn(e)&&0===e.value),"anything except a literal 0"),gn("isPositiveInteger",e=>yn(e)&&Number.isInteger(e.value)&&e.value>0,"a whole number above 0"),gn("isNegativeInteger",e=>yn(e)&&Number.isInteger(e.value)&&e.value<0,"a whole number below 0"),gn("isEven",e=>yn(e)&&Number.isInteger(e.value)&&e.value%2==0,"a whole even number"),gn("isOdd",e=>yn(e)&&Number.isInteger(e.value)&&1===Math.abs(e.value%2),"a whole odd number"),gn("greaterThan",(e,n)=>yn(e)&&e.value>Number(n),"above a given value"),gn("lessThan",(e,n)=>yn(e)&&e.value<Number(n),"below a given value"),gn("isValue",(e,n)=>yn(e)&&e.value===Number(n),"equals a given number"),gn("isNumeric",Y,"contains no symbols: a constant (it need not fold to a number: 1 sin)"),gn("hasSymbol",e=>!Y(e),"mentions a symbol somewhere, so it is not just a number"),gn("isVar",(e,n)=>e.type===Z&&e.token===String(n),"is exactly this symbol"),gn("contains",(e,n)=>K(e).includes(String(n)),"mentions this operand somewhere"),gn("isFree",(e,n)=>!K(e).includes(String(n)),"never mentions this operand"),gn("hasOperation",(e,n)=>xn(e,String(n)),"uses this operation somewhere inside"),gn("equals",(e,n)=>e.s===String(n),"is exactly this postfix expression");const qn=e=>e.type===z?null:e.token;function kn(e){if("string"==typeof e)return{name:e,args:[]};if(Array.isArray(e)&&e.length>0&&"string"==typeof e[0])return{name:e[0],args:e.slice(1)};throw new mn(`bad requirement: ${JSON.stringify(e)}`)}vn("freeOf",(e,n)=>{const t=qn(n);return null!==t&&!K(e).includes(t)},"the first operand never mentions the second"),vn("dependsOn",(e,n)=>{const t=qn(n);return null!==t&&K(e).includes(t)},"the first operand does mention the second"),vn("sameAs",(...e)=>e.every(n=>n.s===e[0].s),"these operands are structurally identical"),vn("differs",(...e)=>new Set(e.map(e=>e.s)).size===e.length,"these operands are all different"),vn("sameValue",(...e)=>e.every(e=>yn(e))&&e.every(n=>n.value===e[0].value),"these operands are the same number");const $n="simplify";class Sn extends Error{constructor(e,n){super(n?`rule "${n}": ${e}`:e),this.name="RuleError",this.ruleId=n}}const Mn=/^[A-Za-z_][A-Za-z0-9_]*$/;function Nn(e,n){if(L(e))return{literal:e.value};const t=e.token;if(t.startsWith("=")){const e=t.slice(1);if(""===e)throw new Sn('"=" needs an operand after it',n);return{token:e}}if(!Mn.test(t))throw new Sn(`"${t}" is not a usable slot name; use letters, digits and _`,n);if(I(t))throw new Sn(`slot name "${t}" collides with an operator`,n);return{name:t}}function On(e){if(!W(e))return[e];const n=e.args.map(On),t=A(e.op),s=[];for(const i of function(e){let n=[[]];for(const t of e){const e=[];for(const s of n)for(const n of t)e.push(s.concat([n]));if(n=e,n.length>64)return n.slice(0,64)}return n}(n))if(s.push(V(e.op,i)),t.commutative&&2===i.length&&i[0].s!==i[1].s&&s.push(V(e.op,[i[1],i[0]])),s.length>=64)break;return s}function An(e,n=[]){return"op"===e.kind?e.args.forEach(e=>An(e,n)):"const"===e.kind&&e.free&&n.push(e.node.token),n}function In(e){if(!e||"object"!=typeof e)throw new Sn("rule must be a mapping");const n=e.id||e.name;if(!n)throw new Sn("rule needs an id");if(!e.pattern)throw new Sn("rule needs a pattern",n);if(void 0===e.output||null===e.output)throw new Sn("rule needs an output",n);let t;try{t=_(String(e.pattern))}catch(e){if(e instanceof B)throw new Sn(`bad pattern: ${e.message}`,n);throw e}const s=pn(t).map(e=>Nn(e,n)),i=new Set(s.filter(e=>e.name).map(e=>e.name)),r=function(e,n,t){const s=[],i=e.when||{};if("object"!=typeof i||Array.isArray(i))throw new Sn('"when" must map slot names to lists of requirements',t);for(const[e,r]of Object.entries(i)){if(!n.has(e))throw new Sn(`"when" mentions "${e}", which is not a slot in the pattern`,t);const i=Array.isArray(r)?r:[r];for(const n of i){const{name:i,args:r}=kn(n),o=bn(i);if(!o)throw new Sn(`unknown requirement "${i}"`,t);s.push({slot:e,name:i,args:r,fn:o.fn})}}return s}(e,i,n),o=function(e,n,t){const s=[],i=e.require||[];if(!Array.isArray(i))throw new Sn('"require" must be a list of relations',t);for(const e of i){const{name:i,args:r}=kn(e),o=wn(i);if(!o)throw new Sn(`unknown relation "${i}"`,t);if(r.length<2)throw new Sn(`relation "${i}" needs at least two operands`,t);for(const e of r)if("string"==typeof e&&!n.has(e)&&Mn.test(e))throw new Sn(`relation "${i}" mentions "${e}", which is not a slot in the pattern`,t);s.push({name:i,args:r,fn:o.fn})}return s}(e,i,n),a=function(e,n,t){let s;try{s=_(e)}catch(n){throw new Sn(`bad output "${e}": ${n.message}`,t)}const i=e=>W(e)?{kind:"op",op:e.op,args:e.args.map(i)}:L(e)?{kind:"const",node:e}:n.has(e.token)?{kind:"slot",name:e.token}:e.token.startsWith("=")?{kind:"const",node:D(e.token.slice(1))}:{kind:"const",node:e,free:!0};return i(s)}(String(e.output),i,n),u=e.commutative?On(t):[t],l=[],c=new Set;for(const e of u){const t=fn(e),s=pn(e).map(e=>Nn(e,n)),i=t+"\0"+s.map(e=>e.name??(void 0!==e.literal?`#${e.literal}`:`=${e.token}`)).join(",");c.has(i)||(c.add(i),l.push({key:t,slots:s}))}const f={id:String(n),name:e.name?String(e.name):String(n),pattern:String(e.pattern),patternTree:t,output:String(e.output),outputTemplate:a,explain:e.explain?String(e.explain).trim():"",mode:e.mode?String(e.mode):$n,tags:Array.isArray(e.tags)?e.tags.map(String):[],priority:Number.isFinite(e.priority)?e.priority:0,fold:!!e.fold,commutative:!!e.commutative,enabled:void 0===e.enabled||!!e.enabled,when:r,require:o,slots:[...i],depth:Q(t),bindings:l,freeSymbols:An(a),source:e};for(const e of l)e.rule=f;return f}function En(e){const n={};for(const t of e.when)(n[t.slot]||=[]).push(t.args.length?[t.name,...t.args]:t.name);const t={id:e.id};return e.name!==e.id&&(t.name=e.name),e.mode!==$n&&(t.mode=e.mode),t.pattern=e.pattern,Object.keys(n).length&&(t.when=n),e.require.length&&(t.require=e.require.map(e=>[e.name,...e.args])),t.output=e.output,e.explain&&(t.explain=e.explain),e.fold&&(t.fold=!0),e.commutative&&(t.commutative=!0),e.priority&&(t.priority=e.priority),e.tags.length&&(t.tags=e.tags),e.enabled||(t.enabled=!1),t}class Tn extends Error{constructor(e,n){super(null==n?e:`${e} (line ${n+1})`),this.name="YamlError",this.line=n}}class jn{constructor(e){this.records=e,this.i=0,this.pushed=[]}peek(){if(this.pushed.length)return this.pushed[this.pushed.length-1];for(;this.i<this.records.length&&this.records[this.i].blank;)this.i++;return this.i<this.records.length?this.records[this.i]:null}next(){if(this.pushed.length)return this.pushed.pop();const e=this.peek();return e&&this.i++,e}push(e){this.pushed.push(e)}}const Zn=e=>"-"===e||e.startsWith("- ");function zn(e){let n=null,t=0;for(let s=0;s<e.length;s++){const i=e[s];if(n)i===n?"'"===n&&"'"===e[s+1]?s++:n=null:'"'===n&&"\\"===i&&s++;else if('"'===i||"'"===i)n=i;else if("["===i||"{"===i)t++;else if("]"===i||"}"===i)t--;else if(":"===i&&0===t&&(s+1===e.length||" "===e[s+1])){const n=e.slice(0,s).trim();return""===n?null:{key:Fn(n),rest:e.slice(s+1).trim()}}}return null}function Fn(e){return e.length>=2&&'"'===e[0]&&'"'===e[e.length-1]?JSON.parse(e):e.length>=2&&"'"===e[0]&&"'"===e[e.length-1]?e.slice(1,-1).replace(/''/g,"'"):e}function Bn(e){const n=new jn(function(e){return String(e).split(/\r?\n/).map((e,n)=>{const t=e.search(/\S/);if(-1===t)return{raw:e,n:n,indent:0,text:"",blank:!0};const s=function(e){let n=null;for(let t=0;t<e.length;t++){const s=e[t];if(n)s===n?"'"===n&&"'"===e[t+1]?t++:n=null:'"'===n&&"\\"===s&&t++;else if('"'===s||"'"===s)n=s;else if("#"===s&&(0===t||/\s/.test(e[t-1])))return e.slice(0,t)}return e}(e.slice(t)).trimEnd();return{raw:e,n:n,indent:t,text:s,blank:""===s}})}(e));let t=n.peek();if(t&&"---"===t.text&&(n.next(),t=n.peek()),!t)return null;const s=Dn(n,t.indent),i=n.peek();if(i&&"..."!==i.text&&"---"!==i.text)throw new Tn(`unexpected content "${i.text}"`,i.n);return s}const Cn=/^[|>][-+]?\d*$/;function Dn(e,n){const t=e.peek();return!t||t.indent<n?null:Zn(t.text)?Pn(e,t.indent):zn(t.text)?function(e,n){const t={};for(;;){const s=e.peek();if(!s||s.indent!==n)break;const i=zn(s.text);if(!i)break;e.next();const{key:r,rest:o}=i;if(""===o){const s=e.peek();s&&s.indent>n?t[r]=Dn(e,s.indent):s&&s.indent===n&&Zn(s.text)?t[r]=Pn(e,n):t[r]=null}else Cn.test(o)?t[r]=Rn(e,o,n):t[r]=Un(o,s.n)}return t}(e,t.indent):(e.next(),Cn.test(t.text)?Rn(e,t.text,t.indent-1):Un(t.text,t.n))}function Pn(e,n){const t=[];for(;;){const s=e.peek();if(!s||s.indent!==n||!Zn(s.text))break;if(e.next(),"-"===s.text){const s=e.peek();t.push(s&&s.indent>n?Dn(e,s.indent):null);continue}if(Cn.test(s.text.slice(2).trim())){t.push(Rn(e,s.text.slice(2).trim(),n));continue}const i=s.text.slice(2),r=n+2+(i.length-i.trimStart().length);e.push({raw:s.raw,n:s.n,indent:r,text:i.trim(),blank:!1}),t.push(Dn(e,r))}return t}function Rn(e,n,t){const s=n[0],i=(n.match(/[-+]/)||[""])[0],r=(n.match(/\d+/)||[null])[0];let o=r?t+Number(r):null;const a=[];for(;e.i<e.records.length;){const n=e.records[e.i];if(""===n.raw.trim()){a.push(""),e.i++;continue}const s=n.raw.search(/\S/);if(s<=t)break;if(null===o&&(o=s),s<o)break;a.push(n.raw.slice(o)),e.i++}for(;a.length&&""===a[a.length-1];)a.pop();let u;if("|"===s)u=a.join("\n");else{const e=[];for(const n of a)""===n?e.push("\n"):e.length&&"\n"!==e[e.length-1]?e[e.length-1]+=" "+n:e.push(n);u=e.join("").replace(/\n(?!$)/g,"\n")}return"-"===i?u:"+"===i?u+"\n":""===u?"":u+"\n"}function Un(e,n){const t=e.trim();return""===t||"~"===t||"null"===t||"Null"===t||"NULL"===t?null:"true"===t||"True"===t||"TRUE"===t||"false"!==t&&"False"!==t&&"FALSE"!==t&&("["===t[0]||"{"===t[0]?function(e,n){const t={text:e,i:0,line:n},s=Ln(t);if(Vn(t),t.i<t.text.length)throw new Tn(`unexpected "${t.text.slice(t.i)}" in flow value`,n);return s}(t,n):'"'===t[0]||"'"===t[0]?Fn(t):/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(t)?Number(t):t)}const Vn=e=>{for(;e.i<e.text.length&&/\s/.test(e.text[e.i]);)e.i++};function Ln(e){Vn(e);const n=e.text[e.i];return"["===n?function(e){e.i++;const n=[];for(;;){if(Vn(e),e.i>=e.text.length)throw new Tn("unterminated [",e.line);if("]"===e.text[e.i])return e.i++,n;if(n.push(Ln(e)),Vn(e),","===e.text[e.i])e.i++;else if("]"!==e.text[e.i])throw new Tn(`expected , or ] near "${e.text.slice(e.i)}"`,e.line)}}(e):"{"===n?function(e){e.i++;const n={};for(;;){if(Vn(e),e.i>=e.text.length)throw new Tn("unterminated {",e.line);if("}"===e.text[e.i])return e.i++,n;const t=String(Ln(e));if(Vn(e),":"!==e.text[e.i])throw new Tn(`expected : after "${t}"`,e.line);if(e.i++,n[t]=Ln(e),Vn(e),","===e.text[e.i])e.i++;else if("}"!==e.text[e.i])throw new Tn(`expected , or } near "${e.text.slice(e.i)}"`,e.line)}}(e):Un(function(e){const n=e.text[e.i];if('"'===n||"'"===n){const t=e.i;for(e.i++;e.i<e.text.length;)if("\\"===e.text[e.i]&&'"'===n)e.i+=2;else if(e.text[e.i]===n){if("'"!==n||"'"!==e.text[e.i+1])return e.i++,e.text.slice(t,e.i);e.i+=2}else e.i++;throw new Tn("unterminated quoted string",e.line)}const t=e.i;for(;e.i<e.text.length;){const n=e.text[e.i];if(","===n||"]"===n||"}"===n)break;if(":"===n){const n=e.text[e.i+1];if(void 0===n||/[\s,\]}]/.test(n))break}e.i++}return e.text.slice(t,e.i).trim()}(e),e.line)}const Wn=/^(true|false|null|yes|no|on|off|~)$/i;function _n(e){if(null==e)return"null";if("boolean"==typeof e)return e?"true":"false";if("number"==typeof e){if(!Number.isFinite(e))throw new Tn(`cannot serialize ${e}`);return String(e)}const n=String(e);return function(e){return!!(""===e||/^\s|\s$/.test(e)||/[\u0000-\u001f\u007f]/.test(e)||/^[-?:,[\]{}#&*!|>'"%@`]/.test(e)||/: |\s#/.test(e)||Wn.test(e)||/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(e))}(n)?JSON.stringify(n):n}const Hn=e=>null==e||"object"!=typeof e;function Qn(e){return Array.isArray(e)?`[${e.map(Qn).join(", ")}]`:e&&"object"==typeof e?`{${Object.entries(e).map(([e,n])=>`${_n(e)}: ${Qn(n)}`).join(", ")}}`:_n(e)}function Jn(e){return Array.isArray(e)?!!e.every(e=>Hn(e)||Array.isArray(e)&&e.every(Hn))&&Qn(e).length<=72:!(!e||"object"!=typeof e)&&(Object.values(e).every(e=>Hn(e)||Array.isArray(e)&&e.every(Hn))&&Qn(e).length<=72)}function Kn(e){const n=[];return Yn(e,0,n),n.length?n.join("\n")+"\n":""}function Yn(e,n,t){const s=" ".repeat(n);if(Array.isArray(e)){if(0===e.length)return void t.push(s+"[]");for(const s of e)Gn(s,n,t)}else{if(e&&"object"==typeof e){const i=Object.entries(e).filter(([,e])=>void 0!==e);if(0===i.length)return void t.push(s+"{}");for(const[e,s]of i)Xn(e,s,n,t);return}!function(e,n,t){if("string"==typeof e&&e.includes("\n")){t.push(n+"|-");for(const s of e.replace(/\n+$/,"").split("\n"))t.push(n+" "+s);return}t.push(n+_n(e))}(e,s,t)}}function Gn(e,n,t){const s=" ".repeat(n);if(null!==e&&"object"==typeof e&&!Jn(e)){const i=[];if(Yn(e,n+2,i),0===i.length)return void t.push(s+"-");t.push(s+"- "+i[0].slice(n+2));for(let e=1;e<i.length;e++)t.push(i[e]);return}if(null===e||"object"!=typeof e)if("string"==typeof e&&e.includes("\n")){t.push(s+"- |-");for(const s of e.replace(/\n+$/,"").split("\n"))t.push(" ".repeat(n+4)+s)}else t.push(s+"- "+_n(e));else t.push(s+"- "+Qn(e))}function Xn(e,n,t,s){const i=" ".repeat(t),r=_n(e);if("string"==typeof n&&n.includes("\n")){s.push(`${i}${r}: |-`);for(const e of n.replace(/\n+$/,"").split("\n"))s.push(" ".repeat(t+2)+e)}else{if(null!==n&&"object"==typeof n)return Jn(n)?void s.push(`${i}${r}: ${Qn(n)}`):(s.push(`${i}${r}:`),void Yn(n,Array.isArray(n)?t:t+2,s));s.push(`${i}${r}: ${_n(n)}`)}}class et{constructor(e=[]){this.index=new Map,this.rules=[],this.maxDepth=0,this.name="",this.views=new Map;for(const n of e)this.add(n)}add(e){const n=e&&e.bindings?e:In(e);if(this.rules.some(e=>e.id===n.id))throw new Sn(`duplicate rule id "${n.id}"`);return this.rules.push(n),n.enabled&&this.link(n),n.depth>this.maxDepth&&(this.maxDepth=n.depth),this.views.clear(),n}view(e){if(!e)return this;let n=this.views.get(e);return n||(n=new et(this.rules.filter(n=>n.mode===e)),n.name=this.name,this.views.set(e,n)),n}modes(){return[...new Set(this.rules.map(e=>e.mode))].sort((e,n)=>e===$n?-1:n===$n?1:e.localeCompare(n))}link(e){for(const n of e.bindings){let e=this.index.get(n.key);e||this.index.set(n.key,e=[]),e.push(n),e.sort((e,n)=>n.rule.priority-e.rule.priority||n.rule.depth-e.rule.depth)}}remove(e){const n=this.rules.findIndex(n=>n.id===e);return-1!==n&&(this.rules.splice(n,1),this.reindex(),!0)}setEnabled(e,n){const t=this.get(e);return!!t&&(t.enabled=!!n,this.reindex(),!0)}reindex(){this.index=new Map,this.maxDepth=0,this.views.clear();for(const e of this.rules)e.enabled&&this.link(e),e.depth>this.maxDepth&&(this.maxDepth=e.depth)}get(e){return this.rules.find(n=>n.id===e)||null}candidates(e){return this.index.get(e)||null}get size(){return this.rules.length}static fromYaml(e,{strict:n=!0}={}){const t=Bn(e);return et.fromSpecs(t,{strict:n})}static fromSpecs(e,{strict:n=!0}={}){let t=e,s="";if(e&&!Array.isArray(e)&&"object"==typeof e&&(t=e.rules,s=e.name?String(e.name):""),!Array.isArray(t))throw new Sn('expected a list of rules, or a mapping with a "rules" list');const i=new et;i.name=s;const r=[];for(let e=0;e<t.length;e++)try{i.add(t[e])}catch(n){r.push(`#${e+1}: ${n.message}`)}if(r.length&&n)throw new Sn(`${r.length} rule(s) failed to compile:\n ${r.join("\n ")}`);return i.errors=r,i}toSpecs(){return this.rules.map(En)}toYaml(){const e=this.toSpecs();return this.name?Kn({name:this.name,rules:e}):Kn(e)}keyReport(){return[...this.index.entries()].map(([e,n])=>({key:e,rules:n.map(e=>e.rule.id)})).sort((e,n)=>e.key.localeCompare(n.key))}}function nt(e,n){const t=Object.create(null),s=e.slots;for(let e=0;e<s.length;e++){const i=s[e],r=n[e];if(void 0!==i.literal){if(!L(r)||r.value!==i.literal)return null;continue}if(void 0!==i.token){if(r.s!==i.token)return null;continue}const o=t[i.name];if(void 0!==o){if(o.s!==r.s)return null}else t[i.name]=r}return t}function tt(e,n){for(const t of e.when){const e=n[t.slot];if(void 0===e)return!1;if(!t.fn(e,...t.args))return!1}for(const t of e.require){const e=t.args.map(e=>void 0!==n[e]?n[e]:e);if(!t.fn(...e))return!1}return!0}function st(e,n){return n.rule.priority-e.rule.priority||n.rule.depth-e.rule.depth}function it(e,n){const t=[];if(0===n.maxDepth)return t;for(const{key:s,slots:i}of function(e,n){const t=cn(e,n),s=[];for(const e of t)e.key!==an&&s.push(e);return s}(e,n.maxDepth)){const e=n.candidates(s);if(e)for(const n of e){const e=nt(n,i);e&&(tt(n.rule,e)&&t.push({rule:n.rule,binding:n,key:s,bound:e}))}}return t.sort(st)}function rt(e,n){switch(e.kind){case"slot":{const t=n[e.name];if(!t)throw new Error(`output references unbound slot "${e.name}"`);return t}case"const":return e.node;case"op":return V(e.op,e.args.map(e=>rt(e,n)));default:throw new Error(`bad output template: ${JSON.stringify(e)}`)}}const ot=4e5,at=()=>new ee("a number too large to approximate"),ut=e=>e<0n?-e:e;class lt{constructor(e){this.P=e,this.S=10n**BigInt(e),this.cache=new Map}fromQ(e){return e.n*this.S/e.d}mul(e,n){return e*n/this.S}div(e,n){if(0n===n)throw new ee("division by zero");return e*this.S/n}sqrt(e){if(e<0n)throw new ee("the square root of a negative number is not real");return ae(e*this.S,2)}series(e,n){let t=0n,s=e;for(let e=1;0n!==s;e++)if(t+=s,s=n(s,e),e>1e5)throw new ee("a series did not converge");return t}atanhInv(e){const n=BigInt(e),t=n*n;let s=this.S/n,i=0n;for(let e=1n;0n!==s;e+=2n)i+=s/e,s/=t;return i}atanInv(e){const n=BigInt(e),t=n*n;let s=this.S/n,i=0n;for(let e=1n,n=1n;0n!==s;e+=2n,n=-n)i+=n*s/e,s/=t;return i}get pi(){return this.memo("pi",()=>16n*this.atanInv(5)-4n*this.atanInv(239))}get ln2(){return this.memo("ln2",()=>2n*this.atanhInv(3))}get e(){return this.memo("e",()=>this.exp(this.S))}memo(e,n){return this.cache.has(e)||this.cache.set(e,n()),this.cache.get(e)}exp(e){const n=(e+(e>=0n?this.ln2/2n:-this.ln2/2n))/this.ln2;if(n>BigInt(ot))throw at();if(n<-BigInt(ot))return 0n;const t=e-n*this.ln2,s=this.series(this.S,(e,n)=>e*t/this.S/BigInt(n));return n>=0n?s<<n:s>>-n}ln(e){if(e<=0n)throw new ee("the log of a number that is not positive is not real");let n=0n,t=e;for(;t>=this.S;)t>>=1n,n++;for(;t<this.S/2n;)t<<=1n,n--;const s=this.div(t-this.S,t+this.S),i=this.mul(s,s);let r=s,o=0n;for(let e=1n;0n!==r;e+=2n)o+=r/e,r=this.mul(r,i);return 2n*o+n*this.ln2}sin(e){const n=2n*this.pi;let t=e%n;t>this.pi&&(t-=n),t<-this.pi&&(t+=n);const s=this.mul(t,t);return this.series(t,(e,n)=>-e*s/this.S/BigInt(2*n*(2*n+1)))}cos(e){return this.sin(e+this.pi/2n)}atan(e){if(ut(e)>this.S){const n=this.pi/2n;return(e>0n?n:-n)-this.atan(this.div(this.S,e))}let n=e;for(let e=0;e<2;e++)n=this.div(n,this.S+this.sqrt(this.S+this.mul(n,n)));const t=this.mul(n,n);let s=n,i=0n;for(let e=1n,n=1n;0n!==s;e+=2n,n=-n)i+=n*s/e,s=this.mul(s,t);return 4n*i}asin(e){if(ut(e)>this.S)throw new ee("arcsin of a number beyond ±1 is not real");return ut(e)===this.S?e>0n?this.pi/2n:-this.pi/2n:this.atan(this.div(e,this.sqrt(this.S-this.mul(e,e))))}}function ct(e,n,t){if(t>0n)return e.atan(e.div(n,t));if(t<0n)return e.atan(e.div(n,t))+(n>=0n?e.pi:-e.pi);if(0n===n)throw new ee("the argument of 0 is undefined");return n>0n?e.pi/2n:-e.pi/2n}const ft={add:(e,n)=>[e[0]+n[0],e[1]+n[1]],sub:(e,n)=>[e[0]-n[0],e[1]-n[1]],mul:(e,n,t)=>[e.mul(n[0],t[0])-e.mul(n[1],t[1]),e.mul(n[0],t[1])+e.mul(n[1],t[0])],div(e,n,t){const s=e.mul(t[0],t[0])+e.mul(t[1],t[1]);if(0n===s)throw new ee("division by zero");return[e.div(e.mul(n[0],t[0])+e.mul(n[1],t[1]),s),e.div(e.mul(n[1],t[0])-e.mul(n[0],t[1]),s)]},abs:(e,n)=>e.sqrt(e.mul(n[0],n[0])+e.mul(n[1],n[1])),exp(e,n){const t=e.exp(n[0]);return[e.mul(t,e.cos(n[1])),e.mul(t,e.sin(n[1]))]},ln(e,n){const t=ft.abs(e,n);if(0n===t)throw new ee("the log of 0 is undefined");return[e.ln(t),ct(e,n[1],n[0])]},pow(e,n,t,s){if(0n===n[0]&&0n===n[1])return[0n,0n];if(s&&s.isInteger){let t=s.n<0n?-s.n:s.n,i=[e.S,0n],r=n;for(;t>0n;)1n&t&&(i=ft.mul(e,i,r)),r=ft.mul(e,r,r),t>>=1n;return s.n<0n?ft.div(e,[e.S,0n],i):i}return ft.exp(e,ft.mul(e,t,ft.ln(e,n)))},sinh:(e,n)=>(e.exp(n)-e.exp(-n))/2n,cosh:(e,n)=>(e.exp(n)+e.exp(-n))/2n},pt={sin:(e,[n,t])=>[e.mul(e.sin(n),ft.cosh(e,t)),e.mul(e.cos(n),ft.sinh(e,t))],cos:(e,[n,t])=>[e.mul(e.cos(n),ft.cosh(e,t)),-e.mul(e.sin(n),ft.sinh(e,t))],tan:(e,n)=>ft.div(e,pt.sin(e,n),pt.cos(e,n)),ln:(e,n)=>ft.ln(e,n),sqrt:(e,n)=>ft.exp(e,ft.mul(e,[e.S/2n,0n],ft.ln(e,n))),sinh:(e,[n,t])=>[e.mul(ft.sinh(e,n),e.cos(t)),e.mul(ft.cosh(e,n),e.sin(t))],cosh:(e,[n,t])=>[e.mul(ft.cosh(e,n),e.cos(t)),e.mul(ft.sinh(e,n),e.sin(t))]},ht=e=>({q:e}),dt=([e,n])=>0n===n?{f:e}:{z:[e,n]};function mt(e,n,t){const s=e=>((e,n)=>n.z??[gt(e,n),0n])(t,n[e]);switch(e.op){case"+":return dt(ft.add(s(0),s(1)));case"-":return dt(ft.sub(s(0),s(1)));case"neg":return dt([-s(0)[0],-s(0)[1]]);case"*":return dt(ft.mul(t,s(0),s(1)));case"/":return dt(ft.div(t,s(0),s(1)));case"^":return dt(ft.pow(t,s(0),s(1),n[1].q));case"sqrt":return dt(pt.sqrt(t,s(0)));case"root":return dt(ft.pow(t,s(1),ft.div(t,[t.S,0n],s(0)),n[0].q?.inv()));case"abs":return{f:ft.abs(t,s(0))};case"arg":return{f:ct(t,s(0)[1],s(0)[0])};case"re":return{f:s(0)[0]};case"im":return{f:s(0)[1]};case"conj":return dt([s(0)[0],-s(0)[1]]);case"log":return dt(ft.div(t,ft.ln(t,s(1)),ft.ln(t,s(0))));default:{const i=pt[e.op];if(!i||1!==n.length)throw new ee(`no complex value for ${e.op}`);return dt(i(t,s(0)))}}}function gt(e,n){return n.q?e.fromQ(n.q):n.f}const vt={sin:(e,n)=>e.sin(n),cos:(e,n)=>e.cos(n),tan:(e,n)=>e.div(e.sin(n),e.cos(n)),sec:(e,n)=>e.div(e.S,e.cos(n)),csc:(e,n)=>e.div(e.S,e.sin(n)),cot:(e,n)=>e.div(e.cos(n),e.sin(n)),arcsin:(e,n)=>e.asin(n),arccos:(e,n)=>e.pi/2n-e.asin(n),arctan:(e,n)=>e.atan(n),arcsec:(e,n)=>{if(ut(n)<e.S)throw new ee("arcsec of a number between -1 and 1 is not real");return e.pi/2n-e.asin(e.div(e.S,n))},arccsc:(e,n)=>{if(ut(n)<e.S)throw new ee("arccsc of a number between -1 and 1 is not real");return e.asin(e.div(e.S,n))},arccot:(e,n)=>e.pi/2n-e.atan(n),sinh:(e,n)=>(e.exp(n)-e.exp(-n))/2n,cosh:(e,n)=>(e.exp(n)+e.exp(-n))/2n,tanh:(e,n)=>{const t=e.exp(n),s=e.exp(-n);return e.div(t-s,t+s)},arcsinh:(e,n)=>e.ln(n+e.sqrt(e.mul(n,n)+e.S)),arccosh:(e,n)=>{if(n<e.S)throw new ee("arccosh of a number below 1 is not real");return e.ln(n+e.sqrt(e.mul(n,n)-e.S))},arctanh:(e,n)=>{if(ut(n)>=e.S)throw new ee("arctanh of a number beyond ±1 is not real");return e.ln(e.div(e.S+n,e.S-n))/2n},ln:(e,n)=>e.ln(n),loglog:(e,n)=>e.ln(e.ln(n)),logloglog:(e,n)=>e.ln(e.ln(e.ln(n))),expm1:(e,n)=>e.exp(n)-e.S};function bt(e,n,t){if("num"===e.type)return ht(oe(e.token));if("sym"===e.type){if("pi"===e.token||"π"===e.token)return{f:n.pi};if("e"===e.token)return{f:n.e};if("i"===e.token&&fe.complex)return{z:[0n,n.S]};if(t&&e.token in t){const n=t[e.token],s="number"==typeof n||"string"==typeof n||"bigint"==typeof n?oe(String(n)):null;if(!s)throw new ee(`the value of ${e.token} is not a number`);return ht(s)}throw new ee(`${e.token} has no value`)}fe.complex&&e.op.startsWith("\\:")&&Ue[e.op.slice(2)]&&(e=V(Ue[e.op.slice(2)],e.args));const s=e.args.map(e=>bt(e,n,t));if(s.some(e=>e.z)||["re","im","conj","arg"].includes(e.op)||function(e,n){if(!fe.complex)return!1;const t=e=>e.q?e.q.sign<0:void 0!==e.f&&e.f<0n;return"sqrt"===e.op||"ln"===e.op||"log"===e.op?t(n["log"===e.op?1:0])||"log"===e.op&&t(n[0]):"^"===e.op?t(n[0])&&!(n[1].q&&n[1].q.d%2n==1n):"root"===e.op&&t(n[1])&&!(n[0].q&&n[0].q.isInteger&&n[0].q.n%2n==1n)}(e,s))return mt(e,s,n);const i=s.every(e=>e.q),r=e=>gt(n,s[e]);switch(e.op){case"+":return i?ht(s[0].q.add(s[1].q)):{f:r(0)+r(1)};case"-":return i?ht(s[0].q.sub(s[1].q)):{f:r(0)-r(1)};case"neg":return s[0].q?ht(s[0].q.neg()):{f:-s[0].f};case"*":return i?ht(s[0].q.mul(s[1].q)):{f:n.mul(r(0),r(1))};case"/":return i?ht(s[0].q.div(s[1].q)):{f:n.div(r(0),r(1))};case"^":return yt(n,s[0],s[1]);case"sqrt":return yt(n,s[0],ht(re.HALF));case"root":return yt(n,s[1],s[0].q?ht(s[0].q.inv()):{f:n.div(n.S,s[0].f)});case"abs":return s[0].q?ht(s[0].q.abs()):{f:ut(s[0].f)};case"floor":return ht(s[0].q?s[0].q.floor():new re(wt(s[0].f,n.S)));case"ceil":return ht(s[0].q?s[0].q.ceil():new re(-wt(-s[0].f,n.S)));case"log":return{f:n.div(n.ln(r(1)),n.ln(r(0)))};case"atan2":return{f:ct(n,r(0),r(1))};case"max":case"min":if(!s.length)throw new ee(`${e.op} of nothing`);return i?ht(s.map(e=>e.q).reduce((n,t)=>("max"===e.op?t.sub(n).sign>0:t.sub(n).sign<0)?t:n)):{f:s.map((e,n)=>r(n)).reduce((n,t)=>"max"===e.op?t>n?t:n:t<n?t:n)};case"sum":return i?ht(s.reduce((e,n)=>e.add(n.q),re.ZERO)):{f:s.reduce((e,n,t)=>e+r(t),0n)};case"prod":return i?ht(s.reduce((e,n)=>e.mul(n.q),re.ONE)):{f:s.reduce((e,t,s)=>n.mul(e,r(s)),n.S)};case"mean":if(!s.length)throw new ee("mean of nothing");return i?ht(s.reduce((e,n)=>e.add(n.q),re.ZERO).div(new re(BigInt(s.length)))):{f:s.reduce((e,n,t)=>e+r(t),0n)/BigInt(s.length)};case"mod":{if(i){if(s[1].q.isZero)throw new ee("mod 0 is undefined");return ht(s[0].q.sub(s[1].q.mul(s[0].q.div(s[1].q).floor())))}const e=r(1);if(0n===e)throw new ee("mod 0 is undefined");return{f:r(0)-n.mul(e,wt(n.div(r(0),e),n.S)*n.S)}}case"round":{if(!s[1].q?.isInteger)throw new ee("round needs a whole number of places");const e=10n**ut(s[1].q.n),t=s[0].q??new re(r(0),n.S),i=s[1].q.sign>=0,o=(i?t.mul(new re(e)):t.div(new re(e))).add(re.HALF).floor();return ht(i?o.div(new re(e)):o.mul(new re(e)))}case"!":{if(!s[0].q?.isInteger||s[0].q.sign<0)throw new ee("factorial is only worked out for whole numbers");let e=1n;for(let n=2n;n<=s[0].q.n;n++)if(e*=n,0n==(255n&n)&&se(e)>ot)throw at();return ht(new re(e))}default:{const t=vt[e.op];if(!t||1!==s.length)throw new ee(`no numeric value for ${e.op}`);return{f:t(n,r(0))}}}}const wt=(e,n)=>{const t=e/n;return e<0n&&t*n!==e?t-1n:t};function yt(e,n,t){if(t.q&&t.q.isInteger){if(n.q)return ht(n.q.pow(t.q.n));let s=t.q.n;const i=s<0n;i&&(s=-s);let r=e.S,o=n.f;for(;s>0n;){if(1n&s&&(r=e.mul(r,o)),o=e.mul(o,o),se(r)>ot+4*e.P||se(o)>8e5){if(i)return{f:0n};throw at()}s>>=1n}return{f:i?e.div(e.S,r):r}}const s=gt(e,n);if(0n===s){if(t.q?t.q.sign>0:t.f>0n)return ht(re.ZERO);throw new ee("0 to a power that is not positive is undefined")}if(s<0n){if(t.q&&t.q.d%2n==1n){const n=yt(e,{f:-s},t).f;return{f:t.q.n%2n==0n?n:-n}}throw new ee("a negative number to a fractional power is not real")}if(t.q&&1n===ut(t.q.n)&&t.q.d<=64n){const n=ae(s*e.S**(t.q.d-1n),Number(t.q.d));return{f:t.q.n<0n?e.div(e.S,n):n}}return{f:e.exp(e.mul(gt(e,t),e.ln(s)))}}function xt(e,n,t){const s=e<0n?"-":"",i=ut(e);if(0n===i)return{sign:"",digits:"0",point:1};const r=i.toString(),o=r.length-n.P;let a=r.slice(0,t);r.length>t&&r[t]>="5"&&(a=(BigInt(a)+1n).toString());let u=o;return a.length>t&&(a=a.slice(0,t),u++),{sign:s,digits:a.replace(/0+$/,"")||"0",point:u}}function qt({sign:e,digits:n,point:t}){if("0"===n)return"0";if(t>21||t<-6){return`${e}${n.length>1?`${n[0]}.${n.slice(1)}`:n}e${t-1}`}return t<=0?`${e}0.${"0".repeat(-t)}${n}`:t>=n.length?`${e}${n}${"0".repeat(t-n.length)}`:`${e}${n.slice(0,t)}.${n.slice(t)}`}function kt(e){let n=0n,t=0n,s=e.d;for(;s%2n==0n;)s/=2n,n++;for(;s%5n==0n;)s/=5n,t++;const i=n>t?n:t;let r=ut(e.n)*10n**i/e.d;if(0n===r)return 1;for(;r%10n==0n;)r/=10n;return r.toString().length}function $t(e){let n=e.d;for(;n%2n==0n;)n/=2n;for(;n%5n==0n;)n/=5n;return 1n===n}function St(e){const n=/^(-?[\d.]+)e(-?\d+)$/.exec(e);return n?V("*",[P(n[1]),V("^",[P("10"),P(n[2])])]):P(e)}function Mt(e,{digits:n=15,scope:t}={}){if(!Number.isInteger(n)||n<1||n>1e5)throw new ee("digits must be a whole number from 1 to 100000");let s=n+25,i=null;for(let r=0;r<4;r++){const o=new lt(s),a=bt(e,o,t);if(a.z){const e=Ot(a.z,o,n);if(e.retry&&r<3){s+=e.retry;continue}return void 0===e.real?e:Nt(e.real,o,n,null)}if(a.q&&a.q.isInteger&&ut(a.q.n).toString().length<=n)return{text:a.q.n.toString(),node:P(a.q.n.toString()),number:Number(a.q.n),re:Number(a.q.n),im:0,exact:!0};const u=gt(o,a);if(0n===u&&(!a.q||!a.q.isZero)&&r<3){i=null,s*=4;continue}const l=xt(u,o,n);if(i&&l.point<-10&&i.point-l.point>=(s-i.P)/2)return{text:"0",node:P("0"),number:0,re:0,im:0,exact:!1};if(!(l.point<-10&&r<3)||i&&i.point===l.point)return Nt(u,o,n,a.q);i={point:l.point,P:s},s+=10-l.point}throw new ee("could not approximate")}function Nt(e,n,t,s){const i=qt(xt(e,n,t));return{text:i,node:St(i),number:Number(i),re:Number(i),im:0,exact:Boolean(s)&&$t(s)&&kt(s)<=t}}function Ot([e,n],t,s){const i=10n**BigInt(Math.max(0,t.P-s-12)),r=e=>ut(e)>i;if(!r(n))return{real:e};const o=xt(n,t,s);if(o.point<-10&&r(n))return{retry:10-o.point};const a=qt(o),u="1"===a?"i":"-1"===a?"-i":`${a}i`,l="1"===a?D("i"):V("*",[St(a.replace(/^-/,"")),D("i")]);if(!r(e))return{text:u,node:a.startsWith("-")?V("neg",[l]):l,number:NaN,re:0,im:Number(a),exact:!1};const c=qt(xt(e,t,s)),f=a.startsWith("-"),p="1"===a.replace(/^-/,"")?D("i"):V("*",[St(a.replace(/^-/,"")),D("i")]);return{text:`${c} ${f?"-":"+"} ${u.replace(/^-/,"")}`,node:V(f?"-":"+",[St(c),p]),number:NaN,re:Number(c),im:Number(a),exact:!1}}function At(e,n={}){const t=e=>(e=>0===sn(e).size)(e)?"num"===e.type&&/^-?\d+$/.test(e.token)?e:Mt(e,n).node:W(e)?V(e.op,e.args.map(t)):e;return t(e)}const It={variable:null},Et=(e,n)=>null!==n&&sn(e).has(n);function Tt(e){if("num"===e.type)return oe(e.token);if(W(e)&&"/"===e.op&&e.args.every(e=>"num"===e.type)){const n=oe(e.args[0].token),t=oe(e.args[1].token);return n&&t&&!t.isZero?n.div(t):null}return null}const jt=e=>0===sn(e).size;function Zt(e,n,t){const s=function(e){const n=Je(e);return"num"===n.k?n.q.isZero?n.q:null:"atom"===n.k&&"sym"===n.node.type&&"pi"===n.node.token?oe("1"):"mul"===n.k&&1===n.fs.length&&"atom"===n.fs[0].b.k&&"pi"===n.fs[0].b.node.token&&"num"===n.fs[0].e.k&&n.fs[0].e.q.isOne?n.c:null}(e);if(!s)return!1;const[i,r="1"]=String(n).split("/");return t(s.compare(oe(i).div(oe(r))))}function zt(e){if(!jt(e))return NaN;try{const{number:n}=Mt(e,{digits:30});return Math.sign(n)}catch{return NaN}}function Ft(){bn("hasVariable")||(gn("hasVariable",e=>Et(e,It.variable),"mentions the variable being solved for"),gn("freeOfVariable",e=>null!==It.variable&&!Et(e,It.variable),"does not mention the variable being solved for"),gn("isRational",e=>null!==Tt(e),"an exact number: 3, -2, 1/2"),gn("isWhole",e=>Tt(e)?.isInteger??!1,"a whole number (any size)"),gn("isEvenWhole",e=>{const n=Tt(e);return Boolean(n?.isInteger&&n.n%2n==0n)},"an even whole number"),gn("isOddWhole",e=>{const n=Tt(e);return Boolean(n?.isInteger&&n.n%2n!=0n)},"an odd whole number"),gn("isPositiveRational",e=>(Tt(e)?.sign??0)>0,"an exact number above 0"),gn("isNegativeRational",e=>(Tt(e)?.sign??0)<0,"an exact number below 0"),gn("isConstant",jt,"has no unknowns (numbers, π and e only)"),gn("notOne",e=>{const n=Tt(e);return!n||!n.isOne},"anything except the number 1"),gn("notMinusOne",e=>{const n=Tt(e);return!n||!n.equals(oe("-1"))},"anything except the number -1"),gn("hasMinusSign",e=>function(e){const n=Je(e);return"num"===n.k?n.q.sign<0:"mul"===n.k&&n.c.sign<0}(e),"written with a leading minus: -x, -2x, -π/6"),gn("piMultipleAtLeast",(e,n)=>Zt(e,n,e=>e>=0),"a multiple of π, at least k·π"),gn("piMultipleAbove",(e,n)=>Zt(e,n,e=>e>0),"a multiple of π, above k·π"),gn("piMultipleBelow",(e,n)=>Zt(e,n,e=>e<0),"a multiple of π, below k·π"),gn("piMultipleAtMost",(e,n)=>Zt(e,n,e=>e<=0),"a multiple of π, at most k·π"),gn("isPositiveConstant",e=>zt(e)>0,"no unknowns, and above 0 (e, π, √2, 3)"),gn("isNegativeConstant",e=>zt(e)<0,"no unknowns, and below 0"),gn("hasImaginaryPart",e=>{if(!fe.complex)return!1;const n=De(Je(e));return Boolean(n)&&!("num"===n.im.k&&n.im.q.isZero)},"complex mode: has a nonzero imaginary part (unknowns count as real)"),gn("isSymbolNode",e=>"sym"===e.type&&!ce.has(e.token),"a single unknown such as x"))}function Bt(e){const n=new Map;for(const t of e){const e=t.id??t.name;if(!e)throw new Error(`a rule needs an id (pattern ${t.pattern})`);n.set(String(e),{...n.get(String(e))??{},...t})}const t=[...n.values()].map(e=>{const n={...e};try{void 0!==n.pattern&&(n.pattern=function(e){const n=_(e),t=e=>"num"===e.type||("sym"===e.type?e.token.startsWith("="):e.args.every(t)),s=e=>"sym"===e.type?D(e.token.slice(1)):"num"===e.type?e:V(e.op,e.args.map(s)),i=e=>"sym"===e.type?D(`=${e.token}`):"num"===e.type?e:V(e.op,e.args.map(i)),r=e=>"op"!==e.type?e:t(e)?i(Ke(s(e))):V(e.op,e.args.map(r));return r(n).s}(String(n.pattern)))}catch(e){throw new Error(`rule "${n.id}": bad pattern "${n.pattern}": ${e.message}`)}return"hidden"===n.step&&(n.tags=[...n.tags??[],"hidden"]),n});return et.fromSpecs(t,{strict:!0})}function Ct(e,n,t,s){return e.explain?e.explain.replace(/\{(\w+)\}/g,(e,i)=>"result"===i?t?s(t):e:n[i]?s(n[i]):e).trim():""}const Dt=e=>W(e)&&("+"===e.op||"-"===e.op),Pt=e=>W(e)&&("*"===e.op||"/"===e.op);function*Rt(e,n,{order:t="pre"}={}){for(const s of function(e,n,{order:t="post"}={}){const s=[];for(const{node:i,path:r}of G(e,t))for(const e of it(i,n))s.push({...e,node:i,path:r});return s}(e,n,{order:t})){const n=rt(s.rule.outputTemplate,s.bound);yield{rule:s.rule,bound:s.bound,path:s.path,before:s.node,after:n,next:()=>Ke(X(e,s.path,n))}}for(const{node:s,path:i}of G(e,t)){const t=Dt(s);if(!t&&!Pt(s))continue;const r=t?rn(Je(s)):on(Je(s));if(r.length<3)continue;const o=t?Ie:Te;for(let t=0;t<r.length;t++)for(let s=t+1;s<r.length;s++){const a=en(o([r[t],r[s]]));for(const u of it(a,n)){const n=rt(u.rule.outputTemplate,u.bound),l=r.filter((e,n)=>n!==t&&n!==s);yield{rule:u.rule,bound:u.bound,path:i,before:a,after:n,next:()=>Ke(X(e,i,en(o([Je(n),...l]))))}}}}}function Ut(e,n,{format:t,order:s="pre",maxSteps:i=200,variable:r=null}={}){const o=It.variable;It.variable=r;try{let r=Ke(e);const o=new Set([r.s]),a=[];for(let e=0;e<i;e++){let e=null;for(const t of Rt(r,n,{order:s})){const n=t.next();if(n.s!==r.s&&!o.has(n.s)){e={c:t,next:n};break}}if(!e)break;const{c:i,next:u}=e;a.push({id:i.rule.id,name:i.rule.name,tags:i.rule.tags,from:r.s,to:u.s,path:i.path,before:i.before.s,after:i.after.s,explanation:Ct(i.rule,i.bound,Ke(i.after),t)}),r=u,o.add(r.s)}return{node:r,steps:a}}finally{It.variable=o}}const Vt={full:[],normal:["hidden"],brief:["hidden","tidy","identity","value","split","base","arithmetic"]},Lt=(e,n)=>"all"===n||"*"===n||Array.isArray(n)&&n.some(n=>n===e.id||e.tags?.includes(n));function Wt(e){if(!1===e)return null;if(void 0===e||!0===e)return{show:"all",hide:Vt.normal,explain:!0};if("string"==typeof e){if(!Vt[e])throw new Error(`steps: "${e}" is not one of ${Object.keys(Vt).join(", ")}`);return{show:"all",hide:Vt[e],explain:!0}}const n=e.detail??"normal";if(!Vt[n])throw new Error(`steps.detail: "${n}" is not one of ${Object.keys(Vt).join(", ")}`);return{show:e.show??"all",hide:[...Vt[n],...e.hide??[]],explain:e.explain??!0}}function _t(e,n){if(!n)return[];e=function(e){const n=[];for(const t of e){const e=n[n.length-1];if(!("d-variable"===t.id&&e&&/^(\S+) \1 der$/.test(t.before??"")&&` ${e.after??""} `.includes(` ${t.before} `))){n.push(t);continue}const s={...e,to:t.to};if(e.after&&(s.after=` ${e.after} `.replace(` ${t.before} `," 1 ").replace(/ 1 \*(?= )/g,"").trim()),e.explanation){const n=t.before.split(" ")[0];s.explanation=e.explanation.endsWith(`the derivative of ${n}.`)?`${e.explanation.slice(0,-1)}, which is 1.`:`${e.explanation} The derivative of ${n} is 1.`}n[n.length-1]=s}return n}(e);const t=[];let s=null;for(const i of e){if(!(Lt(i,n.show)&&!Lt(i,n.hide))){s=s??{from:i.from,ids:[]},s.ids.push(i.id);continue}const e={...i};s&&(e.from=s.from,e.also=s.ids,e.path=null,s=null);!0===n.explain||!1!==n.explain&&Lt(i,n.explain)||delete e.explanation,t.push(e)}if(s&&t.length){const n=t[t.length-1];n.to=e[e.length-1].to,n.also=[...n.also??[],...s.ids]}return t}const Ht=me(re.ONE),Qt=(e,n)=>"atom"===e.k&&"sym"===e.node.type&&e.node.token===n;function Jt(e){switch(e.k){case"num":default:return e;case"atom":return"op"===e.node.type?He(e.node.op,e.node.args.map(e=>Jt(Je(e)))):e;case"add":return Ie(rn(e).map(Jt));case"mul":{let n=[me(e.c)];for(const t of e.fs){const e=Jt(t.b);if("add"===e.k&&we(t.e)&&t.e.q.isInteger&&t.e.q.sign>0&&t.e.q.n<=BigInt(60))for(let s=0n;s<t.e.q.n;s++)n=Kt(n,rn(e));else n=Kt(n,[Ze(e,t.e)])}return Ie(n)}}}function Kt(e,n){const t=[];for(const s of e)for(const e of n)t.push(Te([s,e]));return rn(Ie(t))}function Yt(e,n){const t=new Map;for(const s of rn(Jt(e))){const{coef:e,rest:i}=Ae(s);let r=0;const o=[me(e)];for(const e of i?on(i):[]){const{b:t,e:s}="mul"===e.k&&1===e.fs.length&&e.c.isOne?e.fs[0]:{b:e,e:Ht};if(Qt(t,n)){if(!we(s)||!s.q.isInteger||s.q.sign<0)return null;r+=Number(s.q.n)}else{if(Gt(t,n)||Gt(s,n))return null;o.push(e)}}t.set(r,Ie([t.get(r)??me(re.ZERO),Te(o)]))}for(const[e,n]of t)we(n)&&n.q.isZero&&t.delete(e);return t}const Gt=(e,n)=>sn(en(e)).has(n);function Xt(e){if(!e)return null;const n=Math.max(0,...e.keys());if(n>256)return null;const t=[];for(let s=0;s<=n;s++){const n=e.get(s)??me(re.ZERO);if(!we(n))return null;t.push(n.q)}return t}function es(e,n){const t=Je(D(n));return Ie(e.map((e,n)=>Te([me(e),je(t,me(re.of(n)))])))}const ns=e=>{const n=e.slice();for(;n.length>1&&n[n.length-1].isZero;)n.pop();return n},ts=(e,n)=>e.reduceRight((e,t)=>e.mul(n).add(t),re.ZERO);function ss(e,n){const t=e.length-1,s=new Array(t);let i=re.ZERO;for(let r=t;r>=1;r--)i=e[r].add(i.mul(n)),s[r-1]=i;return s}function is(e){if(0n===(e=(e=>e<0n?-e:e)(e)))return null;if(e>10n**14n)return null;const n=[];let t=e;for(let e=2n;e*e<=t;e+=2n===e?1n:2n){if(t%e)continue;let s=0;for(;t%e===0n;)t/=e,s++;n.push([e,s])}t>1n&&n.push([t,1]);let s=[1n];for(const[e,t]of n){const n=[];for(const i of s)for(let s=0,r=1n;s<=t;s++,r*=e)n.push(i*r);if(s=n,s.length>2e4)return null}return s.sort((e,n)=>e<n?-1:e>n?1:0)}function rs(e){let n=ns(e);const t=[];for(;n.length>1&&n[0].isZero;)t.push(re.ZERO),n=n.slice(1);if(n.length<=1)return{roots:t,rest:n};const s=n.reduce((e,n)=>e*n.d/ie(e,n.d),1n),i=n.map(e=>e.n*s/e.d),r=is(i[0]),o=is(i[i.length-1]);if(!r||!o)return{roots:t,rest:n};const a=new Map;for(const e of r)for(const n of o)for(const t of[1n,-1n]){const s=new re(t*e,n);a.set(s.toString(),s)}const u=[...a.values()].sort((e,n)=>e.compare(n));for(const e of u)for(;n.length>1&&ts(n,e).isZero;)t.push(e),n=ss(n,e);return{roots:t.sort((e,n)=>e.compare(n)),rest:n}}function os(e,n){const t=ns(n);let s=ns(e);const i=t[t.length-1];if(i.isZero)throw new ee("division by the zero polynomial");const r=new Array(Math.max(1,s.length-t.length+1)).fill(re.ZERO);for(;s.length>=t.length&&(1!==s.length||!s[0].isZero);){const e=s.length-t.length,n=s[s.length-1].div(i);if(r[e]=n,s=ns(s.map((s,i)=>i>=e&&i-e<t.length?s.sub(n.mul(t[i-e])):s)),s.length-1<e+t.length-1&&s[s.length-1].isZero)break;if(s.length<t.length)break}return{q:ns(r),r:s}}function as(e){if("num"===e.k)return{coef:e.q,factors:[],notes:[]};if("atom"===e.k)return{coef:re.ONE,factors:[{base:e,exp:Ht}],notes:[]};if("mul"===e.k){let n=e.c;const t=[],s=[];for(const i of e.fs)if("add"===i.b.k&&we(i.e)&&i.e.q.isInteger){const e=as(i.b);n=n.mul(e.coef.pow(i.e.q.n));for(const n of e.factors)t.push({base:n.base,exp:Te([n.exp,i.e])});s.push(...e.notes)}else t.push({base:i.b,exp:i.e});return us(n,t,s)}return function(e){const n=rn(e),t=[],s=n.map(e=>{const{coef:n,rest:t}=Ae(e);return{coef:n,fs:t?on(t).map(cs):[]}}),i=s.reduce((e,n)=>({n:ie(e.n,n.coef.n),d:e.d*n.coef.d/ie(e.d,n.coef.d)}),{n:0n,d:1n});let r=new re(i.n||1n,i.d);ls(e)<0&&(r=r.neg());const o=[];for(const e of s[0].fs){if(!we(e.e)||e.e.q.sign<=0)continue;let n=e.e.q;const t=qe(e.b);let i=!0;for(const e of s.slice(1)){const s=e.fs.find(e=>qe(e.b)===t&&we(e.e)&&e.e.q.sign>0);if(!s){i=!1;break}s.e.q.compare(n)<0&&(n=s.e.q)}i&&o.push({base:e.b,exp:me(n)})}let a=e;if(!r.isOne||o.length){const e=Te([me(r),...o.map(e=>Ze(e.base,e.exp))]);a=Ie(n.map(n=>Te([n,je(e,me(re.MINUS_ONE))]))),t.push({id:"factor.common",values:{common:e}})}const u="add"===a.k?function(e,n){const t=[...fs(e)];for(const s of t){const i=Xt(Yt(e,s));if(!i||i.length<3)continue;if(1!==t.length)break;const{roots:r,rest:o}=rs(i);if(!r.length)break;const a=[];let u=o[o.length-1]??re.ONE;const l=o.map(e=>e.div(u)),c=[...r].sort((e,n)=>e.abs().compare(n.abs())||n.sign-e.sign);for(const e of c){const t=es([new re(-e.n),new re(e.d)],s);a.push({base:t,exp:Ht}),u=u.div(new re(e.d)),n.push({id:"factor.root",values:{root:me(e),factor:t}})}if(l.length>1){const e=l.reduce((e,n)=>e*n.d/ie(e,n.d),1n),n=l.map(n=>n.mul(new re(e))),t=n.reduce((e,n)=>ie(e,n.n),0n)||1n;u=u.mul(new re(t,e)),a.push({base:es(n.map(e=>e.div(new re(t))),s),exp:Ht})}return us(u,a,[])}const s=rn(e);if(2===s.length){const[e,t]=s;for(const s of[2,3]){const i=ps(e,s),r=ps(Ve(t),s),o=3===s?ps(t,s):null;if(i&&r&&2===s){n.push({id:"factor.squares",values:{a:i,b:r}});const e=as(Ie([i,Ve(r)])),t=as(Ie([i,r]));return us(e.coef.mul(t.coef),[...e.factors,...t.factors],[...e.notes,...t.notes])}if(3===s&&i&&(r||o)){const e=r??o,t=r?-1:1;n.push({id:t<0?"factor.cubes-difference":"factor.cubes-sum",values:{a:i,b:e}});const s=Ie(t<0?[i,Ve(e)]:[i,e]),a=Ie([je(i,me(re.of(2))),t<0?Te([i,e]):Ve(Te([i,e])),je(e,me(re.of(2)))]),u=as(s);return us(u.coef,[...u.factors,{base:a,exp:Ht}],u.notes)}}}return{coef:re.ONE,factors:[{base:e,exp:Ht}],notes:[]}}(a,t):as(a);return us(r.mul(u.coef),[...o,...u.factors],[...t,...u.notes.filter(e=>!t.includes(e))])}(e)}function us(e,n,t){const s=new Map;for(const e of n){const n=qe(e.base),t=s.get(n);t?t.exp=Ie([t.exp,e.exp]):s.set(n,{...e})}return{coef:e,factors:[...s.values()].filter(e=>!(we(e.exp)&&e.exp.q.isZero)),notes:t}}const ls=e=>Ae(rn(e)[0]).coef.sign;const cs=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length?{b:e.fs[0].b,e:e.fs[0].e}:{b:e,e:Ht},fs=e=>sn(en(e));function ps(e,n){const{coef:t,rest:s}=Ae(e);if(t.sign<0)return null;const i=function(e,n){const t=e=>{if(e<0n)return null;let t=0n,s=1n;for(;s**BigInt(n)<=e;)s*=2n;for(;t<s-1n;){const i=(t+s)/2n;i**BigInt(n)<=e?t=i:s=i}return t**BigInt(n)===e?t:null},s=t(e.n),i=t(e.d);return null!==s&&null!==i?new re(s,i):null}(t,n);if(!i)return null;const r=[me(i)];for(const e of s?on(s).map(cs):[]){if(!we(e.e))return null;const t=e.e.q.div(re.of(n));if(!t.isInteger)return null;r.push(Ze(e.b,me(t)))}return Te(r)}function hs({coef:e,factors:n}){const t=[],s=[];for(const e of n){const n=we(e.exp)&&e.exp.q.sign<0,i=n?me(e.exp.q.neg()):e.exp,r=en(Ze(e.base,i));(n?s:t).push(r)}const i=e=>e.reduce((e,n)=>e?V("*",[e,n]):n,null),r=e.n<0n?-e.n:e.n;let o=t.length?i(1n===r?t:[en(me(new re(r))),...t]):en(me(new re(r)));return e.n<0n&&(o=V("neg",[o])),1n!==e.d&&s.unshift(en(me(new re(e.d)))),s.length?V("/",[o,i(s)]):o}function ds(e){if("mul"!==e.k)return{num:e,den:Ht};const n=[me(new re(e.c.n))],t=[me(new re(e.c.d))];for(const s of e.fs)we(s.e)&&s.e.q.sign<0?t.push(Ze(s.b,me(s.e.q.neg()))):n.push(Ze(s.b,s.e));return{num:Te(n),den:Te(t)}}function ms(e){if("add"!==e.k)return ds(e);const n=rn(e).map(ds),t=new Map;let s=1n;for(const e of n){const{coef:n,rest:i}=Ae(e.den);s=s*n.n/ie(s,n.n);for(const e of i?on(i).map(cs):[]){const n=qe(e.b),s=t.get(n);(!s||we(e.e)&&we(s.e)&&e.e.q.compare(s.e.q)>0)&&t.set(n,e)}}const i=Te([me(new re(s)),...[...t.values()].map(e=>Ze(e.b,e.e))]);if(we(i)&&i.q.isOne)return{num:e,den:Ht};return{num:Jt(Ie(n.map(e=>Te([e.num,i,je(e.den,me(re.MINUS_ONE))])))),den:i}}function gs(e){const{num:n,den:t}=ms(e);if(we(t)&&t.q.isOne)return null;const s=as(n),i=as(t),r=new Set(s.factors.map(e=>qe(e.base))),o=i.factors.filter(e=>r.has(qe(e.base))),a=[...s.factors,...i.factors.map(e=>({base:e.base,exp:Ve(e.exp)}))];return{...us(s.coef.div(i.coef),a,[...s.notes,...i.notes]),canceled:o.map(e=>e.base)}}const vs=(e,n)=>V("=",[e,n]),bs=Ke(V("+",[D("x"),V("neg",[D("x")])])),ws=e=>W(e)&&"="===e.op;function ys(e,n,t,s={}){const i=[],r=(n,t,s,r,o,a={})=>i.push(e.step(n,t,s,r,o,a));r.raw=e=>i.push(e);const o=ws(n)?n:vs(n,bs),a=vs(Ke(o.args[0]),Ke(o.args[1]));a.s!==o.s&&r("normal","Work out each side",["tidy","arithmetic"],o,a);const u=[],l=[],c=new Set;u.numeric=c,Ms(e,a,t,s,r,u,l,0);const f=[],p=new Set;for(const n of u.map(n=>c.has(n)?n:(n=>Ut(n,e.set.view("simplify"),{format:e.format}).node)(n))){const e=n.s;if(p.has(e))continue;p.add(e);const s=c.has(n)?null:ks(o,t,n);s?r("solve.reject","Check the answer",["check"],vs(D(t),n),vs(D(t),n),{value:n,reason:s}):f.push(n)}return f.sort(xs),{solutions:f,unsolved:l,steps:i,always:l.some(e=>e.always)}}function xs(e,n){const t=qs(e),s=qs(n);return null===t||null===s?e.s<n.s?-1:1:(Math.abs(t.im)>0)-(Math.abs(s.im)>0)||t.re-s.re||t.im-s.im}function qs(e){if(sn(e).size)return null;try{const{re:n,im:t}=Mt(e,{digits:20});return{re:n,im:t}}catch{return null}}function ks(e,n,t){const[s,i]=e.args,r=new Set([...sn(s),...sn(i),...sn(t)]);if(r.delete(n),r.size)return null;const o=e=>$s(e,n,t);try{const e=Mt(o(s),{digits:40}),n=Mt(o(i),{digits:40}),t=Math.max(1,Math.hypot(e.re,e.im),Math.hypot(n.re,n.im));return Math.hypot(e.re-n.re,e.im-n.im)>1e-12*t?"it does not make the two sides equal":null}catch(e){return`the original equation has no value there (${e.message})`}}function $s(e,n,t){return"sym"===e.type?e.token===n?t:e:W(e)?V(e.op,e.args.map(e=>$s(e,n,t))):e}const Ss=24;function Ms(e,n,t,s,i,r,o,a){if(a>Ss)return js(e,n,t,s,i,r,o);const u=function(e){const n=[],t=e=>{if(W(e)&&"|"===e.op)return void e.args.forEach(t);if(!ws(e))return void n.push(e);const s=e.args[1],i=G(s,"pre").find(({node:e})=>W(e)&&"pm"===e.op);if(!i)return void n.push(e);const r=i.node.args[0],o=Ke(X(s,i.path,r)),a=Ke(X(s,i.path,V("neg",[r])));t(vs(e.args[0],o)),a.s!==o.s&&t(vs(e.args[0],a))};return t(e),n}(n);if(u.length>1){i("solve.split","Two cases",["split"],n,u.reduce((e,n)=>e?V("|",[e,n]):n,null));for(const n of u)Ms(e,n,t,s,i,r,o,a+1);return}if(1===u.length&&u[0].s!==n.s)return Ms(e,u[0],t,s,i,r,o,a+1);const[l,c]=n.args;if("sym"===l.type&&l.token===t&&!Gt(Je(c),t))return void r.push(c);const f=Ie([Je(l),Ve(Je(c))]);if(!Gt(f,t))return we(f)&&f.q.isZero?(i("solve.always","Always true",["check"],n,n,{v:t}),void o.push(Object.assign(Object.create(n),{always:!0}))):void i("solve.never","No solution",["check"],n,n,{v:t});const p=rn(f).filter(e=>Gt(e,t)),h=rn(f).filter(e=>!Gt(e,t)),d=Ie(p),m=Ve(Ie(h));if(fe.complex){const u=Yt(f,t);if(u&&[...u.values()].every(e=>!Gt(e,t))&&Math.max(...u.keys())>=2){const l=vs(en(f),bs);return l.s!==n.s&&i("solve.one-side","Everything on one side",["move"],n,l,{v:t}),Es(e,f,u,t,s,i,r,o,a,l)}}if(1===p.length)return Ns(e,n,d,m,t,s,i,r,o,a);const g=vs(en(f),bs),v=Yt(f,t);if(v&&[...v.values()].every(e=>!Gt(e,t))&&Math.max(...v.keys())>=2)return g.s!==n.s&&i("solve.one-side","Everything on one side",["move"],n,g,{v:t}),Es(e,f,v,t,s,i,r,o,a,g);const b=as(f),w=b.factors.filter(e=>Gt(e.base,t)&&!(we(e.exp)&&e.exp.q.sign<0));if(w.length>=2||1===w.length&&b.factors.length>1){const u=vs(hs(b),bs);g.s!==n.s&&i("solve.one-side","Everything on one side",["move"],n,g,{v:t}),u.s!==g.s&&i("solve.factor","Factor",["factor"],g,u,{});const l=w.map(e=>vs(en(e.base),bs));l.length>1&&i("solve.zero-product","A product is zero when a factor is",["split"],u,l.reduce((e,n)=>e?V("|",[e,n]):n,null),{});for(const n of l)Ms(e,n,t,s,i,r,o,a+1);return}const y=ms(f);if(Gt(y.den,t)){const u=vs(en(y.num),bs);return i("solve.clear-denominator","Clear the denominator",["move"],n,u,{den:en(y.den)}),Ms(e,u,t,s,i,r,o,a+1)}const x=p.filter(e=>!Is(e,t));if(1===x.length&&/\b(sqrt|root|abs)\b/.test(en(x[0]).s))return Ns(e,n,x[0],Ve(Ie(rn(f).filter(e=>e!==x[0]))),t,s,i,r,o,a);const q=function(e,n){const t=en(e),s=new Map;for(const{node:e}of G(t,"pre"))if(W(e)&&sn(e).has(n))if("^"!==e.op||sn(e.args[0]).has(n))["sin","cos","tan","ln","sqrt","abs"].includes(e.op)&&e.args[0].s===n&&s.set(e.s,e);else{const t=Je(e.args[1]),{coef:i,rest:r}=Ae(t);if(r&&i.isInteger&&en(r).s===n){const t=en(je(Je(e.args[0]),Je(D(n))));s.set(t.s,t)}}const i="u"===n?"w":"u";for(const e of s.values()){const s=Ts(t,e,n,i);if(!s||sn(s).has(n))continue;const r=Je(s),o=Yt(r,i);if(o&&Math.max(...o.keys())>=1)return{kernel:Je(e),poly:r,symbol:i}}return null}(f,t);if(q){const n=q.symbol;i("solve.substitute","Substitute",["substitute"],g,vs(en(q.poly),bs),{u:D(n),kernel:en(q.kernel)});const u=[];Ms(e,vs(en(q.poly),bs),n,s,i,u,o,a+1);for(const n of u)Ms(e,vs(en(q.kernel),n),t,s,i,r,o,a+1);return}return js(e,g,t,s,i,r,o)}function Ns(e,n,t,s,i,r,o,a,u,l){let c=vs(en(t),en(s));c.s!==n.s&&o("solve.move","Move the terms",["move"],n,c,{v:i});const{coef:f,rest:p}=Ae(t),h=p?on(p):[],d=Te([me(f),...h.filter(e=>!Gt(e,i))]);if(!we(d)||!d.q.isOne){const e=Te(h.filter(e=>Gt(e,i))),n=vs(en(e),en(Le(s,d))),t=we(d)&&!d.q.isInteger&&(1n===d.q.n||-1n===d.q.n);o(t?"solve.multiply":"solve.divide",t?"Multiply both sides":"Divide both sides",["move"],c,n,{by:en(t?me(d.q.inv()):d),v:i}),c=n}if("sym"===c.args[0].type&&c.args[0].token===i)return void a.push(c.args[1]);const m=Je(c.args[1]);if(we(m)&&m.q.isZero){const n=Je(c.args[0]),t=on(n).filter(e=>Gt(e,i)&&!Os(e));if(!t.length&&on(n).some(e=>Gt(e,i)))return void o("solve.never","No solution",["check"],c,c,{});if(t.length>1||t.length<on(n).filter(e=>Gt(e,i)).length){const n=t.map(e=>vs(en(As(e)),bs));o("solve.zero-product","A product is zero when a factor is",["split"],c,n.reduce((e,n)=>e?V("|",[e,n]):n,null),{});for(const t of n)Ms(e,t,i,r,o,a,u,l+1);return}}const g=Ut(c,e.set.view("isolate"),{format:e.format,maxSteps:1,variable:i});return g.steps.length?(function(e,n){for(const t of n)e.raw(t)}(o,g.steps),Ms(e,g.node,i,r,o,a,u,l+1)):js(e,c,i,r,o,a,u)}const Os=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&we(e.fs[0].e)&&e.fs[0].e.q.sign<0,As=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&we(e.fs[0].e)&&e.fs[0].e.q.sign>0?e.fs[0].b:e,Is=(e,n)=>{const t=Yt(e,n);return Boolean(t)&&[...t.values()].every(e=>!Gt(e,n))};function Es(e,n,t,s,i,r,o,a,u,l){const c=Math.max(...t.keys()),f=Xt(t);if(fe.complex&&c>=3&&c<=64&&f&&f.every((e,n)=>0===n||n===c||e.isZero)&&!f[0].isZero){const n=f[0].neg().div(f[c]),t=je(me(n.abs()),me(new re(1n,BigInt(c)))),i=[];for(let s=0;s<c;s++){const r=Te([me(new re(BigInt((n.sign<0?1:0)+2*s),BigInt(c))),Je(D("pi"))]),o=V("*",[en(t),V("+",[V("cos",[en(r)]),V("*",[D("i"),V("sin",[en(r)])])])]);i.push(Ut(o,e.set.view("simplify"),{format:e.format}).node)}return r("solve.roots","All n roots",["complex"],l,i.map(e=>vs(D(s),e)).reduce((e,n)=>e?V("|",[e,n]):n),{v:s,n:String(c),last:String(c-1),r:en(me(n))}),void o.push(...i)}if(f){const{roots:t}=rs(f);if(t.length){const t=as(n),c=vs(hs(t),bs);if(t.factors.length>1||t.factors.some(e=>!(we(e.exp)&&e.exp.q.isOne))){r("solve.factor","Factor",["factor"],l,c,{});const n=t.factors.filter(e=>Gt(e.base,s)).map(e=>vs(en(e.base),bs));n.length>1&&r("solve.zero-product","A product is zero when a factor is",["split"],c,n.reduce((e,n)=>e?V("|",[e,n]):n,null),{});for(const t of n)Ms(e,t,s,i,r,o,a,u+1);return}}}if(2===c){const e=t.get(2),n=t.get(1)??me(re.ZERO),i=t.get(0)??me(re.ZERO),a=Ie([je(n,me(re.of(2))),Te([me(re.of(-4)),e,i])]);if(we(a)&&a.q.sign<0&&!fe.complex)return void r("solve.no-real","No real solutions",["quadratic"],l,l,{D:en(a)});const u=Te([me(re.of(2)),e]),c=je(a,me(re.HALF)),f=en(Le(Ie([Ve(n),c]),u)),p=en(Le(Ie([Ve(n),Ve(c)]),u)),h=f.s===p.s?vs(D(s),f):V("|",[vs(D(s),f),vs(D(s),p)]);return r(fe.complex&&we(a)&&a.q.sign<0?"solve.quadratic-complex":"solve.quadratic","The quadratic formula",["quadratic"],l,h,{a:en(e),b:en(n),c:en(i),D:en(a),root:en(c),v:s}),o.push(f),void(p.s!==f.s&&o.push(p))}return js(e,l,s,i,r,o,a)}function Ts(e,n,t,s){if(e.s===n.s)return D(s);if(!W(e))return e;if("^"===e.op&&"^"===n.op&&e.args[0].s===n.args[0].s){const n=Je(e.args[1]),{coef:i,rest:r}=Ae(n);if(r&&en(r).s===t&&i.isInteger)return V("^",[D(s),en(me(i))])}return V(e.op,e.args.map(e=>Ts(e,n,t,s)))}function js(e,n,t,s,i,r,o){if(s.approximate){const e="number"==typeof s.approximate?s.approximate:15,o=Je(V("-",[n.args[0],n.args[1]])),a=fe.complex?Xt(Yt(o,t)):null,u=a&&a.length>2?function(e,n){const t=e.length-1,s=e[t],i=e.map(e=>e/s),r=(e,n)=>{let s=1,r=0;for(let o=t-1;o>=0;o--)[s,r]=[s*e-r*n+i[o],s*n+r*e];return[s,r]};let o=Array.from({length:t},(e,n)=>[1.3*Math.cos(2*Math.PI*n/t+.4),1.3*Math.sin(2*Math.PI*n/t+.4)]);for(let e=0;e<500;e++){let e=0;if(o=o.map(([n,s],i)=>{let[a,u]=r(n,s);for(let e=0;e<t;e++){if(e===i)continue;const t=n-o[e][0],r=s-o[e][1],l=t*t+r*r;[a,u]=[(a*t+u*r)/l,(u*t-a*r)/l]}return e=Math.max(e,Math.hypot(a,u)),[n-a,s-u]}),e<1e-15)break}const a=e=>Math.abs(e)<1e-12?0:Number(e.toPrecision(n));return o.map(([e,n])=>[a(e),a(n)]).sort((e,n)=>(0!==e[1])-(0!==n[1])||e[0]-n[0]||e[1]-n[1]).map(([e,n])=>{const t=Zs(e);if(0===n)return t;const s=V("*",[Zs(Math.abs(n)),D("i")]);return 0===e?n<0?V("neg",[s]):s:V(n<0?"-":"+",[t,s])})}(a.map(e=>e.toNumber()),Math.min(e,14)):function(e,n,t){const s=Je(V("-",[e.args[0],e.args[1]])),i=en(s),r=e=>{try{return Mt($s(i,n,zs(e)),{digits:30}).number}catch{return NaN}},o=[],a=[];for(let e=-400;e<=400;e++)a.push(Math.sign(e)*(Math.abs(e)/20)**2);for(let e=0;e+1<a.length;e++){let n=a[e],s=a[e+1],i=r(n);const u=r(s);if(Number.isNaN(i)||Number.isNaN(u))continue;if(0===i){o.push(zs(n));continue}if(i*u>0)continue;for(let e=0;e<200&&s-n>1e-16*Math.abs(n);e++){const e=(n+s)/2,t=r(e);if(Number.isNaN(t))break;i*t<=0?s=e:(n=e,i=t)}const l=(n+s)/2;Math.abs(r(l))<1e-6&&o.push(zs(Number(l.toPrecision(Math.min(t,15)))))}return o}(n,t,e);for(const e of u)r.numeric?.add(e);return i("solve.numeric","Numeric solutions",["numeric"],n,u.length?u.map(e=>vs(D(t),e)).reduce((e,n)=>e?V("|",[e,n]):n):n,{v:t,count:String(u.length)}),void r.push(...u)}i("solve.unsolved","No exact method",["unsolved"],n,n,{v:t}),o.push(n)}const Zs=e=>P(String(e).includes("e")?e.toFixed(20):String(e)),zs=e=>P(Number.isInteger(e)?String(e):e.toFixed(17));const Fs=()=>P("1"),Bs={"<":e=>e<0,">":e=>e>0,"≤":e=>e<=0,"≥":e=>e>=0},Cs=new Set(["sin","cos","tan","csc","sec","cot"]);function Ds(e,n,t){const s=[],i=[],r=[];let o=n;for(;W(o.args[0])&&Bs[o.args[0].op];)r.unshift({op:o.op,right:o.args[1]}),o=o.args[0];const a=[o.args[0],o.args[1],...r.map(e=>e.right)];[o.op,...r.map(e=>e.op)].forEach((e,n)=>i.push({h:Ke(V("-",[a[n],a[n+1]])),op:e}));const u=new Set(i.flatMap(e=>[...sn(e.h)]));if(u.delete(t),u.size)throw new ee(`an inequality in ${t} with other unknowns (${[...u].join(", ")}) can't be charted`);if(i.some(e=>G(e.h,"pre").some(({node:e})=>W(e)&&Cs.has(e.op)&&sn(e).has(t))))return{pieces:null,steps:s,unsolved:!0};const l=[];for(const{h:e}of i){l.push(e);for(const{node:n}of G(e,"pre"))W(n)&&sn(n).has(t)&&("/"===n.op&&l.push(n.args[1]),"sqrt"!==n.op&&"ln"!==n.op||l.push(n.args[0]),"root"===n.op&&l.push(n.args[1]),"log"===n.op&&l.push(n.args[1],n.args[0],V("-",[n.args[0],Fs()])),["arcsin","arccos","arctanh","arcsec","arccsc"].includes(n.op)&&l.push(V("-",[n.args[0],Fs()]),V("+",[n.args[0],Fs()])),"arccosh"===n.op&&l.push(V("-",[n.args[0],Fs()])),"^"===n.op&&we(Je(n.args[1]))&&Je(n.args[1]).q.sign<0&&l.push(n.args[0]),"^"===n.op&&we(Je(n.args[1]))&&!Je(n.args[1]).q.isInteger&&l.push(n.args[0]))}const c=new Map;for(const n of l){const i=ys(e,vs(n,bs),t,{});if(i.unsolved.length&&!i.always)return{pieces:null,steps:s,unsolved:!0};if(!i.always)for(const e of i.solutions){const n=qs(e);!n||Math.abs(n.im)>1e-12||c.set(e.s,{node:e,x:n.re})}}const f=[...c.values()].sort((e,n)=>e.x-n.x).filter((e,n,t)=>0===n||Math.abs(e.x-t[n-1].x)>1e-12),p=f.map(e=>e.x),h=[];if(p.length){h.push(p[0]-Math.max(1,Math.abs(p[0])));for(let e=0;e+1<p.length;e++)h.push((p[e]+p[e+1])/2);h.push(p[p.length-1]+Math.max(1,Math.abs(p[p.length-1])))}else h.push(0);const d=h.map(e=>i.every(({h:n,op:s})=>{try{const i=Mt($s(n,t,P(function(e){return Math.abs(e)>=1e21?BigInt(Math.round(e)).toString():e.toFixed(Math.min(100,Math.max(0,17-Math.floor(Math.log10(Math.abs(e)||1)))))}(e))),{digits:20});return!(!Number.isFinite(i.re)||Math.abs(i.im)>1e-12)&&Bs[s](Math.abs(i.re)<1e-30?0:i.re)}catch{return!1}})),m=f.map(e=>i.every(({h:n,op:s})=>{try{const i=Mt(Ke($s(n,t,e.node)),{digits:30});return!(!Number.isFinite(i.re)||Math.abs(i.im)>1e-12)&&Bs[s](Math.abs(i.re)<1e-15?0:i.re)}catch{return!1}})),g=[];let v=null;const b=(e,n)=>{g.push({...v,hi:e,hiClosed:n}),v=null};for(let e=0;e<=f.length;e++){const n=0===e?null:f[e-1].node;if(d[e]?v??={lo:n,loClosed:!1}:v&&b(n,e>0&&m[e-1]),e===f.length)break;const t=f[e];if(m[e]){if(v)continue;d[e+1]?v={lo:t.node,loClosed:!0}:g.push({lo:t.node,hi:t.node,loClosed:!0,hiClosed:!0})}else v&&b(t.node,!1)}v&&b(null,!1);const w=f.length?f.map(n=>e.format(n.node)).join(", "):"none";return s.push(e.step("solve.sign-chart","A sign chart",["inequality"],n,n,{points:D(w),v:t})),{pieces:g,steps:s}}const Ps={tan:"cos",sec:"cos",csc:"sin",cot:"sin"};class Rs extends Error{}const Us=e=>({fin:e}),Vs={bnd:!0},Ls=e=>({inf:e}),Ws=D("∞");function _s(e){try{const n=Mt(e,{digits:15});return Math.abs(n.im??0)>1e-12?NaN:n.re??n.number}catch{return NaN}}function Hs(e){if(!fe.complex)return Number.isFinite(_s(e));try{const n=Mt(e,{digits:15});return Number.isFinite(n.re??n.number)&&Number.isFinite(n.im??0)}catch{return!1}}function Qs(e,n,t){if(!Number.isFinite(t))return!1;try{const s=Mt($s(e,n,P(Ks(t))),{digits:15});return Math.abs(s.im??0)>1e-12}catch(e){return/not real/.test(e.message)}}function Js(e,n,t){return Number.isFinite(t)?_s($s(e,n,P(Ks(t)))):NaN}function Ks(e){const n=Math.min(40,Math.max(0,16-Math.floor(Math.log10(Math.abs(e)||1))));return e.toFixed(n)}function Ys(e,n,t,s){const i=Gs(t,s).map(t=>Js(e,n,t)).filter(Number.isFinite);if(i.length<3)return NaN;const[r,o,a]=i.slice(-3),u=Math.max(1,Math.abs(a));return Math.abs(a-o)<1e-4*u&&Math.abs(o-r)<.01*u?a:NaN}function Gs(e,n){if(e.inf)return[100,1e3,1e4,1e5,1e6].map(n=>n*e.inf);const t=_s(e.fin);return[.001,1e-4,1e-5,1e-6,1e-7].map(e=>t+n*e*Math.max(1,Math.abs(t)))}function Xs(e,n,t,s,i=0){const r=[];if(!i&&!s.inf){const[e,i]=[Ys(n,t,s,-1),Ys(n,t,s,1)];if(Number.isFinite(e)&&Number.isFinite(i)&&Math.abs(e-i)>.001*Math.max(1,Math.abs(e),Math.abs(i)))throw new Rs(`from the left it goes to ${+e.toPrecision(6)}, from the right to ${+i.toPrecision(6)}`)}if(!s.inf&&!fe.complex)for(const e of i?[i]:[-1,1])if(Gs(s,e).every(e=>Qs(n,t,e)))throw new Rs(`it has no real values ${e<0?"to the left":"to the right"} of ${+_s(s.fin).toPrecision(6)}`);const o=new ei(e,t,s,i,r);let a;try{if(a=o.of(Ke(n),0),a.bnd)throw new Rs("it keeps swinging between bounds")}catch(e){if(e instanceof Rs){const e=(s.inf?[s.inf]:i?[i]:[-1,1]).map(e=>Ys(n,t,s,e));if(e.every(Number.isFinite)&&e.every(n=>Math.abs(n-e[0])<1e-6*Math.max(1,Math.abs(n))))throw new ee(`numbers near the point settle on ${+e[0].toPrecision(6)}: not answered`)}throw e}return function(e,n,t,s,i){const r=s?[s]:t.inf?[-1]:[-1,1];for(const s of r){const r=Gs(t,s).map(t=>Js(e,n,t)).filter(Number.isFinite);if(r.length<3)continue;const o=r[r.length-1];if(i.inf){if(Math.sign(o)!==i.inf||Math.abs(o)<Math.abs(r[0]))throw new ee(`numbers near the point don't go to ${i.inf>0?"∞":"-∞"}: not answered`)}else{const e=_s(i.fin);if(!Number.isFinite(e))continue;const n=r.map(n=>Math.abs(n-e)),t=Math.abs(r[r.length-1]-r[r.length-2]),s=n.every((e,t)=>0===t||e<n[t-1])&&n[n.length-1]<.5*n[0]&&n[n.length-1]<10*t;if(n[n.length-1]>.01*Math.max(1,Math.abs(e))&&!s)throw new ee(`numbers near the point go to ${o.toPrecision(6)}, not ${e.toPrecision(6)}: not answered`)}}}(n,t,s,i,a),{value:a,steps:r}}class ei{constructor(e,n,t,s,i){Object.assign(this,{cas:e,v:n,a:t,side:s,steps:i}),this.point=t.inf?t.inf>0?Ws:D("-∞"):t.fin}step(e,n,t,s,i={}){this.steps.push(this.cas.step(e,n,["limit"],t,s,{v:D(this.v),a:this.point,...i}))}of(e,n){if(n>8)throw new ee("this limit went too deep");const{v:t,a:s}=this;if(!sn(e).has(t))return Us(e);if("sym"===e.type)return s.inf?Ls(s.inf):Us(s.fin);if(s.inf){const i=Xt(Yt(Je(e),t));if(i&&i.length>1){const r=i.length-1,o=i[r].sign*(r%2&&s.inf<0?-1:1);return 0===n&&this.step("limit.leading","The leading term",e,Ke(V("*",[en(me(i[r])),V("^",[D(t),P(String(r))])])),{f:e,lead:Ke(V("*",[en(me(i[r])),V("^",[D(t),P(String(r))])]))}),Ls(o)}}if(!s.inf&&0===n){const n=$s(e,t,s.fin);let i=null;if(Hs(n)&&!this.pole(n)&&!ni(n))try{i=Ke(n)}catch{}if(i&&Hs(i)){const n=this.cas.simplify(i,{steps:!1}).result;return this.step("limit.substitute","Put the point in",e,n,{f:e}),Us(n)}}if(!W(e))return Us(e);switch(e.op){case"+":case"-":return this.sum(e,n);case"neg":return si(this.of(e.args[0],n+1));case"*":return this.product(e,n);case"/":return this.quotient(e,e.args[0],e.args[1],n);case"^":return this.power(e,n);default:return this.func(e,n)}}signOf(e){const n=Math.sign(_s(e));if(!n)throw new ee(`the sign of ${this.cas.format(e)} is not known`);return n}pole(e){return ti(e).some(e=>W(e)&&Ps[e.op]&&this.isExactZero(V(Ps[e.op],[e.args[0]])))}isExactZero(e){try{const n=this.cas.simplify(Ke(e),{steps:!1}).result;return L(n)&&0===Number(n.value)}catch{return!1}}sum(e,n){const[t,s]=e.args;let i,r;try{i=this.of(t,n+1),r=this.of(s,n+1)}catch(t){if(!(t instanceof Rs))throw t;const s=ms(Je(e)),i=Ke(V("/",[en(s.num),en(s.den)]));if(i.s===e.s)throw t;return this.step("limit.combine","One fraction",e,i,{f:e}),this.of(i,n+1)}const o="-"===e.op?si(r):r;if(i.bnd||o.bnd)return i.inf||o.inf?i.inf?i:o:Vs;if(i.fin&&o.fin)return Us(Ke(V("+",[i.fin,o.fin])));if(i.inf&&o.inf&&i.inf!==o.inf){const i="-"===e.op?s:V("neg",[s]);if([t,s].some(e=>W(e)&&"sqrt"===e.op)||W(s)&&"neg"===s.op&&W(s.args[0])&&"sqrt"===s.args[0].op){const s=Ke(V("/",[V("-",[V("^",[t,P("2")]),V("^",[i,P("2")])]),V("+",[t,i])]));return this.step("limit.conjugate","∞ − ∞: the conjugate",e,s,{f:e}),this.of(s,n+1)}const r=ms(Je(e)),o=Ke(V("/",[en(r.num),en(r.den)]));if(o.s===e.s)throw new ee("∞ − ∞ that does not become one fraction");return this.step("limit.combine","∞ − ∞: one fraction",e,o,{f:e}),this.of(o,n+1)}return i.inf?i:o}product(e,n){const[t,s]=e.args,i=this.of(t,n+1),r=this.of(s,n+1),o=e=>e.fin&&Math.abs(_s(e.fin))<1e-300;if(i.bnd||r.bnd){const n=i.bnd?r:i;if(o(n))return this.step("limit.squeeze","The squeeze theorem",e,P("0"),{f:e,bounded:i.bnd?t:s}),Us(P("0"));if(n.inf)throw new Rs("a growing factor times one that keeps swinging");return Vs}if(i.fin&&r.fin)return Us(Ke(V("*",[i.fin,r.fin])));if(o(i)&&r.inf||i.inf&&o(r)){const[r,a]=o(i)?[t,s]:[s,t],u=e=>e.s.split(" ").length,[l,c]=[Ke(V("/",[P("1"),r])),Ke(V("/",[P("1"),a]))],f=u(l)<=u(c)?V("/",[a,l]):V("/",[r,c]);return this.step("limit.zero-times-infinity","0·∞: a quotient",e,f,{f:e}),this.quotient(f,f.args[0],f.args[1],n+1)}const a=e=>e.inf?e.inf:this.signOf(e.fin);return Ls(a(i)*a(r))}quotient(e,n,t,s){const{v:i,a:r}=this;if(r.inf){const n=this.rational(e,s);if(n)return n}const o=this.of(n,s+1),a=this.of(t,s+1),u=e=>e.fin&&Math.abs(_s(e.fin))<1e-300;if(o.bnd&&a.inf)return this.step("limit.squeeze","The squeeze theorem",e,P("0"),{f:e,bounded:n}),Us(P("0"));if(o.bnd&&a.fin&&!u(a))return Vs;if(a.bnd)throw new ee("a quotient over something that keeps swinging is not worked out here");if(o.inf&&a.inf&&r.inf){const i=this.dividePower(e,n,t,s);if(i)return i}if(a.fin&&!u(a))return o.fin?Us(this.cas.simplify(Ke(V("/",[o.fin,a.fin])),{steps:!1}).result):Ls(o.inf*this.signOf(a.fin));if(a.inf&&o.fin)return Us(P("0"));if(u(a)&&!u(o))return this.blowUp(e);const l=u(o)?"0/0":"∞/∞",c=this.rational(e,s);if(c)return c;const f=Ke(this.cas.differentiate(n,i)),p=Ke(this.cas.differentiate(t,i)),h=Ke(V("/",[f,p]));return this.step("limit.lhopital","L'Hôpital's rule",e,h,{f:e,form:D(l)}),this.of(h,s+1)}dividePower(e,n,t,s){const{v:i,a:r}=this;if(!ti(e).some(e=>W(e)&&(["sqrt","root","sin","cos"].includes(e.op)||"^"===e.op&&!sn(e.args[1]).size&&!Number.isInteger(_s(e.args[1]))))||this.divided?.has(e.s))return null;const[o,a]=[1e4*r.inf,1e6*r.inf],u=Math.log(Math.abs(Js(t,i,a)/Js(t,i,o)))/Math.log(100),l=Math.round(2*u)/2;if(!Number.isFinite(u)||Math.abs(u-l)>.05||l<=0||r.inf<0&&!Number.isInteger(l))return null;const c=V("^",[D(i),P(String(l))]),f=e=>{if(W(e)&&("+"===e.op||"-"===e.op))return V(e.op,e.args.map(f));if(W(e)&&"neg"===e.op)return V("neg",[f(e.args[0])]);if(W(e)&&"sqrt"===e.op){const n=V("sqrt",[Ke(V("/",[e.args[0],V("^",[D(i),P(String(2*l))])]))]);return r.inf<0&&l%2?V("neg",[n]):n}return Ke(V("/",[e,c]))},p=V("/",[Ke(f(n)),Ke(f(t))]);return(this.divided??=new Set).add(e.s),this.step("limit.divide-power","Divide by the highest power",e,p,{f:e,power:c}),this.quotient(p,p.args[0],p.args[1],s+1)}rational(e,n){const{v:t,a:s}=this,{num:i,den:r}=ms(Je(e)),o=Xt(Yt(i,t)),a=Xt(Yt(r,t));if(!o||!a||a.length<2)return null;if(s.inf){const[n,i]=[o.length-1,a.length-1],r=Ke(V("/",[V("*",[en(me(o[n])),V("^",[D(t),P(String(n))])]),V("*",[en(me(a[i])),V("^",[D(t),P(String(i))])])]));if(r.s!==e.s&&this.step("limit.leading","The leading terms",e,r,{f:e,lead:r}),n<i)return Us(P("0"));if(n===i)return Us(en(me(o[n].div(a[i]))));const u=o[n].div(a[i]).sign*((n-i)%2&&s.inf<0?-1:1);return Ls(u)}const u=this.cas.cancel(e,{steps:!1}).result;if(u.s===e.s)return null;this.step("limit.cancel","Cancel the common factor",e,u,{f:e});const l=$s(u,t,s.fin);return Number.isFinite(_s(l))?Us(this.cas.simplify(Ke(l),{steps:!1}).result):this.blowUp(u)}blowUp(e){const{v:n,a:t,side:s}=this,i=(s?[s]:[-1,1]).map(s=>function(e,n,t,s){const i=Gs(t,s).map(t=>Js(e,n,t)).filter(Number.isFinite);if(!i.length)return 0;const r=Math.sign(i[i.length-1]);return i.slice(-3).every(e=>Math.sign(e)===r)?r:0}(e,n,t,s));if(i.includes(0))throw new ee("the sign near the point could not be told");if(2===i.length&&i[0]!==i[1])throw this.step("limit.one-sided","The two sides differ",e,e,{f:e,left:i[0]>0?Ws:D("-∞"),right:i[1]>0?Ws:D("-∞")}),new Rs(`from the left it goes to ${i[0]>0?"∞":"-∞"}, from the right to ${i[1]>0?"∞":"-∞"}`);return Ls(i[0])}power(e,n){const{v:t}=this,[s,i]=e.args,r=this.of(s,n+1);let o;const a=this.steps.length;try{o=this.of(i,n+1)}catch(t){if(!(t instanceof Rs)||!r.fin||Math.abs(_s(r.fin)-1)>1e-12)throw t;return this.steps.length=a,this.expLog(e,s,i,"1^∞",n)}if(r.bnd||o.bnd)throw new ee("a power of something that keeps swinging is not worked out here");const u=e=>e.fin?_s(e.fin):e.inf*(1/0),l=u(r),c=u(o);if(r.fin&&o.fin){if(Math.abs(l)<1e-300&&c<0)return this.blowUp(e);if(!(Math.abs(l)<1e-300&&Math.abs(c)<1e-300))return Us(this.cas.simplify(Ke(V("^",[r.fin,o.fin])),{steps:!1}).result)}const f=!sn(s).has(t),p=!sn(i).has(t),h=r.fin&&Math.abs(l)<1e-300,d=r.fin&&Math.abs(l-1)<1e-12;if(r.fin&&o.inf&&(!d||f)){if(d)return Us(P("1"));if(h){if(o.inf<0){if(f)throw new Rs("0 to a negative power has no value");return Ls(1)}return Us(P("0"))}if(l>1)return o.inf>0?Ls(1):Us(P("0"));if(l>0)return o.inf>0?Us(P("0")):Ls(1);throw new Rs("a negative number to a growing power swings between signs")}if(r.inf<0&&!p)throw new ee("a power of something going to -∞ is not worked out here");if(r.inf&&(p||o.fin&&Math.abs(c)>1e-300||o.inf)){if(c>0)return Ls(r.inf>0?1:p&&Number.isInteger(c)&&c%2?-1:1);if(c<0)return Us(P("0"))}if(p&&h&&c>0)return Us(P("0"));const m=d?"1^∞":h?"0^0":r.inf&&o.fin?"∞^0":null;if(!m)throw new ee("a power of this shape is not worked out here");return this.expLog(e,s,i,m,n)}expLog(e,n,t,s,i){const r=Ke(V("*",[t,V("ln",[n])]));this.step("limit.exp-log","Take logs",e,V("^",[D("e"),r]),{f:e,form:D(s)});const o=this.of(r,i+1);if(o.bnd)throw new ee("a power of something that keeps swinging is not worked out here");return o.inf?o.inf>0?Ls(1):Us(P("0")):Us(this.cas.simplify(Ke(V("^",[D("e"),o.fin])),{steps:!1}).result)}func(e,n){const t=e.op,s=e.args;if(1!==s.length){if("log"===t&&!sn(s[0]).has(this.v)){const e=this.of(s[1],n+1);if(e.fin){const n=Ke(V("log",[s[0],e.fin]));if(Number.isFinite(_s(n)))return Us(this.cas.simplify(n,{steps:!1}).result)}return this.of(Ke(V("/",[V("ln",[s[1]]),V("ln",[s[0]])])),n+1)}throw new ee(`a limit of ${t} is not worked out here`)}let i;try{i=this.of(s[0],n+1)}catch(e){if(e instanceof Rs&&("sin"===t||"cos"===t))return Vs;throw e}if(i.bnd){if("sin"===t||"cos"===t||"arctan"===t||"abs"===t)return Vs;throw new ee(`${t} of something that keeps swinging is not worked out here`)}if(i.fin){if(Ps[t]&&this.isExactZero(V(Ps[t],[i.fin])))return this.blowUp(e);const n=Ke(V(t,[i.fin]));if(Hs(n))return Us(this.cas.simplify(n,{steps:!1}).result);if("ln"===t&&Math.abs(_s(i.fin))<1e-300)return Ls(-1);if(["tan","sec","csc","cot"].includes(t))return this.blowUp(e);throw new ee(`${t} has no value at the limit of its argument`)}const r=i.inf;switch(t){case"sqrt":case"ln":case"cosh":if(r<0&&"cosh"!==t)throw new Rs(`${t} has no value as its argument goes to -∞`);return Ls(1);case"abs":return Ls(1);case"sinh":return Ls(r);case"tanh":return Us(P(String(r)));case"arctan":return Us(Ke(V("/",[r>0?D("pi"):V("neg",[D("pi")]),P("2")])));case"arccot":return Us(r>0?P("0"):D("pi"));case"arcsec":case"arccsc":return Us("arcsec"===t?Ke(V("/",[D("pi"),P("2")])):P("0"));case"sin":case"cos":return Vs;case"tan":case"sec":case"csc":case"cot":throw new Rs(`${t} keeps swinging as its argument grows`);default:throw new ee(`a limit of ${t} at ∞ is not worked out here`)}}}const ni=e=>ti(e).some(e=>W(e)&&("/"===e.op&&Math.abs(_s(e.args[1]))<1e-300||"^"===e.op&&_s(e.args[1])<0&&Math.abs(_s(e.args[0]))<1e-300)),ti=(e,n=[])=>(n.push(e),W(e)&&e.args.forEach(e=>ti(e,n)),n),si=e=>e.bnd?e:e.inf?Ls(-e.inf):Us(Ke(V("neg",[e.fin])));function ii(e){if(!W(e)||"lim"!==e.op)return null;const[n,t,s,i]=e.args;if(W(t)&&"→"===t.op)return{f:n,v:t.args[0].token,to:t.args[1],side:0};if("sym"===t?.type&&s){const e="r"===i?.token?1:"l"===i?.token?-1:0;return{f:n,v:t.token,to:s,side:e}}return null}function ri(e){return"sym"!==e.type||"∞"!==e.token&&"oo"!==e.token&&"infinity"!==e.token?"sym"===e.type&&"-∞"===e.token||W(e)&&"neg"===e.op&&"sym"===e.args[0].type&&"∞"===e.args[0].token?Ls(-1):Us(Ke(e)):Ls(1)}const oi=new Set(["sin","cos","tan","sec","csc","cot"]),ai=()=>P("2");function ui(e,n){if(!li(n))return[];let t,s;try{const e=ci(n);t=new Map;s=ms(Je(fi(e,t)))}catch{return[]}const i=[];for(const n of["sin","cos","none"])try{const r="none"===n?Jt(s.num):pi(s.num,t,n),o="none"===n?Jt(s.den):pi(s.den,t,n);if(!r||!o)continue;const a=[mi(r,o)],u=[hi(r,t),hi(o,t)];u[0]&&u[1]&&a.push(mi(u[0],u[1]));for(const n of a)i.push(vi(e,gi(n,t)))}catch{}return i}const li=e=>W(e)&&(oi.has(e.op)||e.args.some(li));function ci(e){if(!W(e))return e;const n=e.args.map(ci),[t]=n,s=e=>V("sin",[e]),i=e=>V("cos",[e]),r=e=>W(e)&&"*"===e.op&&L(e.args[0])&&2===Number(e.args[0].value)?2===e.args.length?e.args[1]:V("*",e.args.slice(1)):null;switch(e.op){case"tan":return V("/",[s(t),i(t)]);case"sec":return V("/",[P("1"),i(t)]);case"csc":return V("/",[P("1"),s(t)]);case"cot":return V("/",[i(t),s(t)]);case"sin":{const e=r(t);return e?V("*",[V("*",[ai(),s(e)]),i(e)]):s(t)}case"cos":{const e=r(t);return e?V("-",[V("^",[i(e),ai()]),V("^",[s(e),ai()])]):i(t)}default:return V(e.op,n)}}function fi(e,n){if(!W(e))return e;if(("sin"===e.op||"cos"===e.op)&&!li(e.args[0])){const t=e.args[0];n.has(t.s)||n.set(t.s,{u:t,s:`$s${n.size}`,c:`$c${n.size}`});const s=n.get(t.s);return D("sin"===e.op?s.s:s.c)}return V(e.op,e.args.map(e=>fi(e,n)))}function pi(e,n,t){let s=Jt(e);for(const{s:e,c:i}of n.values()){const[n,r]="sin"===t?[e,i]:[i,e],o=Yt(s,n);if(!o)return null;const a=[];for(const[e,t]of o){const s=Math.floor(e/2),i=[t];e%2&&i.push(Je(D(n))),s&&i.push(Je(V("^",[V("-",[P("1"),V("^",[D(r),ai()])]),P(String(s))]))),a.push(Te(i))}if(s=Jt(Ie(a)),rn(s).length>200)return null}return s}function hi(e,n){let t=Jt(e);for(const{u:e,s:s,c:i}of n.values()){const n=V("sin",[V("*",[ai(),e])]),r=V("cos",[V("*",[ai(),e])]),o=[];for(const e of rn(t)){const t=en(e),a=di(t,s),u=di(t,i);if(a+u===0){o.push(e);continue}if(a+u!==2)return null;const l=$s($s(t,s,P("1")),i,P("1")),c=V("/",1===a?[n,ai()]:2===a?[V("-",[P("1"),r]),ai()]:[V("+",[P("1"),r]),ai()]);o.push(Je(V("*",[l,c])))}t=Jt(Ie(o))}return t}function di(e,n){const t=Yt(Je(e),n);return t?Math.max(0,...t.keys()):0}function mi(e,n){const t=Je(V("/",[en(e),en(n)])),s=gs(t);return s?hs(s):en(t)}function gi(e,n){let t=e;for(const{u:e,s:s,c:i}of n.values())t=$s($s(t,s,V("sin",[e])),i,V("cos",[e]));return Ke(t)}function vi(e,n){const t=e=>{if(!W(e))return e;const n=e.args.map(t);if("/"===e.op&&L(n[0])){const e=n[1],[t,s]=W(e)&&"^"===e.op&&L(e.args[1])?[e.args[0],e.args[1]]:[e,null],i=W(t)&&{cos:"sec",sin:"csc"}[t.op];if(i){const e=V(i,t.args),r=s?V("^",[e,s]):e;return 1===Number(n[0].value)?r:V("*",[n[0],r])}}return V(e.op,n)},s=Ut(Ke(t(n)),e.set.view("simplify"),{format:e.format}).node;try{const{num:e,den:n}=ms(Je(s)),t=Ke(V("/",[en(e),en(n)]));return t.s.split(" ").length<s.s.split(" ").length?t:s}catch{return s}}const bi=(e,n)=>V("int",[e,"string"==typeof n?D(n):n]);function wi(e,n,t,s=0){if(s>6)throw new ee("integration went too deep");const i=[],r=e.set.view("integrate"),o=Ut(n,e.set.view("simplify"),{format:e.format});i.push(...o.steps);let a=Ke(bi(o.node,t));for(let n=0;n<40;n++){const n=Ut(a,r,{format:e.format});i.push(...n.steps),a=n.node;const t=G(a,"pre").find(({node:e})=>{return W(n=e)&&"int"===n.op&&2===n.args.length;var n});if(!t)return{node:a,steps:i};const o=yi(e,t.node,s);if(!o)throw new ee(`no rule for ∫ ${e.format(t.node.args[0])} d${t.node.args[1].token}`);i.push(...o.steps),a=Ke(X(a,t.path,o.node))}throw new ee("integration did not finish")}function yi(e,n,t){const[s,i]=n.args,r=i.token,o=Je(s),a=function(e,n){const{num:t,den:s}=ms(e),i=as(t),r=as(s),o=i.coef.div(r.coef);if(o.isOne||!Gt(e,n))return null;const a=Te([...i.factors.map(e=>Ze(e.base,e.exp)),...r.factors.map(e=>Ze(e.base,Ve(e.exp)))]);return{c:o,rest:a}}(o,r);if(a){const t=V("*",[en(me(a.c)),bi(en(a.rest),i)]);return{node:t,steps:[e.step("integrate.constant","Take the number out",["split"],n,t,{c:en(me(a.c))})]}}const u=Jt(o);if(en(u).s!==s.s&&"add"===u.k){const t=bi(en(u),i);return{node:t,steps:[e.step("integrate.expand","Multiply out",["expand"],n,t,{})]}}const l=function(e,n){const t=new Map;for(const{node:s}of G(e,"pre")){if(!W(s))continue;const e="^"===s.op?s.args:"/"===s.op?[s.args[1]]:"der"===s.op||"int"===s.op?[]:1===s.args.length||"root"===s.op?[s.args[s.args.length-1]]:[];for(const s of e){if("sym"===s.type||!sn(s).has(n))continue;const e=Yt(Je(s),n);if(!e||1!==Math.max(...e.keys()))continue;const i=e.get(1);Gt(i,n)||we(i)&&i.q.isZero||t.set(s.s,{node:s,a:i})}}for(const s of t.values()){if(!sn(Ai(e,s.node,D("§"))).has(n))return s}return null}(s,r);if(l){const i="u"===r?"t":"u",o=Ai(s,l.node,D(i));if(!sn(o).has(r)){const s=wi(e,Ke(o),i,t+1),a=Ke($s(s.node,i,l.node)),u=en(Le(Je(a),l.a));return{node:u,steps:[e.step("integrate.substitute","Substitute",["substitute"],n,Ke(bi(o,i)),{u:D(i),inside:l.node,a:en(l.a),v:r}),...s.steps,e.step("integrate.back","Substitute back",["substitute"],s.node,u,{u:D(i),inside:l.node})]}}}const c=function(e,n,t,s){const{num:i,den:r}=ms(t);if(!Gt(r,s))return null;const o=Xt(Yt(i,s)),a=Xt(Yt(r,s));if(!o||!a||a.length<2)return null;const u=Je(D(s)),l=e=>es(e,s);if(o.length>=a.length){const{q:t,r:i}=os(o,a),r=bi(en(Ie([l(t),Le(l(i),l(a))])),D(s));return{node:r,steps:[e.step("integrate.divide","Divide the polynomials",["divide"],n,r,{})]}}const{roots:c,rest:f}=rs(a),p=new Set(c.map(String)).size===c.length,h=3===f.length&&f[1].mul(f[1]).sub(re.of(4).mul(f[0]).mul(f[2])).sign<0;if(!p||1!==f.length&&!h||!c.length&&!h)return null;const d=(e=>e.length<=1?[re.ZERO]:e.slice(1).map((e,n)=>e.mul(re.of(n+1))))(a),m=c.map(e=>ts(o,e).div(ts(d,e))),g=c.map((e,n)=>Le(me(m[n]),Ie([u,me(e.neg())])));if(!h){const t=bi(en(Ie(g)),D(s));return{node:t,steps:[e.step("integrate.partial-fractions","Partial fractions",["partial-fractions"],n,t,{})]}}let v=o;c.forEach((e,n)=>{v=Oi(v,Ni(os(a,[e.neg(),re.of(1)]).q,m[n]))});const b=c.reduce((e,n)=>Mi(e,[n.neg(),re.of(1)]),[re.of(1)]),{q:w}=os(v,b),[y,x]=[w[0]??re.ZERO,w[1]??re.ZERO],[q,k,$]=os(a,b).q,S=re.of(4).mul($).mul(q).sub(k.mul(k)),M=es([q,k,$],s),N=x.div(re.of(2).mul($)),O=y.sub(x.mul(k).div(re.of(2).mul($))),A=V("sqrt",[xi(S)]),I=V("*",[xi(N),V("ln",[V("abs",[en(M)])])]),E=V("*",[V("/",[V("*",[qi(2),xi(O)]),A]),V("arctan",[V("/",[en(es([k,$.mul(re.of(2))],s)),A])])]),T=g.length?bi(en(Ie(g)),D(s)):qi(0),j=Ke(V("+",[V("+",[T,I]),E]));return{node:j,steps:[e.step("integrate.complete-square","Complete the square",["partial-fractions"],n,j,{Q:en(M)})]}}(e,n,o,r);if(c)return c;const f=Si(e,n,r);if(f)return f;const p=function(e,n,t,s){if(s>=3)return null;const[i,r]=n.args,o="u"===t?"t":"u",a=new Set;for(const{node:r}of G(i,"pre")){if(r===i||!W(r)||r.s===i.s||a.has(r.s)||!sn(r).has(t)||["der","int"].includes(r.op))continue;let u,l,c;a.add(r.s);try{u=Ke(e.differentiate(r,t))}catch{continue}if(L(u)&&0===Number(u.value))continue;try{l=Ai(Ke(V("/",[i,u])),r,D(o))}catch{continue}if(sn(l).has(t))continue;try{c=wi(e,Ke(l),o,s+1)}catch{continue}const f=Ke($s(c.node,o,r));return{node:f,steps:[e.step("integrate.u-substitution","Substitute",["substitute"],n,Ke(bi(l,o)),{u:D(o),inside:r,du:u,v:t}),...c.steps,e.step("integrate.back","Substitute back",["substitute"],c.node,f,{u:D(o),inside:r})]}}return null}(e,n,r,t);return p||function(e,n,t,s,i){if(i>=6)return null;const r=on(t),o=r.filter(e=>Ii(e,s)||!Gt(e,s)),a=r.filter(e=>!o.includes(e));if(1!==a.length)return null;const u=Te(o),l=a[0],c=en(l),f=W(c)?c.op:"",p=["ln","arctan","arcsin","arccos","arcsec","arccsc","arccot"];if(!Gt(u,s)&&!p.includes(f))return null;let h,d,m;p.includes(f)?(h=l,d=u):(h=u,d=l);try{m=wi(e,en(d),s,i+1)}catch{return null}const g=Je(e.differentiate(en(h),s)),v=Te([h,Je(m.node)]),b=bi(en(Te([g,Je(m.node)])),D(s)),w=Ke(V("-",[en(v),b]));return{node:w,steps:[e.step("integrate.parts","Integration by parts",["parts"],n,w,{u:en(h),dv:en(d),V:m.node,du:en(g),v:s})]}}(e,n,o,r,t)}const xi=e=>en(me(e)),qi=e=>P(String(e));function ki(e,n){if(!e||!sn(e).has(n))return null;const t=Yt(Je(e),n);if(!t||1!==Math.max(...t.keys()))return null;const s=t.get(1);return!we(s)||s.q.isZero?null:{a:s.q,node:e}}function $i(e){return W(e)&&"^"===e.op&&L(e.args[1])&&Number.isInteger(Number(e.args[1].value))?{base:e.args[0],n:Number(e.args[1].value)}:{base:e,n:1}}function Si(e,n,t){const[s,i]=n.args,r=on(Je(s)).map(en).map($i),o=(e,...n)=>W(e.base)&&n.includes(e.base.op),a=(s,i,r,o={})=>({node:r,steps:[e.step(s,i,["rewrite"],n,r,{v:t,...o})]});if(2===r.length&&r.every(e=>1===e.n)){const e=r.find(e=>W(e.base)&&"^"===e.base.op&&"sym"===e.base.args[0].type&&"e"===e.base.args[0].token),n=r.find(e=>o(e,"sin","cos")),s=e&&ki(e.base.args[1],t),i=n&&ki(n.base.args[0],t);if(s&&i){const[t,r]=[s.a,i.a],o=t.mul(t).add(r.mul(r)),[u,l]=[V("sin",[i.node]),V("cos",[i.node])],c="sin"===n.base.op?V("-",[V("*",[xi(t),u]),V("*",[xi(r),l])]):V("+",[V("*",[xi(t),l]),V("*",[xi(r),u])]);return a("integrate.parts-twice","By parts twice",Ke(V("/",[V("*",[e.base,c]),xi(o)])),{e:e.base,t:n.base})}}if(2===r.length&&r.every(e=>1===e.n&&o(e,"sin","cos")&&ki(e.base.args[0],t))&&r[0].base.args[0].s!==r[1].base.args[0].s){const[e,n]="sin"===r[0].base.op?r:[r[1],r[0]],[t,s]=[e.base.args[0],n.base.args[0]],o=(e,n)=>V(e,[V(n,[t,s])]);let u;u="sin"===e.base.op&&"cos"===n.base.op?V("+",[o("sin","+"),o("sin","-")]):"cos"===e.base.op?V("+",[o("cos","-"),o("cos","+")]):V("-",[o("cos","-"),o("cos","+")]);return a("integrate.product-to-sum","Product to sum",Ke(bi(V("/",[u,qi(2)]),i)))}const u=r.find(e=>o(e,"sin")),l=r.find(e=>o(e,"cos")),c=!u||!l||u.base.args[0].s===l.base.args[0].s;if((u||l)&&c&&r.every(e=>e===u||e===l)&&[u,l].every(e=>!e||e.n>=0))for(const[n,s]of[[l,"sin"],[u,"cos"]]){if(!n||n.n<3||n.n%2==0)continue;const o=n.base.args[0],u=(n.n-1)/2,l=r.filter(e=>e!==n).map(e=>V("^",[e.base,qi(e.n)])),c=[...l,V("^",[V("-",[qi(1),V("^",[V(s,[o]),qi(2)])]),qi(u)]),V(n.base.op,[o])].reduce((e,n)=>V("*",[e,n])),f=Ke(bi(c,i)),p=a("integrate.odd-power","An odd power",f,{f:n.base,other:V(s,[o])});if("sym"!==o.type||o.token!==t)return p;const h="u"===t?"t":"u",d=l.length?r.find(e=>e!==n).n:0;if(2*u+d>100)throw new ee(`a power this high (${n.n+d}) is not integrated here`);const m="sin"===n.base.op?-1:1,g=V(s,[o]),v=V("*",[V("^",[V("-",[qi(1),V("^",[D(h),qi(2)])]),qi(u)]),V("^",[D(h),qi(d)])]),b=Ke(bi(m<0?V("neg",[v]):v,D(h))),w=Yt(Jt(Je(v)),h);if(!w)return p;const y=[...w].map(([e,n])=>V("*",[en(n),V("/",[V("^",[g,qi(e+1)]),qi(e+1)])])).reduce((e,n)=>V("+",[e,n])),x=Ke(m<0?V("neg",[y]):y);return{node:x,steps:[...p.steps,e.step("integrate.u-substitution","Substitute",["substitute"],f,b,{u:D(h),inside:g,du:m<0?V("neg",[n.base]):n.base,v:t}),e.step("integrate.back","Back to "+t,["substitute"],b,x,{u:D(h),inside:g})]}}if(1===r.length&&r[0].n>=3&&o(r[0],"sec","csc")&&"sym"===r[0].base.args[0].type&&r[0].base.args[0].token===t){const{base:e,n:n}=r[0],t=e.args[0],s="sec"===e.op?V("tan",[t]):V("cot",[t]),o=V("/",[V("*",[V("^",[e,qi(n-2)]),s]),qi(n-1)]),u=V("*",[V("/",[qi(n-2),qi(n-1)]),bi(V("^",[e,qi(n-2)]),i)]);return a("integrate.reduction","Reduction formula",Ke(V("+",["sec"===e.op?o:V("neg",[o]),u])),{f:e,n:qi(n)})}const f=e=>{if(!W(e)||"sqrt"!==e.op)return null;const n=Yt(Je(e.args[0]),t);if(!n||2!==n.size||!n.has(2)||!n.has(0))return null;const[s,i]=[n.get(2),n.get(0)];return!we(s)||!we(i)||s.q.sign>=0||i.q.sign<=0?null:{k:s.q.neg(),c:i.q,root:e}},p=D(t),h=e=>V("sqrt",[xi(e)]),d=f(s),m=W(s)&&"/"===s.op&&L(s.args[0])&&1===s.args[0].value?f(s.args[1]):null;if(d||m){const{k:e,c:n,root:t}=d??m,s=V("arcsin",[V("*",[p,h(e.div(n))])]);return a("integrate.trig-substitution","A trig substitution",Ke(d?V("+",[V("/",[V("*",[p,t]),qi(2)]),V("*",[V("/",[xi(n),V("*",[qi(2),h(e)])]),s])]):V("/",[s,h(e)])),{x:p,a:Ke(h(n.div(e)))})}return null}const Mi=(e,n)=>{const t=Array.from({length:e.length+n.length-1},()=>re.ZERO);return e.forEach((e,s)=>n.forEach((n,i)=>{t[s+i]=t[s+i].add(e.mul(n))})),t},Ni=(e,n)=>e.map(e=>e.mul(n)),Oi=(e,n)=>Array.from({length:Math.max(e.length,n.length)},(t,s)=>(e[s]??re.ZERO).sub(n[s]??re.ZERO));function Ai(e,n,t){return e.s===n.s?t:W(e)?V(e.op,e.args.map(e=>Ai(e,n,t))):e}const Ii=(e,n)=>{const t=Yt(e,n);return Boolean(t)&&[...t.values()].every(e=>!Gt(e,n))&&Math.max(...t.keys())>=1};function Ei(e,n,t,s,i,r){if([s,i].some(e=>ri(e).inf))return function(e,n,t,s,i,r){const o=[s,i].map(e=>ri(e)),a=e=>e.inf?e.inf*(1/0):Mt(e.fin,{digits:20}).number,[u,l]=o.map(a).sort((e,n)=>e-n);for(const n of r?Ti(r,t):[]){let s=[];try{s=e.solve(V("=",[n,P("0")]),t,{steps:!1}).solutions}catch{continue}for(const n of s){const s=Mt(n,{digits:20});if(Number.isFinite(s.number)&&!s.im&&s.number>u&&s.number<l)throw new ee(`the integrand has no value at ${t} = ${e.format(n)}, between the limits: split the integral there`)}}const c=(s,i,r)=>{if(!i.inf)try{const e=Ke($s(n,t,s));if(Number.isFinite(Mt(e,{digits:15}).number))return e}catch{}const o=e.limit(n,t,s,{steps:!1,side:i.inf?void 0:r});if(!o.exists)throw new ee(`the integral diverges: as ${t} → ${e.format(s)}, ${e.format(n)} has no limit (${o.reason})`);if(o.infinite)throw new ee(`the integral diverges: as ${t} → ${e.format(s)}, ${e.format(n)} goes to ${o.text}`);return o.result},f=a(o[0])<a(o[1]),[p,h]=[c(s,o[0],f?"right":"left"),c(i,o[1],f?"left":"right")],d=Ke(V("-",[h,p])),m=V("-",[h,p]);return{value:d,step:e.step("integrate.improper","Limits at the ends",["evaluate"],n,m,{a:s,b:i,F:n,v:t})}}(e,n,t,s,i,r);if(r&&!sn(s).size&&!sn(i).size){const o=Mt(s,{digits:20}).number,a=Mt(i,{digits:20}).number,u=[...sn(r)].filter(e=>e!==t);if(!u.length){const[s,i]=o<=a?[o,a]:[a,o];for(const o of Ti(r,t)){let r=[];try{r=e.solve(V("=",[o,P("0")]),t,{steps:!1}).solutions}catch{continue}for(const o of r){const r=Mt(o,{digits:20});if(!Number.isFinite(r.number)||r.im||r.number<s||r.number>i)continue;if(r.number>s&&r.number<i)throw new ee(`the integrand has no value at ${t} = ${e.format(o)}, between the limits, so F(b) - F(a) would be wrong`);let a=NaN;try{a=Mt(Ke($s(n,t,o)),{digits:15}).number}catch{}if(!Number.isFinite(a))throw new ee(`the integral diverges at ${t} = ${e.format(o)}: F has no value at that limit`)}}}for(let e=0;!u.length&&e<=64;e++){const n=o+(a-o)*(e+.5)/65;try{const e=Mt($s(r,t,P(n.toFixed(15))),{digits:15}).number;if(!Number.isFinite(e))throw new ee("not finite")}catch(e){throw new ee(`the integrand has no value at ${t} = ${n.toPrecision(6)}, between the limits, so F(b) - F(a) would be wrong`)}}}const o=e=>Ke($s(n,t,e)),a=Ke(V("-",[o(i),o(s)])),u=V("-",[o(i),o(s)]);return{value:a,step:e.step("integrate.evaluate","Between the limits",["evaluate"],n,u,{a:s,b:i,F:n,v:t})}}function Ti(e,n){const t=[],s={tan:"cos",sec:"cos",csc:"sin",cot:"sin"};return G(e,"pre").forEach(({node:e})=>{if(!W(e))return;let i=null;"/"===e.op?i=e.args[1]:"^"===e.op&&"num"===e.args[1].type&&e.args[1].value<0||"^"===e.op&&W(e.args[1])&&"neg"===e.args[1].op?i=e.args[0]:s[e.op]&&(i=V(s[e.op],[e.args[0]])),i&&sn(i).has(n)&&!t.some(e=>e.s===i.s)&&t.push(i)}),t}const ji={"=":1,"≠":1,"<":1,">":1,"≤":1,"≥":1,"+":2,"-":2,"±":2,"*":3,"/":3,neg:4,pm:4,"^":5},Zi={pi:"π","≤":"≤","≥":"≥"};function zi(e){return Pi(e).text}function Fi(e,n,t=!1){return e.prec<n||t&&e.prec===n?`(${e.text})`:e.text}const Bi=e=>"op"===e.type?e.op:null,Ci=e=>e.text.startsWith("-"),Di={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]};function Pi(e){if("num"===e.type)return{text:e.token,prec:e.token.startsWith("-")?4:9};if("sym"===e.type)return{text:Zi[e.token]??e.token,prec:9};const n=e.args.map(Pi),t=ji[e.op];switch(e.op){case"+":case"-":case"±":{const s="+"===e.op&&["+","-"].includes(Bi(e.args[1])),i=Ci(n[1])?`(${n[1].text})`:s?n[1].text:Fi(n[1],t,!0);return{text:`${Fi(n[0],t)} ${"±"===e.op?"±":e.op} ${i}`,prec:t}}case"*":{const s=Fi(n[0],t),i=Ci(n[1])?`(${n[1].text})`:"*"===Bi(e.args[1])?n[1].text:Fi(n[1],t,!0);return{text:"num"===e.args[0].type&&"num"!==e.args[1].type&&!/^[\d(-]/.test(i)||"sym"===e.args[1].type&&"i"===e.args[1].token&&!/[\dA-Za-z]$/.test(s)?`${s}${i}`:`${s}·${i}`,prec:t}}case"/":return{text:`${Fi(n[0],t)}/${Fi(n[1],t,!0)}`,prec:t};case"^":return{text:`${Fi(n[0],t+1)}^${Fi(n[1],t)}`,prec:t};case"neg":return{text:`-${Fi(n[0],3)}`,prec:4};case"pm":return{text:`±${Fi(n[0],4)}`,prec:4};case"!":return{text:`${Fi(n[0],9)}!`,prec:6};case"abs":return{text:`|${n[0].text}|`,prec:9};case"root":return{text:`root(${n[0].text}, ${n[1].text})`,prec:9};case"der":return"op"===e.args[1].type&&"="===e.args[1].op?{text:`d/d${n[1].text.split(" = ")[0]} (${n[0].text}) at ${n[1].text}`,prec:1}:{text:`d/d${n[1].text} (${n[0].text})`,prec:6};case"int":return{text:4===n.length?`∫ from ${n[2].text} to ${n[3].text} of ${n[0].text} d${n[1].text}`:`∫ ${n[0].text} d${n[1].text}`,prec:1};case"|":return{text:`${n[0].text} or ${n[1].text}`,prec:0};case"_":return{text:`${Fi(n[0],9)}_${n[1].prec>=9&&!/\s/.test(n[1].text)?n[1].text:`(${n[1].text})`}`,prec:9};case"()":case"[]":case"{}":case"(]":case"[)":return{text:`${Di[e.op][0]}${n.map(e=>e.text).join(", ")}${Di[e.op][1]}`,prec:9};case"&":return{text:`${n[0].text} and ${n[1].text}`,prec:0};default:return void 0!==t?{text:`${Fi(n[0],t)} ${e.op} ${Fi(n[1],t,!0)}`,prec:t}:{text:`${e.op.replace(/^\\:?/,"")}(${n.map(e=>e.text).join(", ")})`,prec:9}}}const Ri=['name: Differentiation\n\n# `u v der` means d(u)/dv (MathZetta\'s postfix: mathzetta/docs/postfix.md). Every rule here rewrites one derivative into smaller\n# derivatives, so differentiating always terminates: the expressions sitting\n# under a `D` get strictly smaller at every step.\n#\n# The variable is a slot, not a fixed letter, so these rules work for d/dx,\n# d/dt or anything else. That is what freeOf and dependsOn are for: they ask\n# whether one operand mentions whatever the variable slot bound to.\n#\n# Where two rules share a structure key, requirements keep them apart and\n# priority picks the one that reads better. The constant-multiple rule outranks\n# the product rule for exactly that reason.\n\nrules:\n # ---- the two base cases ----------------------------------------------\n - id: d-constant\n name: Derivative of a constant\n mode: differentiate\n pattern: c v der\n require:\n - [freeOf, c, v]\n output: "0"\n priority: 10\n explain: "{c} does not change when {v} changes, so its rate of change is 0."\n tags: [base]\n\n - id: d-variable\n name: Derivative of the variable\n mode: differentiate\n pattern: u v der\n require:\n - [sameAs, u, v]\n output: "1"\n priority: 10\n explain: "{v} changes exactly as fast as itself, so the rate is 1."\n tags: [base]\n\n # ---- splitting a derivative into smaller ones ------------------------\n - id: d-sum\n name: Sum rule\n mode: differentiate\n pattern: u w + v der\n output: u v der w v der +\n explain: "Differentiate {u} and {w} separately, then add the two results."\n tags: [split]\n\n - id: d-difference\n name: Difference rule\n mode: differentiate\n pattern: u w - v der\n output: u v der w v der -\n explain: "Differentiate {u} and {w} separately, then subtract the second from the first."\n tags: [split]\n\n - id: d-negate\n name: Derivative of a negative\n mode: differentiate\n pattern: u neg v der\n output: u v der neg\n explain: "The minus sign just carries through to the derivative of {u}."\n tags: [split]\n\n - id: d-constant-multiple\n name: Constant multiple rule\n mode: differentiate\n pattern: c u * v der\n commutative: true\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n output: c u v der *\n priority: 5\n explain: "{c} is only a scale factor, so it comes along unchanged while {u} is differentiated."\n tags: [split]\n\n - id: d-constant-divisor\n name: Dividing by a constant\n mode: differentiate\n pattern: u c / v der\n require:\n - [freeOf, c, v]\n output: u v der c /\n priority: 5\n explain: "Dividing by {c} is only a scale factor, so differentiate {u} and keep the division."\n tags: [split]\n\n - id: d-product\n name: Product rule\n mode: differentiate\n pattern: u w * v der\n require:\n - [dependsOn, u, v]\n - [dependsOn, w, v]\n output: u v der w * u w v der * +\n explain: "Differentiate {u} and keep {w}, then keep {u} and differentiate {w}, and add the two."\n tags: [split]\n\n - id: d-quotient\n name: Quotient rule\n mode: differentiate\n pattern: u w / v der\n output: u v der w * u w v der * - w 2 ^ /\n explain: "Bottom times the derivative of the top, minus top times the derivative of the bottom, all over {w} squared."\n tags: [split]\n\n # ---- powers -----------------------------------------------------------\n - id: d-power-of-variable\n name: Power rule\n mode: differentiate\n pattern: u n ^ v der\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n output: n u n 1 - ^ *\n fold: true\n priority: 6\n explain: "Bring the {n} down in front and drop the power by one."\n tags: [power]\n\n - id: d-power-chain\n name: Power rule with the chain rule\n mode: differentiate\n pattern: u n ^ v der\n require:\n - [freeOf, n, v]\n - [dependsOn, u, v]\n output: n u n 1 - ^ * u v der *\n fold: true\n explain: "Bring the {n} down and drop the power by one, then multiply by the derivative of {u}."\n tags: [power, chain]\n\n - id: d-exponential-base\n name: Derivative of a constant to a power\n mode: differentiate\n pattern: a u ^ v der\n require:\n - [freeOf, a, v]\n - [dependsOn, u, v]\n output: a u ^ a ln * u v der *\n explain: "A constant base gives itself back, multiplied by the natural log of {a} and the derivative of {u}."\n tags: [power, chain]\n\n # ---- the standard functions, each with its chain-rule factor ---------\n # e^u is `=e u ^`: the base is the literal symbol e. Outranks the general\n # a^u rule (which would give e^u · ln e · u\').\n - id: d-exp\n name: Derivative of e to a power\n mode: differentiate\n pattern: =e u ^ v der\n require:\n - [dependsOn, u, v]\n output: =e u ^ u v der *\n priority: 7\n explain: "e to a power is its own derivative, times the derivative of {u}."\n tags: [chain]\n\n - id: d-ln\n name: Derivative of a natural log\n mode: differentiate\n pattern: u ln v der\n output: u v der u /\n explain: "The derivative of {u} over {u} itself."\n tags: [chain]\n\n - id: d-sqrt\n name: Derivative of a square root\n mode: differentiate\n pattern: u sqrt v der\n output: u v der 2 u sqrt * /\n explain: "The derivative of {u}, over twice the square root of {u}."\n tags: [chain]\n\n - id: d-sin\n name: Derivative of sine\n mode: differentiate\n pattern: u sin v der\n output: u cos u v der *\n explain: "Sine differentiates to cosine, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-cos\n name: Derivative of cosine\n mode: differentiate\n pattern: u cos v der\n output: u sin u v der * neg\n explain: "Cosine differentiates to minus sine, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-tan\n name: Derivative of tangent\n mode: differentiate\n pattern: u tan v der\n output: u v der u cos 2 ^ /\n explain: "The derivative of {u}, over cosine squared of {u}."\n tags: [chain, trig]\n\n # ---- the rest of the standard functions -----------------------------\n - id: d-csc\n name: Derivative of cosecant\n mode: differentiate\n pattern: u csc v der\n output: u csc u cot * u v der * neg\n explain: "Cosecant differentiates to minus cosecant times cotangent, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-sec\n name: Derivative of secant\n mode: differentiate\n pattern: u sec v der\n output: u sec u tan * u v der *\n explain: "Secant differentiates to secant times tangent, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-cot\n name: Derivative of cotangent\n mode: differentiate\n pattern: u cot v der\n output: u v der u sin 2 ^ / neg\n explain: "Minus the derivative of {u}, over sine squared of {u}."\n tags: [chain, trig]\n\n - id: d-arcsin\n name: Derivative of arcsine\n mode: differentiate\n pattern: u arcsin v der\n output: u v der 1 u 2 ^ - sqrt /\n explain: "The derivative of {u}, over the square root of 1 minus {u} squared."\n tags: [chain, trig]\n\n - id: d-arccos\n name: Derivative of arccosine\n mode: differentiate\n pattern: u arccos v der\n output: u v der 1 u 2 ^ - sqrt / neg\n explain: "Minus the derivative of {u}, over the square root of 1 minus {u} squared."\n tags: [chain, trig]\n\n - id: d-arctan\n name: Derivative of arctangent\n mode: differentiate\n pattern: u arctan v der\n output: u v der 1 u 2 ^ + /\n explain: "The derivative of {u}, over 1 plus {u} squared."\n tags: [chain, trig]\n\n - id: d-arcsec\n name: Derivative of arcsecant\n mode: differentiate\n pattern: u arcsec v der\n output: u v der u abs u 2 ^ 1 - sqrt * /\n explain: "The derivative of {u}, over the absolute value of {u} times the square root of {u} squared minus 1."\n tags: [chain, trig]\n\n - id: d-arccsc\n name: Derivative of arccosecant\n mode: differentiate\n pattern: u arccsc v der\n output: u v der u abs u 2 ^ 1 - sqrt * / neg\n explain: "Minus the derivative of {u}, over the absolute value of {u} times the square root of {u} squared minus 1."\n tags: [chain, trig]\n\n - id: d-arccot\n name: Derivative of arccotangent\n mode: differentiate\n pattern: u arccot v der\n output: u v der 1 u 2 ^ + / neg\n explain: "Minus the derivative of {u}, over 1 plus {u} squared."\n tags: [chain, trig]\n\n - id: d-sinh\n name: Derivative of hyperbolic sine\n mode: differentiate\n pattern: u sinh v der\n output: u cosh u v der *\n explain: "Hyperbolic sine differentiates to hyperbolic cosine, times the derivative of {u}."\n tags: [chain, hyperbolic]\n\n - id: d-cosh\n name: Derivative of hyperbolic cosine\n mode: differentiate\n pattern: u cosh v der\n output: u sinh u v der *\n explain: "Hyperbolic cosine differentiates to hyperbolic sine — no minus sign, unlike cosine — times the derivative of {u}."\n tags: [chain, hyperbolic]\n\n - id: d-tanh\n name: Derivative of hyperbolic tangent\n mode: differentiate\n pattern: u tanh v der\n output: u v der u cosh 2 ^ /\n explain: "The derivative of {u}, over hyperbolic cosine squared of {u}."\n tags: [chain, hyperbolic]\n\n - id: d-arcsinh\n name: Derivative of inverse hyperbolic sine\n mode: differentiate\n pattern: u arcsinh v der\n output: u v der u 2 ^ 1 + sqrt /\n explain: "The derivative of {u}, over the square root of {u} squared plus 1."\n tags: [chain, hyperbolic]\n\n - id: d-arccosh\n name: Derivative of inverse hyperbolic cosine\n mode: differentiate\n pattern: u arccosh v der\n output: u v der u 2 ^ 1 - sqrt /\n explain: "The derivative of {u}, over the square root of {u} squared minus 1."\n tags: [chain, hyperbolic]\n\n - id: d-arctanh\n name: Derivative of inverse hyperbolic tangent\n mode: differentiate\n pattern: u arctanh v der\n output: u v der 1 u 2 ^ - /\n explain: "The derivative of {u}, over 1 minus {u} squared."\n tags: [chain, hyperbolic]\n\n # log base a: `a u log` in MathZetta\'s postfix\n - id: d-log\n name: Derivative of a logarithm\n mode: differentiate\n pattern: a u log v der\n require:\n - [freeOf, a, v]\n output: u v der u a ln * /\n explain: "The derivative of {u}, over {u} times the natural log of {a}."\n tags: [chain]\n\n - id: d-abs\n name: Derivative of an absolute value\n mode: differentiate\n pattern: u abs v der\n output: u u abs / u v der *\n explain: "The absolute value keeps the sign of {u}: {u} over its absolute value, times the derivative of {u}."\n tags: [chain]\n\n # n-th root: `n u root`\n - id: d-root\n name: Derivative of a root\n mode: differentiate\n pattern: n u root v der\n require:\n - [freeOf, n, v]\n output: u v der n n u root n 1 - ^ * /\n fold: true\n explain: "The derivative of {u}, over {n} times the {n}th root of {u} to the power {n} minus 1."\n tags: [chain]\n','name: More derivatives\n\n# Derivative rules the CAS adds to rules/calculus.yaml (which calcvidnew also uses).\n\nrules:\n - id: d-general-power\n name: A power with the variable in both places\n mode: differentiate\n pattern: u w ^ v der\n require:\n - [dependsOn, u, v]\n - [dependsOn, w, v]\n output: u w ^ w v der u ln * w u v der * u / + *\n explain: "Write {u}^{w} as e^({w} ln {u}) and use the chain rule: the derivative is {u}^{w} times the derivative of {w} ln {u}."\n tags: [chain]\n','name: Integrals\n\n# mode: integrate. `f v 2 int` is ∫ f dv (MathZetta\'s postfix; the 2 counts f and v).\n# Each rule turns one integral into smaller ones, or into an answer. The CAS also\n# tries, when no rule fits: multiplying out, a linear substitution (∫ f(ax + b) dx\n# from the rule for ∫ f(u) du), and integration by parts for polynomial × e^, sin,\n# cos, ln, arctan. Definite integrals are the antiderivative between the limits.\n#\n# Patterns see the normal form: 1/x is "1 x /", x^-2 is "1 x 2 ^ /", √x is "x sqrt",\n# 1/√(1 - x²) is "1 x 2 ^ neg 1 + sqrt /".\n\nrules:\n # ---- splitting -----------------------------------------------------------\n - id: i-sum\n name: Sum rule\n mode: integrate\n pattern: u w + v 2 int\n output: u v 2 int w v 2 int +\n explain: "Integrate {u} and {w} separately, and add."\n tags: [split]\n\n - id: i-difference\n name: Difference rule\n mode: integrate\n pattern: u w - v 2 int\n output: u v 2 int w v 2 int -\n explain: "Integrate {u} and {w} separately, and subtract."\n tags: [split]\n\n - id: i-negate\n name: A minus sign\n mode: integrate\n pattern: u neg v 2 int\n output: u v 2 int neg\n explain: "The minus sign comes out of the integral."\n tags: [split]\n\n - id: i-constant-multiple\n name: Constant multiple\n mode: integrate\n pattern: c u * v 2 int\n commutative: true\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n output: c u v 2 int *\n priority: 5\n explain: "{c} doesn\'t change with {v}, so it comes out of the integral."\n tags: [split]\n\n - id: i-constant-divisor\n name: Dividing by a constant\n mode: integrate\n pattern: u c / v 2 int\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n output: u v 2 int c /\n priority: 5\n explain: "Dividing by {c} comes out of the integral."\n tags: [split]\n\n - id: i-constant-over\n name: A constant over something\n mode: integrate\n pattern: c u / v 2 int\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n when:\n c: [notOne]\n output: c 1 u / v 2 int *\n priority: 4\n explain: "{c} comes out of the integral, leaving ∫ 1/{u}."\n tags: [split]\n\n # ---- the table -----------------------------------------------------------\n - id: i-constant\n name: Integral of a constant\n mode: integrate\n pattern: c v 2 int\n require:\n - [freeOf, c, v]\n output: c v *\n priority: 10\n explain: "A constant {c} integrates to {c}·{v}."\n tags: [base]\n\n - id: i-variable\n name: Integral of the variable\n mode: integrate\n pattern: u v 2 int\n require:\n - [sameAs, u, v]\n output: v 2 ^ 2 /\n priority: 10\n explain: "∫ {v} d{v} = {v}²/2."\n tags: [base]\n\n - id: i-power\n name: Power rule\n mode: integrate\n pattern: u n ^ v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n when:\n n: [notMinusOne]\n output: v n 1 + ^ n 1 + /\n explain: "Add 1 to the power and divide by the new power: {result}."\n tags: [power]\n\n - id: i-reciprocal\n name: Integral of 1/x\n mode: integrate\n pattern: 1 u / v 2 int\n require:\n - [sameAs, u, v]\n output: v abs ln\n explain: "∫ 1/{v} d{v} = ln|{v}| (the power rule can\'t divide by 0 here)."\n tags: [log]\n\n - id: i-reciprocal-power\n name: Power rule (a power below)\n mode: integrate\n pattern: 1 u n ^ / v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n when:\n n: [notOne]\n output: v 1 n - ^ 1 n - /\n explain: "1/{v}^{n} is {v}^(-{n}): add 1 to the power and divide by it."\n tags: [power]\n\n - id: i-sqrt\n name: Integral of a square root\n mode: integrate\n pattern: u sqrt v 2 int\n require:\n - [sameAs, u, v]\n output: 2 v 3 2 / ^ * 3 /\n explain: "√{v} is {v}^(1/2): add 1 to the power and divide by 3/2."\n tags: [power]\n\n - id: i-reciprocal-sqrt\n name: Integral of 1/√x\n mode: integrate\n pattern: 1 u sqrt / v 2 int\n require:\n - [sameAs, u, v]\n output: 2 v sqrt *\n explain: "1/√{v} is {v}^(-1/2): add 1 to the power and divide by 1/2."\n tags: [power]\n\n - id: i-root\n name: Integral of a root\n mode: integrate\n pattern: n u root v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n output: v 1 n / 1 + ^ 1 n / 1 + /\n explain: "The {n}th root of {v} is {v}^(1/{n}): add 1 to the power and divide by it."\n tags: [power]\n\n - id: i-exp\n name: Integral of e^x\n mode: integrate\n pattern: =e u ^ v 2 int\n require:\n - [sameAs, u, v]\n output: =e v ^\n explain: "e^{v} is its own integral."\n tags: [exp]\n\n - id: i-exponential\n name: Integral of a^x\n mode: integrate\n pattern: a u ^ v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, a, v]\n output: a v ^ a ln /\n explain: "∫ {a}^{v} d{v} = {a}^{v} / ln {a}."\n tags: [exp]\n\n - id: i-ln\n name: Integral of ln x\n mode: integrate\n pattern: u ln v 2 int\n require:\n - [sameAs, u, v]\n output: v v ln * v -\n explain: "By parts: ∫ ln {v} d{v} = {v} ln {v} - {v}."\n tags: [log]\n\n - { id: i-sin, name: Integral of sin, mode: integrate, pattern: u sin v 2 int, require: [[sameAs, u, v]], output: v cos neg, tags: [trig], explain: "The derivative of -cos {v} is sin {v}." }\n - { id: i-cos, name: Integral of cos, mode: integrate, pattern: u cos v 2 int, require: [[sameAs, u, v]], output: v sin, tags: [trig], explain: "The derivative of sin {v} is cos {v}." }\n - { id: i-tan, name: Integral of tan, mode: integrate, pattern: u tan v 2 int, require: [[sameAs, u, v]], output: v cos abs ln neg, tags: [trig], explain: "tan = sin/cos, and -ln|cos {v}| differentiates to it." }\n - { id: i-sec-squared, name: Integral of sec², mode: integrate, pattern: 1 u cos 2 ^ / v 2 int, require: [[sameAs, u, v]], output: v tan, tags: [trig], explain: "The derivative of tan {v} is 1/cos²{v}." }\n - { id: i-sec-squared-written, name: Integral of sec², mode: integrate, pattern: u sec 2 ^ v 2 int, require: [[sameAs, u, v]], output: v tan, tags: [trig], explain: "The derivative of tan {v} is sec²{v}." }\n - { id: i-csc-squared, name: Integral of csc², mode: integrate, pattern: 1 u sin 2 ^ / v 2 int, require: [[sameAs, u, v]], output: v cot neg, tags: [trig], explain: "The derivative of -cot {v} is 1/sin²{v}." }\n - { id: i-sin-squared, name: Integral of sin², mode: integrate, pattern: u sin 2 ^ v 2 int, require: [[sameAs, u, v]], output: v 2 / 2 v * sin 4 / -, tags: [trig], explain: "sin²{v} = (1 - cos 2{v})/2, which integrates term by term." }\n - { id: i-cos-squared, name: Integral of cos², mode: integrate, pattern: u cos 2 ^ v 2 int, require: [[sameAs, u, v]], output: v 2 / 2 v * sin 4 / +, tags: [trig], explain: "cos²{v} = (1 + cos 2{v})/2, which integrates term by term." }\n - { id: i-sec, name: Integral of sec, mode: integrate, pattern: u sec v 2 int, require: [[sameAs, u, v]], output: v sec v tan + abs ln, tags: [trig], explain: "The derivative of ln|sec {v} + tan {v}| is sec {v}." }\n - { id: i-csc, name: Integral of csc, mode: integrate, pattern: u csc v 2 int, require: [[sameAs, u, v]], output: v csc v cot + abs ln neg, tags: [trig], explain: "The derivative of -ln|csc {v} + cot {v}| is csc {v}." }\n - { id: i-cot, name: Integral of cot, mode: integrate, pattern: u cot v 2 int, require: [[sameAs, u, v]], output: v sin abs ln, tags: [trig], explain: "cot = cos/sin, and ln|sin {v}| differentiates to it." }\n - { id: i-sec-tan, name: Integral of sec·tan, mode: integrate, pattern: u sec u tan * v 2 int, commutative: true, require: [[sameAs, u, v]], output: v sec, tags: [trig], explain: "The derivative of sec {v} is sec {v} tan {v}." }\n - { id: i-csc-cot, name: Integral of csc·cot, mode: integrate, pattern: u csc u cot * v 2 int, commutative: true, require: [[sameAs, u, v]], output: v csc neg, tags: [trig], explain: "The derivative of -csc {v} is csc {v} cot {v}." }\n - { id: i-sinh, name: Integral of sinh, mode: integrate, pattern: u sinh v 2 int, require: [[sameAs, u, v]], output: v cosh, tags: [trig], explain: "The derivative of cosh {v} is sinh {v}." }\n - { id: i-cosh, name: Integral of cosh, mode: integrate, pattern: u cosh v 2 int, require: [[sameAs, u, v]], output: v sinh, tags: [trig], explain: "The derivative of sinh {v} is cosh {v}." }\n - { id: i-arctan, name: Integral of 1/(1 + x²), mode: integrate, pattern: 1 u 2 ^ 1 + / v 2 int, require: [[sameAs, u, v]], output: v arctan, tags: [trig], explain: "The derivative of arctan {v} is 1/(1 + {v}²)." }\n - { id: i-arcsin, name: Integral of 1/√(1 - x²), mode: integrate, pattern: 1 u 2 ^ neg 1 + sqrt / v 2 int, require: [[sameAs, u, v]], output: v arcsin, tags: [trig], explain: "The derivative of arcsin {v} is 1/√(1 - {v}²)." }\n','name: Values and identities\n\n# The CAS\'s simplify rules (mode: simplify). They see expressions in normal form\n# (src/cas/form.js), as drawn: x/2, 2x - 3, -x, √x is "x sqrt",\n# ∛x is "3 x root", π/6 is "=pi 6 /", 2π/3 is "2 =pi * 3 /", e^x is "=e x ^".\n#\n# - a word is a slot (u, v, n …); a fixed symbol is written =pi, =e\n# - a number is itself; "1 2 /" is ½\n# - arithmetic (2 + 3, x + x, √8 = 2√2) is done for you before and after every rule\n# - a rule for a sum or product of two parts also fires on any two parts of a longer one\n# - tags pick what a step list shows (steps: \'brief\' hides value, identity, tidy …)\n#\n# To change one: copy it into a file of your own with the same id and edit it;\n# to turn one off: give its id with enabled: false. createCAS({ rules: [yours] }).\n\nrules:\n # ---- logs and exponentials -------------------------------------------\n - id: ln-one\n name: Log of 1\n pattern: 1 ln\n output: "0"\n explain: "e^0 = 1, so ln 1 = 0."\n tags: [value]\n\n - id: ln-e\n name: Log of e\n pattern: =e ln\n output: "1"\n explain: "e^1 = e, so ln e = 1."\n tags: [value]\n\n - id: ln-exp\n name: Log undoes e to a power\n pattern: =e u ^ ln\n output: u\n explain: "ln and e^ undo each other: ln(e^{u}) = {u}."\n tags: [inverse]\n\n - id: exp-ln\n name: e to a power undoes the log\n pattern: =e u ln ^\n output: u\n explain: "e^ and ln undo each other: e^(ln {u}) = {u} (for {u} > 0)."\n tags: [inverse]\n\n - id: exp-multiple-ln\n name: A multiple of a log in a power\n pattern: =e n u ln * ^\n when:\n n: [isRational]\n output: u n ^\n explain: "e^({n} ln {u}) = (e^(ln {u}))^{n} = {result}."\n tags: [inverse]\n\n - id: log-same-base\n name: Log of its own base\n pattern: b b log\n output: "1"\n explain: "{b}^1 = {b}, so the log of {b} to base {b} is 1."\n tags: [value]\n\n - id: log-of-power\n name: Log undoes a power of its base\n pattern: b b u ^ log\n output: u\n explain: "log base {b} and {b}^ undo each other."\n tags: [inverse]\n\n - id: power-of-log\n name: A power undoes the log to its base\n pattern: b b u log ^\n output: u\n explain: "{b}^(log base {b} of {u}) = {u}."\n tags: [inverse]\n\n # ---- roots and absolute value --------------------------------------------\n - id: sqrt-of-square\n name: Square root of a square\n pattern: u 2 ^ sqrt\n output: u abs\n explain: "√({u}²) is the size of {u}, whatever its sign: |{u}|."\n tags: [identity]\n\n - id: abs-squared\n name: Absolute value squared\n pattern: u abs 2 ^\n output: u 2 ^\n explain: "Squaring removes the sign anyway: |{u}|² = {u}²."\n tags: [identity]\n\n - id: abs-of-abs\n name: Absolute value twice\n pattern: u abs abs\n output: u abs\n explain: "|{u}| is never negative, so its absolute value is itself."\n tags: [identity]\n\n - id: abs-positive\n name: Absolute value of a positive number\n pattern: u abs\n when:\n u: [isPositiveConstant]\n output: u\n explain: "{u} is positive, so |{u}| = {u}."\n tags: [value]\n\n - id: abs-negative\n name: Absolute value of a negative number\n pattern: u abs\n when:\n u: [isNegativeConstant]\n output: u neg\n explain: "{u} is negative, so |{u}| = -({u})."\n tags: [value]\n\n - id: abs-of-exp\n name: e to a power is positive\n pattern: =e u ^ abs\n output: =e u ^\n explain: "e to any power is positive, so the absolute value changes nothing."\n tags: [identity]\n\n # ---- trigonometry: signs and turns ---------------------------------------\n - id: sin-odd\n name: Sine of a negative angle\n pattern: u sin\n when:\n u: [hasMinusSign]\n output: u neg sin neg\n explain: "sin(-θ) = -sin θ."\n tags: [symmetry]\n\n - id: cos-even\n name: Cosine of a negative angle\n pattern: u cos\n when:\n u: [hasMinusSign]\n output: u neg cos\n explain: "cos(-θ) = cos θ."\n tags: [symmetry]\n\n - id: tan-odd\n name: Tangent of a negative angle\n pattern: u tan\n when:\n u: [hasMinusSign]\n output: u neg tan neg\n explain: "tan(-θ) = -tan θ."\n tags: [symmetry]\n\n - id: sin-full-turn\n name: A full turn\n pattern: u sin\n when:\n u: [[piMultipleAtLeast, 2]]\n output: u 2 =pi * - sin\n explain: "Turning a full 2π brings you back: sin({u}) = sin({u} - 2π)."\n tags: [symmetry]\n\n - id: cos-full-turn\n name: A full turn\n pattern: u cos\n when:\n u: [[piMultipleAtLeast, 2]]\n output: u 2 =pi * - cos\n explain: "Turning a full 2π brings you back: cos({u}) = cos({u} - 2π)."\n tags: [symmetry]\n\n - id: tan-half-turn\n name: Tangent repeats every π\n pattern: u tan\n when:\n u: [[piMultipleAtLeast, 1]]\n output: u =pi - tan\n explain: "tan repeats every π: tan({u}) = tan({u} - π)."\n tags: [symmetry]\n\n - id: sin-half-turn\n name: A half turn\n pattern: u sin\n when:\n u: [[piMultipleAbove, 1], [piMultipleBelow, 2]]\n output: u =pi - sin neg\n explain: "Half a turn flips the sign: sin({u}) = -sin({u} - π)."\n tags: [symmetry]\n\n - id: cos-half-turn\n name: A half turn\n pattern: u cos\n when:\n u: [[piMultipleAbove, 1], [piMultipleBelow, 2]]\n output: u =pi - cos neg\n explain: "Half a turn flips the sign: cos({u}) = -cos({u} - π)."\n tags: [symmetry]\n\n - id: sin-second-quarter\n name: The second quarter turn\n pattern: u sin\n when:\n u: [[piMultipleAbove, 1/2], [piMultipleAtMost, 1]]\n output: =pi u - sin\n explain: "sin({u}) = sin(π - {u})."\n tags: [symmetry]\n\n - id: cos-second-quarter\n name: The second quarter turn\n pattern: u cos\n when:\n u: [[piMultipleAbove, 1/2], [piMultipleAtMost, 1]]\n output: =pi u - cos neg\n explain: "cos({u}) = -cos(π - {u})."\n tags: [symmetry]\n\n - id: tan-second-quarter\n name: The second quarter turn\n pattern: u tan\n when:\n u: [[piMultipleAbove, 1/2], [piMultipleBelow, 1]]\n output: =pi u - tan neg\n explain: "tan({u}) = -tan(π - {u})."\n tags: [symmetry]\n\n # ---- trigonometry: the standard angles -------------------------------------\n - { id: sin-0, name: Sine of 0, pattern: 0 sin, output: "0", tags: [value], explain: "sin 0 = 0." }\n - { id: sin-pi-6, name: Sine of π/6, pattern: =pi 6 / sin, output: 1 2 /, tags: [value], explain: "sin(π/6) = 1/2." }\n - { id: sin-pi-4, name: Sine of π/4, pattern: =pi 4 / sin, output: 2 sqrt 2 /, tags: [value], explain: "sin(π/4) = √2/2." }\n - { id: sin-pi-3, name: Sine of π/3, pattern: =pi 3 / sin, output: 3 sqrt 2 /, tags: [value], explain: "sin(π/3) = √3/2." }\n - { id: sin-pi-2, name: Sine of π/2, pattern: =pi 2 / sin, output: "1", tags: [value], explain: "sin(π/2) = 1." }\n - { id: sin-pi, name: Sine of π, pattern: =pi sin, output: "0", tags: [value], explain: "sin π = 0." }\n - { id: cos-0, name: Cosine of 0, pattern: 0 cos, output: "1", tags: [value], explain: "cos 0 = 1." }\n - { id: cos-pi-6, name: Cosine of π/6, pattern: =pi 6 / cos, output: 3 sqrt 2 /, tags: [value], explain: "cos(π/6) = √3/2." }\n - { id: cos-pi-4, name: Cosine of π/4, pattern: =pi 4 / cos, output: 2 sqrt 2 /, tags: [value], explain: "cos(π/4) = √2/2." }\n - { id: cos-pi-3, name: Cosine of π/3, pattern: =pi 3 / cos, output: 1 2 /, tags: [value], explain: "cos(π/3) = 1/2." }\n - { id: cos-pi-2, name: Cosine of π/2, pattern: =pi 2 / cos, output: "0", tags: [value], explain: "cos(π/2) = 0." }\n - { id: cos-pi, name: Cosine of π, pattern: =pi cos, output: "-1", tags: [value], explain: "cos π = -1." }\n - { id: tan-0, name: Tangent of 0, pattern: 0 tan, output: "0", tags: [value], explain: "tan 0 = 0." }\n - { id: tan-pi-6, name: Tangent of π/6, pattern: =pi 6 / tan, output: 3 sqrt 3 /, tags: [value], explain: "tan(π/6) = √3/3." }\n - { id: tan-pi-4, name: Tangent of π/4, pattern: =pi 4 / tan, output: "1", tags: [value], explain: "tan(π/4) = 1." }\n - { id: tan-pi-3, name: Tangent of π/3, pattern: =pi 3 / tan, output: 3 sqrt, tags: [value], explain: "tan(π/3) = √3." }\n - { id: arcsin-0, name: Arcsine of 0, pattern: 0 arcsin, output: "0", tags: [value], explain: "sin 0 = 0, so arcsin 0 = 0." }\n - { id: arcsin-half, name: Arcsine of 1/2, pattern: 1 2 / arcsin, output: =pi 6 /, tags: [value], explain: "sin(π/6) = 1/2, so arcsin(1/2) = π/6." }\n - { id: arcsin-1, name: Arcsine of 1, pattern: 1 arcsin, output: =pi 2 /, tags: [value], explain: "sin(π/2) = 1, so arcsin 1 = π/2." }\n - { id: arccos-0, name: Arccosine of 0, pattern: 0 arccos, output: =pi 2 /, tags: [value], explain: "cos(π/2) = 0, so arccos 0 = π/2." }\n - { id: arccos-half, name: Arccosine of 1/2, pattern: 1 2 / arccos, output: =pi 3 /, tags: [value], explain: "cos(π/3) = 1/2, so arccos(1/2) = π/3." }\n - { id: arccos-1, name: Arccosine of 1, pattern: 1 arccos, output: "0", tags: [value], explain: "cos 0 = 1, so arccos 1 = 0." }\n - { id: arccos-minus-1, name: Arccosine of -1, pattern: -1 arccos, output: =pi, tags: [value], explain: "cos π = -1, so arccos(-1) = π." }\n - { id: arctan-0, name: Arctangent of 0, pattern: 0 arctan, output: "0", tags: [value], explain: "tan 0 = 0, so arctan 0 = 0." }\n - { id: arctan-1, name: Arctangent of 1, pattern: 1 arctan, output: =pi 4 /, tags: [value], explain: "tan(π/4) = 1, so arctan 1 = π/4." }\n - { id: sinh-0, name: sinh of 0, pattern: 0 sinh, output: "0", tags: [value], explain: "sinh 0 = 0." }\n - { id: cosh-0, name: cosh of 0, pattern: 0 cosh, output: "1", tags: [value], explain: "cosh 0 = 1." }\n - { id: tanh-0, name: tanh of 0, pattern: 0 tanh, output: "0", tags: [value], explain: "tanh 0 = 0." }\n\n - { id: arctan-sqrt3, name: Arctangent of √3, pattern: 3 sqrt arctan, output: =pi 3 /, tags: [value], explain: "tan(π/3) = √3, so arctan √3 = π/3." }\n - { id: arctan-sqrt3-over-3, name: Arctangent of √3/3, pattern: 3 sqrt 3 / arctan, output: =pi 6 /, tags: [value], explain: "tan(π/6) = √3/3, so arctan(√3/3) = π/6." }\n\n # atan2(y, x): the angle of the point (x, y), in (-π, π]\n - id: atan2-right\n name: The angle of a point to the right\n pattern: y x atan2\n when:\n x: [isPositiveConstant]\n output: y x / arctan\n explain: "For x > 0, atan2(y, x) = arctan(y/x)."\n tags: [value]\n - id: atan2-left-up\n name: The angle of a point to the left\n pattern: y x atan2\n when:\n x: [isNegativeConstant]\n y: [isPositiveConstant]\n output: y x / arctan =pi +\n explain: "For x < 0 and y > 0, atan2(y, x) = arctan(y/x) + π."\n tags: [value]\n - id: atan2-left-down\n name: The angle of a point to the left\n pattern: y x atan2\n when:\n x: [isNegativeConstant]\n y: [isNegativeConstant]\n output: y x / arctan =pi -\n explain: "For x < 0 and y < 0, atan2(y, x) = arctan(y/x) - π."\n tags: [value]\n - { id: atan2-negative-axis, name: The angle of a point on the negative axis, pattern: 0 x atan2, when: { x: [isNegativeConstant] }, output: =pi, tags: [value], explain: "A point on the negative x-axis is at angle π." }\n - { id: atan2-up, name: Straight up, pattern: y 0 atan2, when: { y: [isPositiveConstant] }, output: =pi 2 /, tags: [value], explain: "A point straight up is at angle π/2." }\n - { id: atan2-down, name: Straight down, pattern: y 0 atan2, when: { y: [isNegativeConstant] }, output: =pi 2 / neg, tags: [value], explain: "A point straight down is at angle -π/2." }\n\n # the odd inverses take the sign out; arccos(-u) = π - arccos u\n - id: arcsin-odd\n name: Arcsine of a negative\n pattern: u arcsin\n when:\n u: [hasMinusSign]\n output: u neg arcsin neg\n explain: "arcsin(-x) = -arcsin x."\n tags: [symmetry]\n\n - id: arctan-odd\n name: Arctangent of a negative\n pattern: u arctan\n when:\n u: [hasMinusSign]\n output: u neg arctan neg\n explain: "arctan(-x) = -arctan x."\n tags: [symmetry]\n\n - id: arccos-negative\n name: Arccosine of a negative\n pattern: u arccos\n when:\n u: [hasMinusSign]\n output: =pi u neg arccos -\n explain: "arccos(-x) = π - arccos x."\n tags: [symmetry]\n\n # ---- trigonometry: identities --------------------------------------------\n - id: pythagorean\n name: sin² + cos² = 1\n pattern: u sin 2 ^ u cos 2 ^ +\n commutative: true\n output: "1"\n explain: "sin²{u} + cos²{u} = 1 for every angle."\n tags: [identity]\n\n - id: pythagorean-multiple\n name: sin² + cos² = 1\n pattern: a u sin 2 ^ * a u cos 2 ^ * +\n commutative: true\n output: a\n explain: "{a}·sin²{u} + {a}·cos²{u} = {a}(sin²{u} + cos²{u}) = {a}."\n tags: [identity]\n\n - id: one-minus-sin-squared\n name: 1 - sin² = cos²\n pattern: u sin 2 ^ neg 1 +\n output: u cos 2 ^\n explain: "1 - sin²{u} = cos²{u}."\n tags: [identity]\n\n - id: one-minus-cos-squared\n name: 1 - cos² = sin²\n pattern: u cos 2 ^ neg 1 +\n output: u sin 2 ^\n explain: "1 - cos²{u} = sin²{u}."\n tags: [identity]\n\n - id: sin-over-cos\n name: sin/cos is tan\n pattern: u sin u cos /\n output: u tan\n explain: "sin {u} / cos {u} = tan {u}."\n tags: [identity]\n\n - id: cos-over-sin\n name: cos/sin is cot\n pattern: u cos u sin /\n output: u cot\n explain: "cos {u} / sin {u} = cot {u}."\n tags: [identity]\n\n - id: sin-arcsin\n name: sin undoes arcsin\n pattern: u arcsin sin\n output: u\n explain: "sin(arcsin {u}) = {u}."\n tags: [inverse]\n\n - id: cos-arccos\n name: cos undoes arccos\n pattern: u arccos cos\n output: u\n explain: "cos(arccos {u}) = {u}."\n tags: [inverse]\n\n - id: tan-arctan\n name: tan undoes arctan\n pattern: u arctan tan\n output: u\n explain: "tan(arctan {u}) = {u}."\n tags: [inverse]\n\n - id: cosh-squared-minus-sinh-squared\n name: cosh² - sinh² = 1\n pattern: u cosh 2 ^ u sinh 2 ^ -\n output: "1"\n explain: "cosh²{u} - sinh²{u} = 1."\n tags: [identity]\n\n # ---- trigonometry: shifts by π/2 and π, written with an unknown angle ----------\n - { id: sin-plus-quarter, name: sin(u + π/2), pattern: u =pi 2 / + sin, commutative: true, output: u cos, tags: [symmetry], explain: "Shifting sine by a quarter turn gives cosine: sin({u} + π/2) = cos {u}." }\n - { id: cos-plus-quarter, name: cos(u + π/2), pattern: u =pi 2 / + cos, commutative: true, output: u sin neg, tags: [symmetry], explain: "cos({u} + π/2) = -sin {u}." }\n - { id: sin-minus-quarter, name: sin(u − π/2), pattern: u =pi 2 / - sin, output: u cos neg, tags: [symmetry], explain: "sin({u} - π/2) = -cos {u}." }\n - { id: cos-minus-quarter, name: cos(u − π/2), pattern: u =pi 2 / - cos, output: u sin, tags: [symmetry], explain: "cos({u} - π/2) = sin {u}." }\n - { id: sin-cofunction, name: sin(π/2 − u), pattern: u neg =pi 2 / + sin, commutative: true, output: u cos, tags: [symmetry], explain: "Sine of the complement is cosine: sin(π/2 - {u}) = cos {u}." }\n - { id: cos-cofunction, name: cos(π/2 − u), pattern: u neg =pi 2 / + cos, commutative: true, output: u sin, tags: [symmetry], explain: "Cosine of the complement is sine: cos(π/2 - {u}) = sin {u}." }\n - { id: tan-cofunction, name: tan(π/2 − u), pattern: u neg =pi 2 / + tan, commutative: true, output: u cot, tags: [symmetry], explain: "tan(π/2 - {u}) = cot {u}." }\n - { id: sin-supplement, name: sin(π − u), pattern: u neg =pi + sin, commutative: true, output: u sin, tags: [symmetry], explain: "sin(π - {u}) = sin {u}." }\n - { id: cos-supplement, name: cos(π − u), pattern: u neg =pi + cos, commutative: true, output: u cos neg, tags: [symmetry], explain: "cos(π - {u}) = -cos {u}." }\n - { id: sin-plus-half, name: sin(u + π), pattern: u =pi + sin, commutative: true, output: u sin neg, tags: [symmetry], explain: "Half a turn changes the sign: sin({u} + π) = -sin {u}." }\n - { id: cos-plus-half, name: cos(u + π), pattern: u =pi + cos, commutative: true, output: u cos neg, tags: [symmetry], explain: "Half a turn changes the sign: cos({u} + π) = -cos {u}." }\n - { id: tan-plus-half, name: tan(u + π), pattern: u =pi + tan, commutative: true, output: u tan, tags: [symmetry], explain: "Tangent repeats every π: tan({u} + π) = tan {u}." }\n - { id: sin-minus-half, name: sin(u − π), pattern: u =pi - sin, output: u sin neg, tags: [symmetry], explain: "sin({u} - π) = -sin {u}." }\n - { id: cos-minus-half, name: cos(u − π), pattern: u =pi - cos, output: u cos neg, tags: [symmetry], explain: "cos({u} - π) = -cos {u}." }\n\n # ---- trigonometry: more exact values (15°, 75°, 22.5°, 67.5°) -------------------\n - { id: sin-pi-12, name: Sine of π/12, pattern: =pi 12 / sin, output: 6 sqrt 2 sqrt - 4 /, tags: [value], explain: "sin(π/12) = sin(π/3 - π/4) = (√6 - √2)/4." }\n - { id: cos-pi-12, name: Cosine of π/12, pattern: =pi 12 / cos, output: 6 sqrt 2 sqrt + 4 /, tags: [value], explain: "cos(π/12) = cos(π/3 - π/4) = (√6 + √2)/4." }\n - { id: tan-pi-12, name: Tangent of π/12, pattern: =pi 12 / tan, output: 2 3 sqrt -, tags: [value], explain: "tan(π/12) = 2 - √3." }\n - { id: sin-5pi-12, name: Sine of 5π/12, pattern: 5 =pi * 12 / sin, output: 6 sqrt 2 sqrt + 4 /, tags: [value], explain: "sin(5π/12) = sin(π/4 + π/6) = (√6 + √2)/4." }\n - { id: cos-5pi-12, name: Cosine of 5π/12, pattern: 5 =pi * 12 / cos, output: 6 sqrt 2 sqrt - 4 /, tags: [value], explain: "cos(5π/12) = cos(π/4 + π/6) = (√6 - √2)/4." }\n - { id: tan-5pi-12, name: Tangent of 5π/12, pattern: 5 =pi * 12 / tan, output: 2 3 sqrt +, tags: [value], explain: "tan(5π/12) = 2 + √3." }\n - { id: sin-pi-8, name: Sine of π/8, pattern: =pi 8 / sin, output: 2 2 sqrt - sqrt 2 /, tags: [value], explain: "By the half-angle formula, sin(π/8) = √(2 - √2)/2." }\n - { id: cos-pi-8, name: Cosine of π/8, pattern: =pi 8 / cos, output: 2 2 sqrt + sqrt 2 /, tags: [value], explain: "By the half-angle formula, cos(π/8) = √(2 + √2)/2." }\n - { id: tan-pi-8, name: Tangent of π/8, pattern: =pi 8 / tan, output: 2 sqrt 1 -, tags: [value], explain: "tan(π/8) = √2 - 1." }\n - { id: sin-3pi-8, name: Sine of 3π/8, pattern: 3 =pi * 8 / sin, output: 2 2 sqrt + sqrt 2 /, tags: [value], explain: "sin(3π/8) = cos(π/8) = √(2 + √2)/2." }\n - { id: cos-3pi-8, name: Cosine of 3π/8, pattern: 3 =pi * 8 / cos, output: 2 2 sqrt - sqrt 2 /, tags: [value], explain: "cos(3π/8) = sin(π/8) = √(2 - √2)/2." }\n - { id: tan-3pi-8, name: Tangent of 3π/8, pattern: 3 =pi * 8 / tan, output: 2 sqrt 1 +, tags: [value], explain: "tan(3π/8) = √2 + 1." }\n\n # ---- trigonometry: a function of an inverse function (a right triangle) -----------\n - { id: sin-arccos, name: sin(arccos u), pattern: u arccos sin, output: u 2 ^ neg 1 + sqrt, tags: [inverse], explain: "In a right triangle with cos θ = {u}, the other side is √(1 - {u}²): sin(arccos {u}) = √(1 - {u}²)." }\n - { id: cos-arcsin, name: cos(arcsin u), pattern: u arcsin cos, output: u 2 ^ neg 1 + sqrt, tags: [inverse], explain: "In a right triangle with sin θ = {u}, cos θ = √(1 - {u}²)." }\n - { id: tan-arcsin, name: tan(arcsin u), pattern: u arcsin tan, output: u u 2 ^ neg 1 + sqrt /, tags: [inverse], explain: "tan(arcsin {u}) = {u}/√(1 - {u}²)." }\n - { id: tan-arccos, name: tan(arccos u), pattern: u arccos tan, output: u 2 ^ neg 1 + sqrt u /, tags: [inverse], explain: "tan(arccos {u}) = √(1 - {u}²)/{u}." }\n - { id: sin-arctan, name: sin(arctan u), pattern: u arctan sin, output: u u 2 ^ 1 + sqrt /, tags: [inverse], explain: "In a right triangle with tan θ = {u}, the long side is √(1 + {u}²): sin(arctan {u}) = {u}/√(1 + {u}²)." }\n - { id: cos-arctan, name: cos(arctan u), pattern: u arctan cos, output: 1 u 2 ^ 1 + sqrt /, tags: [inverse], explain: "cos(arctan {u}) = 1/√(1 + {u}²)." }\n - { id: sec-arctan, name: sec(arctan u), pattern: u arctan sec, output: u 2 ^ 1 + sqrt, tags: [inverse], explain: "sec(arctan {u}) = √(1 + {u}²)." }\n - { id: cos-arcsec, name: cos(arcsec u), pattern: u arcsec cos, output: 1 u /, tags: [inverse], explain: "arcsec {u} is the angle whose cosine is 1/{u}." }\n - { id: sin-arccsc, name: sin(arccsc u), pattern: u arccsc sin, output: 1 u /, tags: [inverse], explain: "arccsc {u} is the angle whose sine is 1/{u}." }\n - { id: tan-arccot, name: tan(arccot u), pattern: u arccot tan, output: 1 u /, tags: [inverse], explain: "arccot {u} is the angle whose tangent is 1/{u}." }\n\n # ---- trigonometry: the angle-sum formulas, read backward -------------------------\n - { id: sin-sum, name: sin(u + v), pattern: u sin v cos * u cos v sin * +, commutative: true, output: u v + sin, tags: [identity], explain: "sin {u} cos {v} + cos {u} sin {v} = sin({u} + {v})." }\n - { id: sin-difference, name: sin(u − v), pattern: u sin v cos * u cos v sin * -, commutative: true, output: u v - sin, tags: [identity], explain: "sin {u} cos {v} - cos {u} sin {v} = sin({u} - {v})." }\n - { id: sin-difference-led-by-minus, name: sin(u − v), pattern: u cos v sin * neg u sin v cos * +, commutative: true, output: u v - sin, tags: [identity], explain: "sin {u} cos {v} - cos {u} sin {v} = sin({u} - {v})." }\n - { id: cos-sum, name: cos(u + v), pattern: u cos v cos * u sin v sin * -, commutative: true, output: u v + cos, tags: [identity], explain: "cos {u} cos {v} - sin {u} sin {v} = cos({u} + {v})." }\n - { id: cos-difference, name: cos(u − v), pattern: u cos v cos * u sin v sin * +, commutative: true, output: u v - cos, tags: [identity], explain: "cos {u} cos {v} + sin {u} sin {v} = cos({u} - {v})." }\n\n # ---- logs: opt-in rewrites (run with cas.rewrite(x, \'expand-log\') or \'combine-log\') ----\n - id: ln-product\n name: Log of a product\n mode: expand-log\n pattern: a b * ln\n output: a ln b ln +\n explain: "ln({a}·{b}) = ln {a} + ln {b} (for positive {a}, {b})."\n tags: [log]\n\n - id: ln-quotient\n name: Log of a quotient\n mode: expand-log\n pattern: a b / ln\n output: a ln b ln -\n explain: "ln({a}/{b}) = ln {a} - ln {b} (for positive {a}, {b})."\n tags: [log]\n\n - id: ln-power\n name: Log of a power\n mode: expand-log\n pattern: a n ^ ln\n output: n a ln *\n explain: "ln({a}^{n}) = {n}·ln {a} (for positive {a})."\n tags: [log]\n\n - id: ln-root\n name: Log of a square root\n mode: expand-log\n pattern: a sqrt ln\n output: a ln 2 /\n explain: "ln √{a} = ½ ln {a}."\n tags: [log]\n\n - id: ln-sum-combine\n name: Sum of logs\n mode: combine-log\n pattern: a ln b ln +\n commutative: true\n output: a b * ln\n explain: "ln {a} + ln {b} = ln({a}·{b})."\n tags: [log]\n\n - id: ln-difference-combine\n name: Difference of logs\n mode: combine-log\n pattern: a ln b ln -\n output: a b / ln\n explain: "ln {a} - ln {b} = ln({a}/{b})."\n tags: [log]\n\n - id: ln-multiple-combine\n name: A multiple of a log\n mode: combine-log\n pattern: n a ln *\n when:\n n: [isRational]\n output: a n ^ ln\n explain: "{n}·ln {a} = ln({a}^{n})."\n tags: [log]\n','name: Solving by undoing\n\n# mode: isolate. Each rule undoes the outermost function on the side with the\n# unknown: ln u = r → u = e^r. The predicates hasVariable and freeOfVariable mean\n# "mentions / doesn\'t mention the unknown being solved for".\n#\n# The CAS does the rest itself: it moves terms without the unknown to the other\n# side, divides by a coefficient, and when the unknown appears in several places\n# it uses the polynomial methods (factoring, the quadratic formula) or splits a\n# product equal to 0. Every answer is checked in the original equation, so a\n# rule may give extra candidates (squaring both sides does): the wrong ones are\n# dropped, with a step saying so.\n#\n# An output can give several answers: `pm` (±) splits into two, and so does\n# `|` (or): "u r arcsin = u =pi r arcsin - = |".\n\nrules:\n - id: iso-swap\n name: Unknown on the left\n mode: isolate\n pattern: l r =\n when:\n l: [freeOfVariable]\n r: [hasVariable]\n output: r l =\n priority: 20\n explain: "Swap the sides so the unknown is on the left."\n tags: [tidy]\n\n - id: iso-ln\n name: Undo the log\n mode: isolate\n pattern: u ln r =\n when:\n u: [hasVariable]\n output: u =e r ^ =\n explain: "Raise e to each side: e^(ln {u}) = {u}."\n tags: [inverse]\n\n - id: iso-log\n name: Undo the log\n mode: isolate\n pattern: b u log r =\n when:\n u: [hasVariable]\n b: [freeOfVariable]\n output: u b r ^ =\n explain: "Raise {b} to each side: {b}^(log base {b} of {u}) = {u}."\n tags: [inverse]\n\n - id: iso-exp\n name: Undo e to a power\n mode: isolate\n pattern: =e u ^ r =\n when:\n u: [hasVariable]\n output: u r ln =\n explain: "Take ln of each side: ln(e^{u}) = {u}."\n tags: [inverse]\n\n - id: iso-exponential\n name: Undo a power of a number\n mode: isolate\n pattern: b u ^ r =\n when:\n u: [hasVariable]\n b: [freeOfVariable]\n output: u b r log =\n explain: "Take the log to base {b} of each side."\n tags: [inverse]\n\n - id: iso-square\n name: Undo the square\n mode: isolate\n pattern: u 2 ^ r =\n when:\n u: [hasVariable]\n output: u r sqrt pm =\n priority: 1\n explain: "Take the square root of each side; {u} can be positive or negative."\n tags: [inverse]\n\n - id: iso-even-power\n name: Undo an even power\n mode: isolate\n pattern: u n ^ r =\n when:\n u: [hasVariable]\n n: [isEvenWhole]\n output: u r 1 n / ^ pm =\n explain: "Take the root of each side (the {n}th root); {u} can be positive or negative."\n tags: [inverse]\n\n - id: iso-odd-power\n name: Undo an odd power\n mode: isolate\n pattern: u n ^ r =\n when:\n u: [hasVariable]\n n: [isOddWhole]\n output: u r 1 n / ^ =\n explain: "Take the root of each side (the {n}th root)."\n tags: [inverse]\n\n - id: iso-fractional-power\n name: Undo a power\n mode: isolate\n pattern: u n ^ r =\n when:\n u: [hasVariable]\n n: [isRational]\n output: u r 1 n / ^ =\n priority: -1\n explain: "Raise each side to the power 1/{n}."\n tags: [inverse]\n\n - id: iso-sqrt\n name: Undo the square root\n mode: isolate\n pattern: u sqrt r =\n when:\n u: [hasVariable]\n output: u r 2 ^ =\n explain: "Square each side (this can add answers, so each one is checked at the end)."\n tags: [inverse]\n\n - id: iso-root\n name: Undo the root\n mode: isolate\n pattern: n u root r =\n when:\n u: [hasVariable]\n n: [freeOfVariable]\n output: u r n ^ =\n explain: "Raise each side to the power {n}."\n tags: [inverse]\n\n - id: iso-reciprocal\n name: Undo the fraction\n mode: isolate\n pattern: c u / r =\n when:\n u: [hasVariable]\n c: [freeOfVariable]\n output: u c r / =\n explain: "{c}/{u} = {r}, so {u} = {c}/{r}."\n tags: [inverse]\n\n - id: iso-abs\n name: Undo the absolute value\n mode: isolate\n pattern: u abs r =\n when:\n u: [hasVariable]\n output: u r pm =\n explain: "|{u}| = {r} means {u} is {r} or -{r}."\n tags: [inverse]\n\n - id: iso-sin\n name: Undo the sine\n mode: isolate\n pattern: u sin r =\n when:\n u: [hasVariable]\n output: u r arcsin = u =pi r arcsin - = |\n explain: "Two angles in a turn have sine {r}: arcsin {r} and π - arcsin {r} (add any whole number of turns, 2πk, for the rest)."\n tags: [inverse, trig]\n\n - id: iso-cos\n name: Undo the cosine\n mode: isolate\n pattern: u cos r =\n when:\n u: [hasVariable]\n output: u r arccos pm =\n explain: "Two angles in a turn have cosine {r}: ±arccos {r} (add 2πk for the rest)."\n tags: [inverse, trig]\n\n - id: iso-tan\n name: Undo the tangent\n mode: isolate\n pattern: u tan r =\n when:\n u: [hasVariable]\n output: u r arctan =\n explain: "Take arctan of each side (add πk for the rest)."\n tags: [inverse, trig]\n\n - { id: iso-arcsin, name: Undo arcsin, mode: isolate, pattern: u arcsin r =, when: { u: [hasVariable] }, output: u r sin =, tags: [inverse], explain: "Take sin of each side." }\n - { id: iso-arccos, name: Undo arccos, mode: isolate, pattern: u arccos r =, when: { u: [hasVariable] }, output: u r cos =, tags: [inverse], explain: "Take cos of each side." }\n - { id: iso-arctan, name: Undo arctan, mode: isolate, pattern: u arctan r =, when: { u: [hasVariable] }, output: u r tan =, tags: [inverse], explain: "Take tan of each side." }\n - { id: iso-sinh, name: Undo sinh, mode: isolate, pattern: u sinh r =, when: { u: [hasVariable] }, output: u r arcsinh =, tags: [inverse], explain: "Take arcsinh of each side." }\n - { id: iso-tanh, name: Undo tanh, mode: isolate, pattern: u tanh r =, when: { u: [hasVariable] }, output: u r arctanh =, tags: [inverse], explain: "Take arctanh of each side." }\n - { id: iso-cosh, name: Undo cosh, mode: isolate, pattern: u cosh r =, when: { u: [hasVariable] }, output: u r arccosh pm =, tags: [inverse], explain: "Two numbers have cosh {r}: ±arccosh {r}." }\n - { id: iso-arcsinh, name: Undo arcsinh, mode: isolate, pattern: u arcsinh r =, when: { u: [hasVariable] }, output: u r sinh =, tags: [inverse], explain: "Take sinh of each side." }\n - { id: iso-arccosh, name: Undo arccosh, mode: isolate, pattern: u arccosh r =, when: { u: [hasVariable] }, output: u r cosh =, tags: [inverse], explain: "Take cosh of each side." }\n - { id: iso-arctanh, name: Undo arctanh, mode: isolate, pattern: u arctanh r =, when: { u: [hasVariable] }, output: u r tanh =, tags: [inverse], explain: "Take tanh of each side." }\n'],Ui=['name: Complex numbers\n\n# Loaded only by createCAS({ complex: true }), where i is the imaginary unit.\n# The arithmetic (i² = -1, √-4 = 2i, (2 + 3i)(1 - i) = 5 + i, 1/(1 + i) = (1 - i)/2)\n# and Re, Im, conj, arg, |z| are the normal form\'s (src/cas/form.js); unknowns\n# count as real, so Re(x + 3i) = x. Write a complex unknown as a + bi.\n\noperators:\n - { symbol: re, arity: 1, label: real part }\n - { symbol: im, arity: 1, label: imaginary part }\n - { symbol: conj, arity: 1, label: complex conjugate }\n - { symbol: arg, arity: 1, label: argument }\n\nrules:\n - id: euler\n name: Euler\'s formula\n pattern: =e u ^\n when:\n u: [hasImaginaryPart, isConstant]\n output: =e u re ^ u im cos =i u im sin * + *\n explain: "e^(a + bi) = e^a (cos b + i sin b)."\n tags: [complex]\n\n - id: ln-negative\n name: Log of a negative number\n pattern: u ln\n when:\n u: [isNegativeConstant]\n output: u neg ln =i =pi * +\n explain: "{u} = |{u}|·e^(iπ), so ln {u} = ln |{u}| + iπ (the principal value)."\n tags: [complex]\n\n - id: ln-complex\n name: Log of a complex number\n pattern: u ln\n when:\n u: [hasImaginaryPart, isConstant]\n output: u abs ln u arg =i * +\n explain: "ln z = ln |z| + i arg z (the principal value)."\n tags: [complex]\n\n - id: i-to-the-i\n name: i to the power i\n pattern: =i =i ^\n output: =e =pi 2 / neg ^\n explain: "i = e^(iπ/2), so i^i = e^(i·iπ/2) = e^(-π/2) (the principal value)."\n tags: [complex]\n'],Vi=new Set(["<",">","≤","≥"]),Li=new Set(["sin","cos","tan","sec","csc","cot"]),Wi=new Set(["arcsin","arccos","arctan","arcsec","arccsc","arccot"]),_i={normal:"Work out the numbers and collect like terms.","simplify.cancel":"Cancel the factors the top and bottom share.","simplify.expand":"Multiplying out gives something shorter.","simplify.factor":"Factoring gives something shorter.",expand:"Multiply out the brackets.",factor:"Write it as a product of factors.","factor.common":"Take out the common factor {common}.","factor.polynomial":"Factor what is left: {roots}.",together:"Write it as one fraction over a common denominator.",cancel:"Cancel the factors the top and bottom share: {canceled}.","solve.move":"Keep the terms with {v} on the left and move the others to the right.","solve.divide":"Divide both sides by {by}.","solve.multiply":"Multiply both sides by {by}.","solve.one-side":"Move everything to one side, so the equation reads … = 0.","solve.factor":"Factor the left side.","solve.zero-product":"A product is 0 exactly when one of its factors is 0.","solve.split":"There are two cases; solve each.","solve.quadratic":"The quadratic formula with a = {a}, b = {b}, c = {c}: {v} = (-b ± √(b² - 4ac)) / 2a, and b² - 4ac = {D}.","solve.no-real":"b² - 4ac = {D} is negative, so there are no real solutions.","solve.quadratic-complex":"The quadratic formula with a = {a}, b = {b}, c = {c}: {v} = (-b ± √(b² - 4ac)) / 2a. b² - 4ac = {D} is negative, so its square root is imaginary: √({D}) = {root}.","solve.roots":"{v}^{n} = {r} has {n} solutions, spaced evenly round a circle: |{r}|^(1/{n})·(cos θ + i sin θ), with θ = (arg {r} + 2πk)/{n} for k = 0 … {last}.","solve.clear-denominator":"Multiply both sides by {den} (an answer that makes it 0 is not allowed).","solve.substitute":"Write {u} for {kernel}: this is a polynomial in {u}.","solve.reject":"{value} is not a solution: {reason}.","solve.always":"This is true for every {v}.","solve.never":"This is never true, so there is no solution.","simplify.trig":"Write it with sin and cos, use sin² + cos² = 1 and the double-angle formulas, and cancel.","limit.substitute":"{f} is continuous at {v} = {a}: put {a} in.","limit.cancel":"{f} is 0/0 at {v} = {a}: cancel the common factor first.","limit.lhopital":"{f} is {form} as {v} → {a}: by L'Hôpital's rule, take the limit of the top's derivative over the bottom's.","limit.leading":"As {v} → {a}, the highest powers decide: {f} behaves like {lead}.","limit.zero-times-infinity":"{f} is 0·∞: write it as a quotient.","limit.combine":"{f} is ∞ − ∞: write it as one fraction.","limit.squeeze":"{bounded} stays between two bounds, and what it is multiplied by goes to 0: so does the product (the squeeze theorem).","limit.divide-power":"Divide the top and the bottom by {power}.","limit.conjugate":"{f} is ∞ − ∞ with a root: multiply top and bottom by the conjugate.","limit.exp-log":"{f} is {form}: write it as e to the power (exponent · ln base), and find the limit of the exponent.","limit.one-sided":"From the left {f} goes to {left}, from the right to {right}: the limit does not exist.","solve.sign-chart":"Where each side minus the other is 0, or has no value: {points}. It keeps one sign between them, so test one {v} in each interval, and each point.","solve.unsolved":"There is no exact method here for solving for {v}; try { approximate: true }.","solve.numeric":"Found {count} solution(s) numerically.","system.eliminate":"Use one equation to remove {v} from the others.","integrate.expand":"Multiply out, then integrate term by term.","integrate.substitute":"Let {u} = {inside}, so d{u} = {a} d{v}.","integrate.back":"Put {inside} back for {u}.","integrate.parts":"By parts with u = {u} and dv = {dv} d{v}: ∫ u dv = u·v - ∫ v du, where v = {V} and du = {du} d{v}.","integrate.constant":"The number {c} comes out of the integral.","integrate.divide":"The top has at least the degree of the bottom: divide first.","integrate.partial-fractions":"Split the fraction into simple fractions, one for each factor below.","integrate.evaluate":"Evaluate {F} at {b} and at {a}, and subtract.","integrate.improper":"An improper integral: at an infinite end, the limit of {F} as {v} goes there; then subtract.","integrate.u-substitution":"Let {u} = {inside}, so d{u} = {du} d{v}: the integral is in {u} alone.","integrate.complete-square":"Partial fractions, and complete the square in {Q}: the top that is a multiple of its derivative gives a log, the rest an arctangent.","integrate.parts-twice":"By parts twice: the integral of {e}·{t} comes back, so solve for it.","integrate.product-to-sum":"Write the product of sines and cosines as a sum.","integrate.odd-power":"Keep one {f} and write the rest with {other} (sin² + cos² = 1): then {other} is the substitution.","integrate.reduction":"The reduction formula for {f} to the power {n}.","integrate.trig-substitution":"Let {x} = {a}·sin θ: the root becomes {a}·cos θ.",substitute:"Put in the values."},Hi=["normal","rewrite","simplify","expand","factor","cancel","diff","differentiate","integrate","solve","solveSystem","substitute","approximate","equivalent","limit"];class Qi{constructor(e,n,t,s,i){this.set=e,this.messages=n,this.format=t,this.read=s,this.complex=i;for(const e of Hi){const n=Qi.prototype[e];this[e]=(...e)=>pe(i,()=>n.apply(this,e))}}node(e){return this.atPoints(this.read_(e))}read_(e){if(e&&"object"==typeof e&&!Array.isArray(e)&&e.type)return e;if(Array.isArray(e))return H(e);if("string"!=typeof e)throw new ee("expected an expression");if(this.read){const n=this.read(e);return Array.isArray(n)?H(n):"string"==typeof n?_(n):n}return _(e)}atPoints(e){if(!e||!W(e)||!e.s.includes("= der"))return e;const n=e.args.map(e=>this.atPoints(e)),[t,s]=n;if("der"===e.op&&W(s)&&"="===s.op&&"sym"===s.args[0].type){const e=s.args[0].token;return this.substitute(this.diff(t,e).result,{[e]:s.args[1].s}).result}return V(e.op,n)}step(e,n,t,s,i,r={}){return function(e,n,t,s,i,r,o,a,u=[]){const l=(r??"").replace(/\{(\w+)\}/g,(e,n)=>{const t=o?.[n];return void 0===t?e:"string"==typeof t?t:a(t)});return{id:e,name:n,tags:t,from:s.s,to:i.s,path:u,before:s.s,after:i.s,explanation:l}}(e,n,t,s,i,this.messages[e]??"",r,this.format)}result(e,n,t,s={}){let i=e;if(t.approximate&&i){i=At(i,{digits:"number"==typeof t.approximate?t.approximate:15})}return{result:i,text:i?this.format(i):"",steps:_t(n,Wt(t.steps)),...s}}variable(e,n){if(n&&!/^\\?[A-Za-z\u0370-\u03FF][A-Za-z0-9_\u0370-\u03FF′]*$/.test(n))throw new ee(`"${n}" is not a variable name; for a derivative at a point write der(f, x = a)`);if(n)return n;const t=[...sn(e)];return 1===t.length?t[0]:t.includes("x")?"x":t[0]??"x"}tidyStep(e,n){return e.s===n.s?[]:[this.step("normal","Work out and collect",["tidy","arithmetic"],e,n)]}normal(e){return Ke(this.node(e))}rewrite(e,n,t={}){const s=this.node(e),i=this.set.view(n);if(!i.size)throw new ee(`no rules in mode "${n}" (modes: ${this.set.modes().join(", ")})`);const r=Ut(s,i,{format:this.format,order:t.order,variable:t.variable});return this.result(r.node,[...this.tidyStep(s,Ke(s)),...r.steps],t)}simplify(e,n={}){const t=this.node(e),s=[...this.tidyStep(t,Ke(t))],i=Ut(t,this.set.view("simplify"),{format:this.format});s.push(...i.steps);let r=i.node,o=null;const a=Je(r),u=[],l=0===sn(r).size,c=l?null:gs(a);c&&u.push({node:hs(c),id:"simplify.cancel",name:"Cancel"});const f=Ut(en(Jt(a)),this.set.view("simplify"),{format:this.format});u.push({node:f.node,id:"simplify.expand",name:"Multiply out"}),"add"!==a.k||l||u.push({node:hs(as(a)),id:"simplify.factor",name:"Factor"});const p=e=>G(e,"pre").some(({node:e})=>W(e)&&Li.has(e.op)&&G(e.args[0],"pre").some(({node:e})=>W(e)&&Wi.has(e.op)));for(const e of ui(this,r))u.push({node:e,id:"simplify.trig",name:"Trigonometric identities",prefer:p(r)&&!p(e)});let h=!1;for(const e of u)h&&"simplify.trig"===e.id&&!e.prefer||(e.prefer&&(h=!0),(J(e.node)<J(r)||e.prefer)&&(o=this.step(e.id,e.name,["shorter"],r,e.node),r=e.node));return o&&s.push(o),this.result(r,s,n)}expand(e,n={}){const t=this.node(e),s=en(Jt(Je(t)));return this.result(s,t.s===s.s?[]:[this.step("expand","Multiply out",["expand"],t,s)],n)}factor(e,n={}){const t=this.node(e),s=as(Je(t)),i=hs(s),r=[],o=s.notes.find(e=>"factor.common"===e.id);return i.s!==Ke(t).s&&r.push(this.step(o?"factor.common":"factor","Factor",["factor"],t,i,o?{common:en(o.values.common)}:{})),this.result(i,r,n)}cancel(e,n={}){const t=this.node(e),s=Je(t),i=gs(s);if(!i)return this.result(Ke(t),this.tidyStep(t,Ke(t)),n);const r=hs(i),o=ms(s),a=V("/",[en(o.num),en(o.den)]),u=[];return"/"===t.op&&a.s===Ke(t).s||u.push(this.step("together","One fraction",["together"],t,a)),r.s!==a.s&&u.push(this.step("cancel","Cancel",["cancel"],a,r,{canceled:i.canceled.length?i.canceled.map(e=>this.format(en(e))).join(", "):"numbers"})),this.result(r,u,n)}diff(e,n,t={}){const s=this.node(e),i=this.variable(s,n);let r=s;const o=[];for(let e=0;e<(t.order??1);e++){const e=Ut(V("der",[r,D(i)]),this.set.view("differentiate"),{format:this.format,order:"pre"}),n=Ut(e.node,this.set.view("simplify"),{format:this.format});o.push(...e.steps,...n.steps),r=n.node}return this.result(r,o,t,{variable:i})}differentiate(e,n){const t=Ut(V("der",[e,D(n)]),this.set.view("differentiate"),{format:this.format,order:"pre"});return Ut(t.node,this.set.view("simplify"),{format:this.format}).node}integrate(e,n,t={}){let s=this.node(e);const i=e=>void 0===e?null:this.node("number"==typeof e?String(e):e);let r=i(t.from),o=i(t.to);if(W(s)&&"int"===s.op){const[e,t,i,a]=s.args;n=t.token,i&&a&&(r=i,o=a),s=e}const a=this.variable(s,n),u=wi(this,s,a),l=Ut(u.node,this.set.view("simplify"),{format:this.format}),c=[...u.steps,...l.steps];if(r&&o){const e=Ei(this,l.node,a,r,o,s);c.push(e.step);const n=Ut(e.value,this.set.view("simplify"),{format:this.format});return c.push(...n.steps),this.result(n.node,c,t,{antiderivative:l.node,variable:a})}let f=l.node;return t.constant&&(f=V("+",[f,D(String(t.constant))])),this.result(f,c,t,{variable:a})}solve(e,n,t={}){const s=this.node(e),i=this.variable(s,n);if(W(s)&&Vi.has(s.op))return this.inequality(s,i,t);const r=ys(this,s,i,t);let o=r.solutions;if(t.approximate){const e="number"==typeof t.approximate?t.approximate:15;o=o.map(n=>At(n,{digits:e}))}const a=o.map(e=>V("=",[D(i),e])),u=a.length?a.reduce((e,n)=>e?V("|",[e,n]):n,null):null;return{solutions:o,result:u,variable:i,text:r.always?`true for every ${i}`:u?this.format(u):r.unsolved.length?`no exact solution found for ${i}`:"no solution",unsolved:r.unsolved.filter(e=>!e.always),always:r.always,steps:_t(r.steps,Wt(t.steps))}}inequality(e,n,t){const s=Ds(this,e,n),i={solutions:[],variable:n,unsolved:[],always:!1,steps:_t(s.steps,Wt(t.steps))};if(!s.pieces)return{...i,pieces:null,intervals:"",result:null,unsolved:[e],text:`no exact solution found for ${n}`};const r=D(n),o=1===s.pieces.length&&!s.pieces[0].lo&&!s.pieces[0].hi,a=s.pieces.map(({lo:e,hi:n,loClosed:t,hiClosed:s})=>e&&n&&e.s===n.s?V("=",[r,e]):e||n?e?n?V(s?"≤":"<",[V(t?"≤":"<",[e,r]),n]):V(t?"≥":">",[r,e]):V(s?"≤":"<",[r,n]):null).filter(Boolean).reduce((e,n)=>e?V("|",[e,n]):n,null),u=s.pieces.length?s.pieces.map(({lo:e,hi:n,loClosed:t,hiClosed:s})=>e&&n&&e.s===n.s?`{${this.format(e)}}`:`${t?"[":"("}${e?this.format(e):"-∞"}, ${n?this.format(n):"∞"}${s?"]":")"}`).join(" ∪ "):"∅",l=o?`true for every ${n}`:a?this.format(a):"no solution";return{...i,pieces:s.pieces,intervals:u,result:a,always:o,text:l}}limit(e,n,t,s={}){null==t||"object"!=typeof t||Array.isArray(t)||t.type||(s=t,t=void 0);const i=this.node(e),r=ii(i);if(!r&&G(i,"pre").some(({node:e})=>ii(e))){let e=i;for(const{node:n,path:t}of G(i,"post").filter(({node:e})=>ii(e)).reverse()){const s=this.limit(n,void 0,void 0,{steps:!1});if(!s.exists)return s;if(s.infinite)throw new ee("a limit inside an expression that is infinite is not worked out here");e=X(e,t,s.result)}return{...this.simplify(e,s),exists:!0,infinite:!1}}const o=r?r.f:i,a=r?r.v:this.variable(i,n),u=r?r.to:"number"==typeof t?P(String(t)):this.node(t??"0"),l="right"===s.side||"+"===s.side?1:"left"===s.side||"-"===s.side?-1:r?r.side:0;try{const{value:e,steps:n}=Xs(this,o,a,ri(u),l);return{...this.result((c=e,c.inf?c.inf>0?Ws:D("-∞"):c.fin),n,s),exists:!0,infinite:Boolean(e.inf)}}catch(e){if(!(e instanceof Rs))throw e;return{result:null,text:"does not exist",exists:!1,reason:e.message,steps:[]}}var c}solveSystem(e,n,t={}){const s=e.map(e=>this.node(e)),i=n??[...new Set(s.flatMap(e=>[...sn(e)]))].sort(),r=function(e,n,t){const s=[],i=n.map(n=>{const s=ws(n)?Ie([Je(n.args[0]),Ve(Je(n.args[1]))]):Je(n),i=t.map(n=>{const t=Yt(s,n);if(!t||Math.max(0,...t.keys())>1)throw new ee(`not linear in ${n}`);const i=t.get(1)??me(re.ZERO);if(!we(i))throw new ee(`the coefficient of ${n} must be a number (it is ${e.format(en(i))})`);return i.q});let r=s;for(let e=0;e<t.length;e++)r=Ie([r,Te([me(i[e].neg()),Je(D(t[e]))])]);for(const e of t)if(Gt(r,e))throw new ee(`not linear in ${e}`);return{coeffs:i,rhs:Ve(r)}}),r=()=>i.map(e=>vs(en(Ie(e.coeffs.map((e,n)=>Te([me(e),Je(D(t[n]))])))),en(e.rhs))).reduce((e,n)=>e?V("&",[e,n]):n,null);let o=0;const a=[];for(let n=0;n<t.length&&o<i.length;n++){const u=i.findIndex((e,t)=>t>=o&&!e.coeffs[n].isZero);if(u<0)continue;[i[o],i[u]]=[i[u],i[o]];const l=r(),c=i[o],f=c.coeffs[n];c.coeffs=c.coeffs.map(e=>e.div(f)),c.rhs=Te([me(f.inv()),c.rhs]);for(let e=0;e<i.length;e++){if(e===o||i[e].coeffs[n].isZero)continue;const t=i[e].coeffs[n];i[e].coeffs=i[e].coeffs.map((e,n)=>e.sub(t.mul(c.coeffs[n]))),i[e].rhs=Ie([i[e].rhs,Te([me(t.neg()),c.rhs])])}s.push(e.step("system.eliminate","Eliminate",["eliminate"],l,r(),{v:D(t[n])})),a.push(n),o++}for(const e of i.slice(o))if(!we(e.rhs)||!e.rhs.q.isZero)return{solution:null,steps:s,status:"none"};if(a.length<t.length)return{solution:null,steps:s,status:"many"};const u=new Map;return a.forEach((e,n)=>u.set(t[e],en(i[n].rhs))),{solution:u,steps:s,status:"one"}}(this,s,i),o=r.solution?Object.fromEntries([...r.solution].map(([e,n])=>[e,n])):null,a="one"===r.status?i.map(e=>`${e} = ${this.format(o[e])}`).join(", "):"none"===r.status?"no solution":"infinitely many solutions";return{solution:o,status:r.status,text:a,steps:_t(r.steps,Wt(t.steps))}}substitute(e,n,t={}){const s=this.node(e);let i=s;for(const[e,t]of Object.entries(n))i=$s(i,e,"number"==typeof t?this.node(String(t)):this.node(t));const r=this.simplify(i,t),o=[this.step("substitute","Substitute",["substitute"],s,i)];return{...r,steps:[..._t(o,Wt(t.steps)),...r.steps]}}defined(e){const n=this.set.view("define");return n.size?Ut(e,n,{format:this.format}).node:e}approximate(e,n={}){const t=this.defined(this.node(e));if(sn(t).size&&!n.scope){const e=At(Ke(t),n);return{result:e,text:this.format(e),number:null,exact:!1}}const s=Mt(t,n);return{result:s.node,text:s.text,number:s.number,re:s.re,im:s.im,exact:s.exact}}equivalent(e,n){const t=this.node(e),s=this.node(n),i=this.defined(V("-",[t,s])),r=this.simplify(i,{steps:!1}).result;if("num"===r.type&&"0"===r.token)return{equal:!0,how:"exact"};const o=[...sn(i)];if(!o.length)try{return{equal:Math.abs(Mt(i,{digits:30}).number)<1e-25,how:"numeric"}}catch{return{equal:!1,how:"numeric"}}const a=[.31,1.7,2.9,-.83,.57];let u=0;for(let e=0;e<a.length;e++){const n=Object.fromEntries(o.map((n,t)=>[n,String(a[(e+t)%a.length]+t/7)]));let t;try{t=Mt(i,{digits:30,scope:n}).number}catch{continue}if(u++,Math.abs(t)>1e-20)return{equal:!1,how:"numeric"}}return{equal:u>0,how:"numeric"}}modes(){return this.set.modes()}}function Ji(e={}){const n=!1===e.defaults?[]:[...Ri,...e.complex?Ui:[]],{specs:t,messages:s}=function(e){Ft();const n=[],t={};for(const s of e){const e="string"==typeof s?Bn(s):s,i=Array.isArray(e)?e:e?.rules??[];for(const n of(Array.isArray(e)?[]:e?.operators)??[]){if(!n?.symbol)throw new Error("an operator needs a symbol");I(n.symbol)||N({symbol:String(n.symbol),arity:"any"===n.arity?$:Number(n.arity),label:n.label})}Object.assign(t,(Array.isArray(e)?null:e?.messages)??{});for(const e of i)n.push(e)}return{specs:n,messages:t}}([...n,...e.rules??[]]),i=pe(e.complex,()=>Bt(t));return new Qi(i,{..._i,...s},e.format??zi,e.read??null,Boolean(e.complex))}function Ki(n){const t=n=>e("op"===n.type?Xi(n,t):function(e){const n=e.value;return"symbol"!==e.type?n:c[n]?c[n]:"\\+"===n||"\\-"===n?n[1]:n}(n));return t(n)}const Yi={"+":"+","-":"-","*":"*","/":"/","^":"^",mod:"mod","±":"±","=":"=","===":"===","≠":"≠","≠=":"≠","<":"<",">":">","≤":"≤","≥":"≥","∈":"∈","∉":"∉","→":"→","≈":"≈","∪":"∪","∩":"∩","≡":"≡","&":"∧","|":"∨","\\xor":"⊕","\\nand":"↑","\\nor":"↓","\\implies":"⇒","\\iff":"⇔"},Gi={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]};function Xi(e,c){const{op:m,args:g}=e,[v,b]=g,w=(e,n)=>a(m,u(e),n)?`(${c(e)})`:c(e),y=()=>g.map(c).join(", "),x=e=>d(m,e)?`(${c(e)})`:c(e);if("*"===m&&n(e))return Xi({...e,op:"neg",args:[b]},c);if("+"===m&&n(b))return Xi({...e,op:"-",args:[v,b.args[1]]},c);if("-"===m&&n(b))return Xi({...e,op:"+",args:[v,b.args[1]]},c);if("^"===m){const e=w(v,"left");return`${e.startsWith("-")?`(${e})`:e}^${w(b,"right")}`}if("*"===m&&e.written)return`${w(v,"left")} ${"cross"===e.written?"×":"·"} ${w(b,"right")}`;if(Yi[m])return`${w(v,"left")} ${Yi[m]} ${w(b,"right")}`;if(t[m])return`${m}(${s(e).map(e=>`[${e.map(c).join(", ")}]`).join(", ")})`;if(Gi[m])return Gi[m][0]+y()+Gi[m][1];if(i(m))return`${r(m)}(${y()})`;switch(m){case"neg":return"-"+x(v);case"pmod":return`${c(v)} (mod ${c(b)})`;case"pm":return"±"+x(v);case"!":return x(v)+"!";case"\\not":return"¬"+x(v);case"sqrt":return`√(${c(v)})`;case"root":{const e="number"===v.type?{3:"∛",4:"∜"}[v.value]:null;return e?`${e}(${c(b)})`:`root(${c(v)}, ${c(b)})`}case"abs":return`|${c(v)}|`;case"floor":return`⌊${c(v)}⌋`;case"ceil":return`⌈${c(v)}⌉`;case"log":return`log_${"op"===v.type?`(${c(v)})`:c(v)}(${c(b)})`;case"loglog":return`ln(ln(${c(v)}))`;case"logloglog":return`ln(ln(ln(${c(v)})))`;case"perm":return`perm(${c(v)}, ${c(b)})`;case"comb":return`comb(${c(v)}, ${c(b)})`;case"_":return`${c(v)}_${c(b)}`;case"?:":return`${l(v)?`(${c(v)})`:c(v)} ? ${c(b)} : ${c(g[2])}`;case"sum":return g.map((e,n)=>a("+",u(e),n?"right":"left")?`(${c(e)})`:c(e)).join(" + ");case"prod":return g.map((e,n)=>a("*",u(e),n?"right":"left")?`(${c(e)})`:c(e)).join(" * ");case"setbuilder":return`{${g.map(c).join(" : ")}}`;case"evaluated":return`evaluated(${g.map(c).join(", ")})`;case"der":{const{n:n,body:t,by:s,at:i,variable:r}=o(e);if(i)return`der(${c(t)}, ${c(s)} = ${c(i)}${n>1?`, ${n}`:""})`;const a=n>1?`^${n}`:"";return r?`d${a}${c(t)}/d${c(s)}${a}`:`d${a}/d${c(s)}${a}(${c(t)})`}case"int":return function(e,n){const[t,s,i,r]=e,o=e.length>=2&&h(s)?n(s):f(t)||"x",a=`${n(t)} d${o}`;return 1===e.length||2===e.length&&h(s)?`∫ ${a}`:`int(${e.map(n).join(", ")})`}(g,c);case"lim":return function(e,n){const[t,s,i,r]=e;return 4===e.length?`lim(${n(t)}, ${n(s)}, ${n(i)}, ${p(r).toLowerCase().startsWith("r")?"r":"l"})`:`lim(${e.map(n).join(", ")})`}(g,c);case"\\sumidx":return er("∑",g,c);case"\\prodidx":return er("∏",g,c)}return`${m}(${y()})`}function er(e,n,t){const[s,i,r]=n,o="∑"===e?"sum":"prod";if(3===n.length&&"op"===i.type&&"="===i.op)return`${o}(${t(s)}, ${t(i)}, ${t(r)})`;if(2===n.length&&"op"===i.type&&"∈"===i.op)return`${o}(${t(s)}, ${t(i)})`;const a=f(s);return 3===n.length&&a?`${o}(${t(s)}, ${a} = ${t(i)}, ${t(r)})`:1===n.length?`${e} ${t(s)}`:2===n.length?`${e}[${t(i)}] ${t(s)}`:`${e}[${t(i)}, ${t(r)}] ${t(s)}`}for(const e of[Yi,Gi])Object.setPrototypeOf(e,null);const nr=Symbol.for("inlinemath.expressions"),tr=new Map,sr={re:"Re",im:"Im",conj:"overline"},ir=["Re","Im","re","im","conj","arg"];function rr(e){const n=[],t=e=>{"op"===e.type?(e.args.forEach(t),b(e.op)?(-1===b(e.op).arity&&n.push(String(e.args.length)),n.push(e.op)):n.push(String(e.args.length),`\\:${sr[e.op]??e.op}`)):n.push(e.token)};return t(e),n}function or(e,n){if(!n)return e;const t=new Map;for(const[e,s]of Object.entries(n))if("number"==typeof s?Number.isFinite(s):"bigint"==typeof s||"string"==typeof s)try{t.set(e,v(String(s)))}catch{}if(!t.size)return e;const s=function(e){let n;try{n=w(e)}catch{return new Set}const t=e=>"symbol"===e?.type?e.value:"op"===e?.type&&["=","→"].includes(e.op)&&"symbol"===e.args[0].type?e.args[0].value:null,s=new Set;return y(n,e=>{if("op"!==e.type||e.args.length<2)return;const n=e.op.startsWith("\\:")?e.op.slice(2):e.op;["der","int","lim","diff","derivative","differentiate","integrate","integral","solve","limit"].includes(n)&&t(e.args[1])&&s.add(t(e.args[1]))}),s}(e);return e.flatMap(e=>t.has(e)&&!s.has(e)?t.get(e):[e])}const ar={right:"right",r:"right","+":"right",left:"left",l:"left","-":"left"},ur=new Set(["simplify","expand","factor","cancel","diff","integrate","solve","approx","limit"]),lr={integral:"integrate",differentiate:"diff",approximate:"approx",simp:"simplify"};function cr(e={}){const n=e.rules||e.names?null:e.complex?"complex":"default";if(n&&tr.has(n))return tr.get(n);const t=[...e.names??[],...e.complex?ir:[],...ur,...Object.keys(lr)],s=Ji({...e,read:e=>v(e,{names:t}),format:zi});return n&&tr.set(n,s),s}function fr(e={}){const n=e.cas??cr(),t=void 0===e.steps?{}:{steps:e.steps},s=(e,i)=>{let r;try{r=n.read(e)}catch{return x(e,i)}const o=i&&i[nr];o&&(r=r.flatMap(e=>Object.hasOwn(o,e)?o[e]:[e])),r=or(r,i);const a=r[r.length-1],u=a?.startsWith("\\:")?lr[a.slice(2)]??a.slice(2):null,l=u&&ur.has(u),c="der"===a||"int"===a||"lim"===a;if(!l&&!c)return x(e,i);const f=n.node(r),p=c&&f.op!==a,h=l?f.args:[f],d=e=>e?e.s:void 0,v=(e,s,i)=>{if(!s||"="!==s.op)return n.diff(e,d(s),{...t,order:i});const r=s.args[0].s,o=n.diff(e,r,{...t,order:i}),a=n.substitute(o.result,{[r]:s.args[1].s},t);return{...a,steps:[...o.steps??[],...a.steps??[]]}};let b;try{switch(p?"simplify-read":l?u:"der"===a?"derivative":"lim"===a?"lim":"antiderivative"){case"simplify-read":b=n.simplify(f,t);break;case"simplify":b=n.simplify(h[0],t);break;case"expand":b=n.expand(h[0],t);break;case"factor":b=n.factor(h[0],t);break;case"cancel":b=n.cancel(h[0],t);break;case"diff":b=v(h[0],h[1],h[2]?Number(h[2].s):1);break;case"integrate":b=n.integrate(h[0],d(h[1]),{...t,...h[3]?{from:h[2].s,to:h[3].s}:{}});break;case"solve":b=n.solve(h[0],d(h[1]),t);break;case"lim":b=n.limit(f,void 0,void 0,t);break;case"limit":b=(([e,s,i,r])=>{let o=r?ar[r.s.replace(/^\\/,"")]:void 0;if(r&&!o)throw new Error(`a side is right or left, not ${r.s}`);if(s&&"→"===s.op){[s,i]=s.args;const e="^"===i.op?i.args[1].s.replace(/^\\/,""):null;"+"!==e&&"-"!==e||(o=ar[e],i=i.args[0])}return n.limit(e,d(s),i,{...t,...o?{side:o}:{}})})(h);break;case"approx":b=n.approximate(h[0],{...t,digits:h[1]?Number(h[1].s):15});break;case"derivative":b=v(f.args[0],f.args[1],1);break;default:b=n.integrate(f,void 0,t)}}catch(n){return`(${e})`}if(s.last=b,!b.result)return`"${b.text}"`;const w=(y=rr(b.result),m(y)?"":Ki(g(y)));var y;return/^-?\d+(\.\d+)?$/.test(w)?w:`(${w})`};return s}const pr=e=>String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function hr(e,n={}){return`<ol class="mv-steps">${e.map(e=>{const t=rr(_(e.from)),s=q(t,{...n,highlight:e.path&&e.path.length?{path:e.path}:void 0}),i=e.to===e.from?"":`<span class="mv-step-arrow" aria-label="becomes">⟶</span>${q(rr(_(e.to)),n)}`,r=e.explanation?`<p class="mv-step-why">${pr(e.explanation)}</p>`:"";return`<li class="mv-step" data-rule="${pr(e.id)}"><span class="mv-step-name">${pr(e.name)}</span><div class="mv-step-maths">${s}${i}</div>${r}</li>`}).join("")}</ol>`}export{fr as casBlocks,cr as mathCAS,hr as stepsHTML,rr as tokensOf};