@mathzetta/inlinemath 0.4.1 → 0.4.2

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.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};
1
+ /* Inline Math 0.4.2 — 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 r,G as i,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 y,z as w}from"./chunks/lite-Dl7abp_j.js";import{c as x}from"./chunks/calculate-BPhXubl4.js";import{a as q}from"./chunks/html-B5rAcnpJ.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 I(e){const n=k.get(e);return n||(M(e)?{...O,symbol:e,label:e.slice(2)}:null)}function A(e){return k.has(e)||M(e)}const E=e=>Number.isFinite(e)&&Number.isInteger(e)?e:null,j=e=>Number.isFinite(e)?e:null;!function(){N({symbol:"+",arity:2,commutative:!0,label:"add",fold:(e,n)=>j(e+n)}),N({symbol:"-",arity:2,label:"subtract",fold:(e,n)=>j(e-n)}),N({symbol:"*",arity:2,commutative:!0,label:"multiply",fold:(e,n)=>j(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?j(e**n):null}),N({symbol:"neg",arity:1,label:"negate",fold:e=>j(-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=>j(Math.abs(e))}),N({symbol:"floor",arity:1,label:"floor",fold:e=>j(Math.floor(e))}),N({symbol:"ceil",arity:1,label:"ceiling",fold:e=>j(Math.ceil(e))}),N({symbol:"round",arity:2,label:"round",fold:(e,n)=>Number.isInteger(n)?j(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 T="num",z="sym",Z="op",C=Object.freeze([]);class F extends Error{constructor(e){super(e),this.name="ExprError"}}function B(e){if("number"!=typeof e||!Number.isFinite(e))throw new F(`not a finite number: ${e}`);const n=(t=e,Object.is(t,-0)?"0":String(t));var t;return Object.freeze({type:T,token:n,value:e,args:C,s:n})}function D(e){if("string"!=typeof e||""===e)throw new F("symbol needs a non-empty token");return Object.freeze({type:z,token:e,value:null,args:C,s:e})}function W(e){const n=/^(-?)0*(\d+?)(?:\.(\d*?)0*)?$/.exec(String(e));if(!n)throw new F(`not an exact decimal: ${e}`);const[,t,s,r=""]=n,i=r?`${s}.${r}`:s,o=/^0(\.0*)?$/.test(i)?"0":t+i;return Object.freeze({type:T,token:o,value:Number(o),args:C,s:o})}const R=/^-?\d+(\.\d+)?$/;function P(e){const n=String(e);if(R.test(n))return W(n);if(""!==n&&!/\s/.test(n)){const e=Number(n);if(Number.isFinite(e))return B(e)}return D(n)}function U(e,n){const t=I(e);if(!t)throw new F(`unknown operator "${e}"`);if(t.arity!==$&&n.length!==t.arity)throw new F(`"${e}" takes ${t.arity} operand(s), got ${n.length}`);const s=Object.freeze(n.slice()),r=t.arity===$?` ${s.length}`:"",i=`${s.length?s.map(e=>e.s).join(" "):""}${s.length,""}${r} ${e}`.trimStart();return Object.freeze({type:Z,op:e,token:e,value:null,args:s,s:i})}const V=e=>e.type===T,L=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 F("fromPostfix needs an array of tokens");if(0===e.length)throw new F("empty expression");const n=[];for(let t=0;t<e.length;t++){const s=String(e[t]);if(A(s)){let e=I(s).arity;if(e===$){const r=n.pop();if(e=r&&r.type===T&&Number.isInteger(r.value)&&r.value>=0?r.value:-1,e<0)throw new F(`"${s}" at position ${t+1} takes any number of operands, so a count must come before it`)}if(n.length<e)throw new F(`"${s}" at position ${t+1} needs ${e} operand(s), only ${n.length} on the stack`);const r=n.splice(n.length-e,e);n.push(U(s,r))}else n.push(P(s))}if(1!==n.length){const t=[...new Set(e.filter(e=>!A(e)))];throw new F(`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===T||e.type!==z&&e.args.every(Y)}function G(e,n="pre",t=[],s=[]){"pre"===n&&s.push({node:e,path:t});for(let r=0;r<e.args.length;r++)G(e.args[r],n,t.concat(r),s);return"post"===n&&s.push({node:e,path:t}),s}function X(e,n){let t=e;for(const e of n){if(!t.args[e])throw new F(`bad path [${n.join(",")}]`);t=t.args[e]}return t}function ee(e,n,t){if(0===n.length)return t;const[s,...r]=n,i=e.args.slice();return i[s]=ee(i[s],r,t),U(e.op,i)}class ne extends Error{constructor(e){super(e),this.name="CasError"}}const te=1e5,se=e=>e<0n?-e:e,re=e=>0n===e?0:se(e).toString(2).length;function ie(e,n){for(e=se(e),n=se(n);n;)[e,n]=[n,e%n];return e}class oe{constructor(e,n=1n){if(0n===n)throw new ne("division by zero");n<0n&&(e=-e,n=-n);const t=ie(e,n)||1n;if(this.n=e/t,this.d=n/t,re(this.n)>te||re(this.d)>te)throw new ne("a number too large to keep exactly")}static of(e){return new oe(BigInt(e))}add(e){return new oe(this.n*e.d+e.n*this.d,this.d*e.d)}sub(e){return new oe(this.n*e.d-e.n*this.d,this.d*e.d)}mul(e){return new oe(this.n*e.n,this.d*e.d)}div(e){if(0n===e.n)throw new ne("division by zero");return new oe(this.n*e.d,this.d*e.n)}neg(){return new oe(-this.n,this.d)}abs(){return this.n<0n?this.neg():this}inv(){return oe.ONE.div(this)}pow(e){if((e=BigInt(e))<0n)return this.inv().pow(-e);if((0n===this.n||1n===se(this.n))&&1n===this.d)return 0n===e||-1n===this.n&&e%2n==0n?oe.ONE:this;if(BigInt(Math.max(re(this.n),re(this.d)))*e>BigInt(te))throw new ne("a power too large to work out exactly");return new oe(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 oe(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(re(this.n),re(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 ae(e){const n=/^(-?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(String(e));if(!n||""===n[2]&&!n[3])return null;const[,t,s,r="",i="0"]=n;let o=new oe(BigInt((s||"0")+r),10n**BigInt(r.length));const a=Number(i);return a&&(o=o.mul(oe.of(10).pow(a))),t?o.neg():o}function ue(e,n){if(e<2n)return e;if(n>=re(e))return 1n;const t=BigInt(n);let s=1n<<BigInt(Math.ceil(re(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}oe.ZERO=new oe(0n),oe.ONE=new oe(1n),oe.MINUS_ONE=new oe(-1n),oe.HALF=new oe(1n,2n);const le=(()=>{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 ce(e,n){const t=BigInt(n);let s=1n,r=1n,i=e;for(const e of le){if(e*e>i)break;if(i%e)continue;let n=0n;for(;i%e===0n;)i/=e,n++;s*=e**(n/t),r*=e**(n%t)}if(i>1n){const e=function(e,n){if(e<0n)return null;if(e<2n)return e;const t=ue(e,n);return t**BigInt(n)===e?t:null}(i,n);null!==e?s*=e:r*=i}return{outside:s,inside:r}}const fe=new Set(["pi","e","π"]),pe={complex:!1};function he(e,n){const t=pe.complex;pe.complex=Boolean(e);try{return n()}finally{pe.complex=t}}const de=e=>fe.has(e)||pe.complex&&"i"===e,me=e=>pe.complex&&"atom"===e.k&&"sym"===e.node.type&&"i"===e.node.token,ge=e=>({k:"num",q:e}),ve=ge(oe.ONE),be=ge(oe.ZERO),ye=ge(oe.HALF),we=e=>"num"===e.k,xe=e=>({k:"atom",node:e}),qe=new WeakMap;function ke(e){let n=qe.get(e);return void 0===n&&qe.set(e,n=nn(e).s),n}function $e(e){if("num"===e.k)return 0;if("atom"===e.k)return"sym"===e.node.type&&de(e.node.token)?0:1;if("add"===e.k)return Math.max(...e.terms.map(e=>$e(e.x)));let n=0;for(const t of e.fs){const e=$e(t.b);e&&(n+=e*(we(t.e)?t.e.q.toNumber():1))}return n}function Se(e,n){return"num"===e.k?n&&!we(n)?3:0:me(e)?1.5:"atom"===e.k&&"sym"===e.node.type?de(e.node.token)?n&&!we(n)?3:1:2:"atom"===e.k?3:4}const Me=(e,n)=>e<n?-1:e>n?1:0;function Ne(e){const n=new Map,t=(e,t)=>{"atom"!==e.k||"sym"!==e.node.type||de(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 Oe(e,n){const t=$e(n.x)-$e(e.x);if(t)return t;const s=Ne(e.x),r=Ne(n.x);for(const e of[...new Set([...s.keys(),...r.keys()])].sort()){const n=(r.get(e)??0)-(s.get(e)??0);if(n)return n}return Me(ke(e.x),ke(n.x))}function Ie(e,n){return e.isOne?n:e.isZero?be:Te([ge(e),n])}function Ae(e){if("num"===e.k)return{coef:e.q,rest:null};if("mul"!==e.k||e.c.isOne)return{coef:oe.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:oe.ONE,fs:e.fs};return{coef:e.c,rest:n}}function Ee(e){let n=oe.ZERO;const t=new Map,s=(e,n)=>{const s=ke(n),r=t.get(s);r?r.coef=r.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 r=[...t.values()].filter(e=>!e.coef.isZero);return r.length?n.isZero&&1===r.length?Ie(r[0].coef,r[0].x):(r.sort(Oe),{k:"add",c:n,terms:r}):ge(n)}function je(e,n){if(!we(n))return e.isOne?{coef:oe.ONE,fs:[]}:{coef:oe.ONE,fs:[{b:ge(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 ne("division by zero");return{coef:oe.ZERO,fs:[]}}if(e.isOne)return{coef:oe.ONE,fs:[]};if(e.sign<0){if(t.d%2n==1n){const{coef:s,fs:r}=je(e.neg(),n);return{coef:t.n%2n==0n?s:s.neg(),fs:r}}if(pe.complex&&2n===t.d){const{coef:s,fs:r}=je(e.neg(),n);return{coef:s,fs:[...r,{b:Ce,e:ge(new oe(t.n))}]}}return{coef:oe.ONE,fs:[{b:ge(e),e:n}]}}if(!e.isInteger){const s=je(new oe(e.n),n),r=je(new oe(e.d),ge(t.neg()));return{coef:s.coef.mul(r.coef),fs:[...s.fs,...r.fs]}}const s=t.floor(),r=t.sub(s);if(BigInt(re(e.n))*r.n>BigInt(te)||r.d>1000n)return{coef:oe.ONE,fs:[{b:ge(e),e:n}]};let i=s.isZero?oe.ONE:e.pow(s.n);const{outside:o,inside:a}=ce(e.n**r.n,Number(r.d));i=i.mul(new oe(o));return{coef:i,fs:a>1n?[{b:ge(new oe(a)),e:ge(new oe(1n,r.d))}]:[]}}function Te(e){let n=oe.ONE;const t=new Map,s=(e,n)=>{const s=ke(e),r=t.get(s);r?r.e=Ee([r.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,ve);if(n.isZero)return be;const r=[],i=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=i.get(n);t?t.n*=e.b.q.n:i.set(n,{n:e.b.q.n,e:e.e});continue}const t=je(e.b.q,e.e);n=n.mul(t.coef),r.push(...t.fs);continue}if("mul"===e.b.k&&we(e.e)&&e.e.q.isInteger){const t=ze(e.b,e.e);"mul"===t.k?(n=n.mul(t.c),r.push(...t.fs)):"num"===t.k?n=n.mul(t.q):r.push({b:t,e:ve});continue}r.push(e)}for(const{n:e,e:t}of i.values()){const s=je(new oe(e),t);n=n.mul(s.coef),r.push(...s.fs)}if(n.isZero)return be;const o=new Map;for(const e of r){const n=ke(e.b),t=o.get(n);t?t.e=Ee([t.e,e.e]):o.set(n,{...e})}let a=[...o.values()].filter(e=>!(we(e.e)&&e.e.q.isZero));if(pe.complex){a=a.flatMap(e=>{if(!me(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:ve}]:[]});const e=a.filter(e=>"add"===e.b.k&&we(e.e)&&e.e.q.isInteger&&Be(e.b)),t=a.some(e=>me(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)&&!me(n.b));let r=t?[Ce]:[ve];for(const n of e){const e=n.e.q.sign<0?Re(n.b):n.b;for(let t=0n;t<(n.e.q.sign<0?-n.e.q.n:n.e.q.n);t++)r=De(r,on(e))}return Te([ge(n),Ee(r),...s.map(e=>Ze(e.b,e.e))])}}if(a.some(e=>"num"===e.b.k&&we(e.e)&&e.e.q.compare(oe.ONE)>=0))return Te([ge(n),...a.map(e=>"num"===e.b.k?ze(e.b,e.e):{k:"mul",c:oe.ONE,fs:[e]})]);if(!a.length)return ge(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 Ee([ge(n.mul(e.c)),...e.terms.map(e=>Ie(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)=>Se(e.b,e.e)-Se(n.b,n.e)||Me(ke(e.b),ke(n.b))),{k:"mul",c:n,fs:a})}function ze(e,n){if(pe.complex&&we(n)&&n.q.isInteger){if(me(e))return Te([{k:"mul",c:oe.ONE,fs:[{b:e,e:n}]}]);if("add"===e.k&&Be(e)&&!n.q.isOne)return Te([{k:"mul",c:oe.ONE,fs:[{b:e,e:n}]}])}if(we(n)){if(n.q.isZero){if(we(e)&&e.q.isZero)throw new ne("0^0 is undefined");return ve}if(n.q.isOne)return e}if(we(e)){const t=je(e.q,n);if(!t.fs.length)return ge(t.coef);if(t.fs.some(e=>me(e.b)))return Te([ge(t.coef),...t.fs.map(e=>({k:"mul",c:oe.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(pe.complex&&we(n)&&2n===n.q.d&&Be(e)){const t=We(e);if(t&&we(t.im)&&!t.im.q.isZero){const e=e=>ze(e,ge(oe.of(2))),s=ze(Ee([e(t.re),e(t.im)]),ye),r=ze(Te([Ee([s,t.re]),ge(oe.HALF)]),ye),i=ze(Te([Ee([s,Ve(t.re)]),ge(oe.HALF)]),ye);return ze(Ee([r,Te([ge(oe.of(t.im.q.sign)),i,Ce])]),ge(new oe(n.q.n)))}}if("mul"===e.k){if(we(n)&&n.q.isInteger)return Te([ge(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([ze(ge(e.c),n),ze({k:"mul",c:oe.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:oe.ONE,fs:[{b:e,e:n}]}}function Ze(e,n){return we(n)&&n.q.isZero?ve:we(e)?ze(e,n):we(n)&&n.q.isOne?e:{k:"mul",c:oe.ONE,fs:[{b:e,e:n}]}}const Ce=xe(D("i")),Fe=e=>pe.complex&&nn(e).s.split(" ").includes("i");function Be(e){return pe.complex&&Fe(e)&&0===rn(nn(e)).size}function De(e,n){const t=[];for(const s of e)for(const e of n)t.push(Te([s,e]));return on(Ee(t))}function We(e){const n=[],t=[];for(const s of on(e)){const{coef:e,rest:r}=Ae(s),i=r?an(r):[],o=i.filter(e=>me(e)),a=i.filter(e=>!me(e));if(a.some(e=>Fe(e)))return null;(o.length?t:n).push(Te([ge(e),...a]))}return{re:Ee(n),im:Ee(t)}}function Re(e){const n=We(e);if(!n)return ze(e,ge(oe.MINUS_ONE));const t=Ee([ze(n.re,ge(oe.of(2))),ze(n.im,ge(oe.of(2)))]);return Te([Ee([n.re,Te([ge(oe.MINUS_ONE),n.im,Ce])]),ze(t,ge(oe.MINUS_ONE))])}const Pe={re:([e])=>We(e)?.re??null,im:([e])=>We(e)?.im??null,conj:([e])=>{const n=We(e);return n?Ee([n.re,Te([ge(oe.MINUS_ONE),n.im,Ce])]):null},arg:([e])=>{const n=We(e);return n?Qe("atan2",[n.im,n.re]):null},abs:([e])=>{const n=We(e);return!n||we(n.im)&&n.im.q.isZero?null:ze(Ee([ze(n.re,ge(oe.of(2))),ze(n.im,ge(oe.of(2)))]),ye)}},Ue={Re:"re",re:"re",Im:"im",im:"im",conj:"conj",overline:"conj",bar:"conj",arg:"arg"},Ve=e=>Te([ge(oe.MINUS_ONE),e]),Le=(e,n)=>Te([e,ze(n,ge(oe.MINUS_ONE))]),_e=3000n,He={abs:([e])=>we(e)?ge(e.q.abs()):"mul"!==e.k||e.c.isOne?null:Te([ge(e.c.abs()),Qe("abs",[Ae(e).rest])]),floor:([e])=>we(e)?ge(e.q.floor()):null,ceil:([e])=>we(e)?ge(e.q.ceil()):null,"!":([e])=>{if(!we(e)||!e.q.isInteger||e.q.sign<0||e.q.n>_e)return null;let n=1n;for(let t=2n;t<=e.q.n;t++)n*=t;return ge(new oe(n))},mod:([e,n])=>we(e)&&we(n)&&!n.q.isZero?ge(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)?ge(new oe(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 be;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 r=Math.round(t*s);if(!(Math.abs(t*s-r)>1e-9||0===r)&&(Math.abs(r)<=256&&e.q.pow(BigInt(r)).equals(n.q.pow(BigInt(s)))))return ge(new oe(BigInt(r),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<=_e?ge(function(e,n){if(n>e)return oe.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 oe(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<=_e))return null;if(n.q.n>e.q.n)return be;let t=1n;for(let s=0n;s<n.q.n;s++)t*=e.q.n-s;return ge(new oe(t))}};function Qe(e,n){if(pe.complex&&Pe[e]){const t=Pe[e](n);if(t)return t}const t=He[e];if(t){const e=t(n);if(e)return e}return xe(U(e,n.map(nn)))}const Je=new Map;function Ke(e){const n=pe.complex?`ℂ ${e.s}`:e.s,t=Je.get(n);if(t)return t;const s=function(e){if("num"===e.type){const n=ae(e.token);if(!n)throw new ne(`not an exact number: ${e.token}`);return ge(n)}if("sym"===e.type)return"π"===e.token?xe(D("pi")):xe(e);const n=e.args.map(Ke);switch(e.op){case"+":return Ee(n);case"-":return((e,n)=>Ee([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 ze(n[0],n[1]);case"sqrt":return ze(n[0],ye);case"root":return ze(n[1],ze(n[0],ge(oe.MINUS_ONE)));default:{const t=e.op.startsWith("\\:")?e.op.slice(2):null;return t&&pe.complex&&Ue[t]&&1===n.length?Qe(Ue[t],n):t&&A(t)&&I(t).arity===n.length?Qe(t,n):Qe(e.op,n)}}}(e);return Je.size>2e4&&Je.clear(),Je.set(n,s),s}const Ye=e=>nn(Ke(e)),Ge=e=>W(String(e));function Xe(e){return e.isInteger?Ge(e.n):U("/",[Ge(e.n),Ge(e.d)])}const en=new WeakMap;function nn(e){let n=en.get(e);return n||en.set(e,n=function(e){switch(e.k){case"num":return Xe(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(tn(e.b,ge(e.e.q.neg()))):t.push(tn(e.b,e.e));let r=1n!==e.n&&-1n!==e.n||!t.length?sn([Ge(e.n),...t]):sn(t);-1n===e.n&&t.length&&(r=U("neg",[r]));1n!==e.d&&s.unshift(Ge(e.d));return s.length?U("/",[r,sn(s)]):r}(e.c,e.fs);case"add":return function(e){let n=null;const t=e=>pe.complex&&Fe(e.x)&&0===rn(nn(e.x)).size,s=[...e.terms.filter(e=>!t(e)),...e.terms.filter(t)],r=e.c,i=()=>{r.isZero||(n=n?r.sign<0?U("-",[n,Xe(r.neg())]):U("+",[n,Xe(r)]):Xe(r))};let o=!1;for(const e of s)!o&&t(e)&&(i(),o=!0),n=n?e.coef.sign<0?U("-",[n,nn(Ie(e.coef.neg(),e.x))]):U("+",[n,nn(Ie(e.coef,e.x))]):nn(Ie(e.coef,e.x));o||i();return n}(e);default:throw new Error(`bad form ${e.k}`)}}(e)),n}function tn(e,n){const t=nn(e);if(we(n)){const e=n.q;if(e.isOne)return t;if(1n===e.n&&2n===e.d)return U("sqrt",[t]);if(1n===e.n)return U("root",[Ge(e.d),t])}return U("^",[t,nn(n)])}const sn=e=>e.reduce((e,n)=>e?U("*",[e,n]):n,null);function rn(e,n=new Set){if("sym"===e.type)de(e.token)||n.add(e.token);else if(L(e))for(const t of e.args)rn(t,n);return n}function on(e){if("add"!==e.k)return[e];const n=e.terms.map(e=>Ie(e.coef,e.x));return e.c.isZero||n.push(ge(e.c)),n}function an(e){if("num"===e.k)return[e];if("mul"!==e.k)return[e];const n=e.c.isOne?[]:[ge(e.c)];for(const t of e.fs)n.push(Ze(t.b,t.e));return n}const un="_",ln=new WeakMap;function cn(e,n){return[...n,...I(e.op)?.arity===$?[String(e.args.length)]:[],e.op].join(" ")}function fn(e,n){let t=ln.get(e);t||ln.set(e,t=new Map);const s=t.get(n);if(s)return s;const r=function(e,n){const t={key:un,slots:[e]};if(e.type!==Z||n<=0)return[t];const s=e.args.map(e=>fn(e,n-1)),r=[t],i=new Array(s.length).fill(0);for(;;){const n=[],t=[];for(let e=0;e<s.length;e++){const r=s[e][i[e]];n.push(r.key);for(const e of r.slots)t.push(e)}if(r.push({key:cn(e,n),slots:t}),r.length>=4096)break;let o=s.length-1;for(;o>=0&&!(++i[o]<s[o].length);o--)i[o]=0;if(o<0)break}return r}(e,n);return t.set(n,r),r}function pn(e){return e.type!==Z?un:cn(e,e.args.map(pn))}function hn(e,n=[]){if(e.type!==Z)n.push(e);else for(const t of e.args)hn(t,n);return n}const dn=new Map,mn=new Map;class gn extends Error{constructor(e){super(e),this.name="RequirementError"}}function vn(e,n,t=""){dn.set(e,{name:e,fn:n,doc:t,arity:Math.max(0,n.length-1)})}function bn(e,n,t=""){mn.set(e,{name:e,fn:n,doc:t})}function yn(e){return dn.get(e)||null}function wn(e){return mn.get(e)||null}const xn=e=>e.type===T;function qn(e,n){return e.type===Z&&(e.op===n||e.args.some(e=>qn(e,n)))}vn("always",()=>!0,"matches anything"),vn("never",()=>!1,"matches nothing"),vn("isLeaf",e=>e.type!==Z,"a bare operand, not an operation"),vn("isCompound",e=>e.type===Z,"an operation, not a bare operand"),vn("isSymbol",e=>e.type===z,"a non-numeric operand such as x"),vn("isOperation",(e,n)=>e.type===Z&&e.op===n,"is this specific operation"),vn("notOperation",(e,n)=>!(e.type===Z&&e.op===n),"is anything except this operation"),vn("isNumber",xn,"a numeric literal"),vn("isInteger",e=>xn(e)&&Number.isInteger(e.value),"a whole number"),vn("isPositive",e=>xn(e)&&e.value>0,"greater than zero"),vn("isNegative",e=>xn(e)&&e.value<0,"less than zero"),vn("isNonNegative",e=>xn(e)&&e.value>=0,"zero or greater"),vn("isZero",e=>xn(e)&&0===e.value,"exactly 0"),vn("isOne",e=>xn(e)&&1===e.value,"exactly 1"),vn("isNonZero",e=>xn(e)&&0!==e.value,"a number that is provably not 0"),vn("isNotZeroLiteral",e=>!(xn(e)&&0===e.value),"anything except a literal 0"),vn("isPositiveInteger",e=>xn(e)&&Number.isInteger(e.value)&&e.value>0,"a whole number above 0"),vn("isNegativeInteger",e=>xn(e)&&Number.isInteger(e.value)&&e.value<0,"a whole number below 0"),vn("isEven",e=>xn(e)&&Number.isInteger(e.value)&&e.value%2==0,"a whole even number"),vn("isOdd",e=>xn(e)&&Number.isInteger(e.value)&&1===Math.abs(e.value%2),"a whole odd number"),vn("greaterThan",(e,n)=>xn(e)&&e.value>Number(n),"above a given value"),vn("lessThan",(e,n)=>xn(e)&&e.value<Number(n),"below a given value"),vn("isValue",(e,n)=>xn(e)&&e.value===Number(n),"equals a given number"),vn("isNumeric",Y,"contains no symbols: a constant (it need not fold to a number: 1 sin)"),vn("hasSymbol",e=>!Y(e),"mentions a symbol somewhere, so it is not just a number"),vn("isVar",(e,n)=>e.type===z&&e.token===String(n),"is exactly this symbol"),vn("contains",(e,n)=>K(e).includes(String(n)),"mentions this operand somewhere"),vn("isFree",(e,n)=>!K(e).includes(String(n)),"never mentions this operand"),vn("hasOperation",(e,n)=>qn(e,String(n)),"uses this operation somewhere inside"),vn("equals",(e,n)=>e.s===String(n),"is exactly this postfix expression");const kn=e=>e.type===Z?null:e.token;function $n(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 gn(`bad requirement: ${JSON.stringify(e)}`)}bn("freeOf",(e,n)=>{const t=kn(n);return null!==t&&!K(e).includes(t)},"the first operand never mentions the second"),bn("dependsOn",(e,n)=>{const t=kn(n);return null!==t&&K(e).includes(t)},"the first operand does mention the second"),bn("sameAs",(...e)=>e.every(n=>n.s===e[0].s),"these operands are structurally identical"),bn("differs",(...e)=>new Set(e.map(e=>e.s)).size===e.length,"these operands are all different"),bn("sameValue",(...e)=>e.every(e=>xn(e))&&e.every(n=>n.value===e[0].value),"these operands are the same number");const Sn="simplify";class Mn extends Error{constructor(e,n){super(n?`rule "${n}": ${e}`:e),this.name="RuleError",this.ruleId=n}}const Nn=/^[A-Za-z_][A-Za-z0-9_]*$/;function On(e,n){if(V(e))return{literal:e.value};const t=e.token;if(t.startsWith("=")){const e=t.slice(1);if(""===e)throw new Mn('"=" needs an operand after it',n);return{token:e}}if(!Nn.test(t))throw new Mn(`"${t}" is not a usable slot name; use letters, digits and _`,n);if(A(t))throw new Mn(`slot name "${t}" collides with an operator`,n);return{name:t}}function In(e){if(!L(e))return[e];const n=e.args.map(In),t=I(e.op),s=[];for(const r 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(U(e.op,r)),t.commutative&&2===r.length&&r[0].s!==r[1].s&&s.push(U(e.op,[r[1],r[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 En(e){if(!e||"object"!=typeof e)throw new Mn("rule must be a mapping");const n=e.id||e.name;if(!n)throw new Mn("rule needs an id");if(!e.pattern)throw new Mn("rule needs a pattern",n);if(void 0===e.output||null===e.output)throw new Mn("rule needs an output",n);let t;try{t=_(String(e.pattern))}catch(e){if(e instanceof F)throw new Mn(`bad pattern: ${e.message}`,n);throw e}const s=hn(t).map(e=>On(e,n)),r=new Set(s.filter(e=>e.name).map(e=>e.name)),i=function(e,n,t){const s=[],r=e.when||{};if("object"!=typeof r||Array.isArray(r))throw new Mn('"when" must map slot names to lists of requirements',t);for(const[e,i]of Object.entries(r)){if(!n.has(e))throw new Mn(`"when" mentions "${e}", which is not a slot in the pattern`,t);const r=Array.isArray(i)?i:[i];for(const n of r){const{name:r,args:i}=$n(n),o=yn(r);if(!o)throw new Mn(`unknown requirement "${r}"`,t);s.push({slot:e,name:r,args:i,fn:o.fn})}}return s}(e,r,n),o=function(e,n,t){const s=[],r=e.require||[];if(!Array.isArray(r))throw new Mn('"require" must be a list of relations',t);for(const e of r){const{name:r,args:i}=$n(e),o=wn(r);if(!o)throw new Mn(`unknown relation "${r}"`,t);if(i.length<2)throw new Mn(`relation "${r}" needs at least two operands`,t);for(const e of i)if("string"==typeof e&&!n.has(e)&&Nn.test(e))throw new Mn(`relation "${r}" mentions "${e}", which is not a slot in the pattern`,t);s.push({name:r,args:i,fn:o.fn})}return s}(e,r,n),a=function(e,n,t){let s;try{s=_(e)}catch(n){throw new Mn(`bad output "${e}": ${n.message}`,t)}const r=e=>L(e)?{kind:"op",op:e.op,args:e.args.map(r)}:V(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 r(s)}(String(e.output),r,n),u=e.commutative?In(t):[t],l=[],c=new Set;for(const e of u){const t=pn(e),s=hn(e).map(e=>On(e,n)),r=t+"\0"+s.map(e=>e.name??(void 0!==e.literal?`#${e.literal}`:`=${e.token}`)).join(",");c.has(r)||(c.add(r),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):Sn,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:i,require:o,slots:[...r],depth:Q(t),bindings:l,freeSymbols:An(a),source:e};for(const e of l)e.rule=f;return f}function jn(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!==Sn&&(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 zn{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 Cn(e){let n=null,t=0;for(let s=0;s<e.length;s++){const r=e[s];if(n)r===n?"'"===n&&"'"===e[s+1]?s++:n=null:'"'===n&&"\\"===r&&s++;else if('"'===r||"'"===r)n=r;else if("["===r||"{"===r)t++;else if("]"===r||"}"===r)t--;else if(":"===r&&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 zn(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=Wn(n,t.indent),r=n.peek();if(r&&"..."!==r.text&&"---"!==r.text)throw new Tn(`unexpected content "${r.text}"`,r.n);return s}const Dn=/^[|>][-+]?\d*$/;function Wn(e,n){const t=e.peek();return!t||t.indent<n?null:Zn(t.text)?Rn(e,t.indent):Cn(t.text)?function(e,n){const t={};for(;;){const s=e.peek();if(!s||s.indent!==n)break;const r=Cn(s.text);if(!r)break;e.next();const{key:i,rest:o}=r;if(""===o){const s=e.peek();s&&s.indent>n?t[i]=Wn(e,s.indent):s&&s.indent===n&&Zn(s.text)?t[i]=Rn(e,n):t[i]=null}else Dn.test(o)?t[i]=Pn(e,o,n):t[i]=Un(o,s.n)}return t}(e,t.indent):(e.next(),Dn.test(t.text)?Pn(e,t.text,t.indent-1):Un(t.text,t.n))}function Rn(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?Wn(e,s.indent):null);continue}if(Dn.test(s.text.slice(2).trim())){t.push(Pn(e,s.text.slice(2).trim(),n));continue}const r=s.text.slice(2),i=n+2+(r.length-r.trimStart().length);e.push({raw:s.raw,n:s.n,indent:i,text:r.trim(),blank:!1}),t.push(Wn(e,i))}return t}function Pn(e,n,t){const s=n[0],r=(n.match(/[-+]/)||[""])[0],i=(n.match(/\d+/)||[null])[0];let o=i?t+Number(i):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"-"===r?u:"+"===r?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 _n=/^(true|false|null|yes|no|on|off|~)$/i;function Hn(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)||_n.test(e)||/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(e))}(n)?JSON.stringify(n):n}const Qn=e=>null==e||"object"!=typeof e;function Jn(e){return Array.isArray(e)?`[${e.map(Jn).join(", ")}]`:e&&"object"==typeof e?`{${Object.entries(e).map(([e,n])=>`${Hn(e)}: ${Jn(n)}`).join(", ")}}`:Hn(e)}function Kn(e){return Array.isArray(e)?!!e.every(e=>Qn(e)||Array.isArray(e)&&e.every(Qn))&&Jn(e).length<=72:!(!e||"object"!=typeof e)&&(Object.values(e).every(e=>Qn(e)||Array.isArray(e)&&e.every(Qn))&&Jn(e).length<=72)}function Yn(e){const n=[];return Gn(e,0,n),n.length?n.join("\n")+"\n":""}function Gn(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)Xn(s,n,t)}else{if(e&&"object"==typeof e){const r=Object.entries(e).filter(([,e])=>void 0!==e);if(0===r.length)return void t.push(s+"{}");for(const[e,s]of r)et(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+Hn(e))}(e,s,t)}}function Xn(e,n,t){const s=" ".repeat(n);if(null!==e&&"object"==typeof e&&!Kn(e)){const r=[];if(Gn(e,n+2,r),0===r.length)return void t.push(s+"-");t.push(s+"- "+r[0].slice(n+2));for(let e=1;e<r.length;e++)t.push(r[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+"- "+Hn(e));else t.push(s+"- "+Jn(e))}function et(e,n,t,s){const r=" ".repeat(t),i=Hn(e);if("string"==typeof n&&n.includes("\n")){s.push(`${r}${i}: |-`);for(const e of n.replace(/\n+$/,"").split("\n"))s.push(" ".repeat(t+2)+e)}else{if(null!==n&&"object"==typeof n)return Kn(n)?void s.push(`${r}${i}: ${Jn(n)}`):(s.push(`${r}${i}:`),void Gn(n,Array.isArray(n)?t:t+2,s));s.push(`${r}${i}: ${Hn(n)}`)}}class nt{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:En(e);if(this.rules.some(e=>e.id===n.id))throw new Mn(`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 nt(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===Sn?-1:n===Sn?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 nt.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 Mn('expected a list of rules, or a mapping with a "rules" list');const r=new nt;r.name=s;const i=[];for(let e=0;e<t.length;e++)try{r.add(t[e])}catch(n){i.push(`#${e+1}: ${n.message}`)}if(i.length&&n)throw new Mn(`${i.length} rule(s) failed to compile:\n ${i.join("\n ")}`);return r.errors=i,r}toSpecs(){return this.rules.map(jn)}toYaml(){const e=this.toSpecs();return this.name?Yn({name:this.name,rules:e}):Yn(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 tt(e,n){const t=Object.create(null),s=e.slots;for(let e=0;e<s.length;e++){const r=s[e],i=n[e];if(void 0!==r.literal){if(!V(i)||i.value!==r.literal)return null;continue}if(void 0!==r.token){if(i.s!==r.token)return null;continue}const o=t[r.name];if(void 0!==o){if(o.s!==i.s)return null}else t[r.name]=i}return t}function st(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 rt(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:r}of function(e,n){const t=fn(e,n),s=[];for(const e of t)e.key!==un&&s.push(e);return s}(e,n.maxDepth)){const e=n.candidates(s);if(e)for(const n of e){const e=tt(n,r);e&&(st(n.rule,e)&&t.push({rule:n.rule,binding:n,key:s,bound:e}))}}return t.sort(rt)}function ot(e,n,{order:t="post"}={}){const s=[];for(const{node:r,path:i}of G(e,t))for(const e of it(r,n))s.push({...e,node:r,path:i});return s}function at(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 U(e.op,e.args.map(e=>at(e,n)));default:throw new Error(`bad output template: ${JSON.stringify(e)}`)}}function ut(e){if(!L(e))return e;const n=e.args.map(ut),t=n.some((n,t)=>n!==e.args[t])?U(e.op,n):e,s=I(t.op);if(!s||!s.fold||!t.args.every(V))return t;if(ct.has(t.op)){const e=function(e,n){const[t,s]=n.map(pt);if(!t||n.length>1&&!s)return;let r;switch(e){case"neg":r={n:-t.n,scale:t.scale};break;case"+":{const[e,n,i]=ht(t,s);r={n:e+n,scale:i};break}case"-":{const[e,n,i]=ht(t,s);r={n:e-n,scale:i};break}case"*":r={n:t.n*s.n,scale:t.scale+s.scale};break;case"^":{if(0!==s.scale||s.n>64n||s.n<-64n)return null;const e=s.n<0n?-s.n:s.n;if((t.n<0n?-t.n:t.n).toString().length*Number(e)>ft)return null;const n={n:t.n**e,scale:t.scale*Number(e)};if(r=s.n<0n?function({n:e,scale:n}){if(0n===e)return null;let t=e<0n?-e:e,s=0,r=0;for(;t%2n==0n;)t/=2n,s++;for(;t%5n==0n;)t/=5n,r++;if(1n!==t)return null;const i=Math.max(s,r),o=10n**BigInt(n)*2n**BigInt(i-s)*5n**BigInt(i-r);return{n:e<0n?-o:o,scale:i}}(n):n,!r)return null;break}default:return}const i=function({n:e,scale:n}){const t=e<0n;let s=(t?-e:e).toString();n>0&&(s=s.padStart(n+1,"0"),s=`${s.slice(0,-n)}.${s.slice(-n)}`.replace(/\.?0+$/,""));return"0"===s?"0":(t?"-":"")+s}(r);return i.length>ft?null:i}(t.op,t.args.map(e=>e.token));if(void 0!==e)return null===e?t:W(e)}const r=s.fold(...t.args.map(e=>e.value));return null!=r&&Number.isFinite(r)?B(r):t}function lt(e,n){const t=function(e){const n=at(e.rule.outputTemplate,e.bound);return e.rule.fold?ut(n):n}(n);return{expr:ee(e,n.path,t),before:n.node,after:t,rule:n.rule,path:n.path,explanation:(s=n.rule,r=n.bound,i=t,s.explain?s.explain.replace(/\{(\w+)\}/g,(e,n)=>{if("result"===n)return i?i.s:e;const t=r[n];return t?t.s:e}):"")};var s,r,i}const ct=new Set(["+","-","*","neg","^"]),ft=2e3;function pt(e){const n=/^(-?)(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/i.exec(e);if(!n)return;const t=n[3]??"";let s=BigInt(n[2]+t),r=t.length-Number(n[4]??0);return r<0&&(s*=10n**BigInt(-r),r=0),{n:n[1]?-s:s,scale:r}}const ht=(e,n)=>{const t=Math.max(e.scale,n.scale);return[e.n*10n**BigInt(t-e.scale),n.n*10n**BigInt(t-n.scale),t]};const dt=4e5,mt=()=>new ne("a number too large to approximate"),gt=e=>e<0n?-e:e;class vt{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 ne("division by zero");return e*this.S/n}sqrt(e){if(e<0n)throw new ne("the square root of a negative number is not real");return ue(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 ne("a series did not converge");return t}atanhInv(e){const n=BigInt(e),t=n*n;let s=this.S/n,r=0n;for(let e=1n;0n!==s;e+=2n)r+=s/e,s/=t;return r}atanInv(e){const n=BigInt(e),t=n*n;let s=this.S/n,r=0n;for(let e=1n,n=1n;0n!==s;e+=2n,n=-n)r+=n*s/e,s/=t;return r}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(dt))throw mt();if(n<-BigInt(dt))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 ne("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),r=this.mul(s,s);let i=s,o=0n;for(let e=1n;0n!==i;e+=2n)o+=i/e,i=this.mul(i,r);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(gt(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,r=0n;for(let e=1n,n=1n;0n!==s;e+=2n,n=-n)r+=n*s/e,s=this.mul(s,t);return 4n*r}asin(e){if(gt(e)>this.S)throw new ne("arcsin of a number beyond ±1 is not real");return gt(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 bt(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 ne("the argument of 0 is undefined");return n>0n?e.pi/2n:-e.pi/2n}const yt={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 ne("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=yt.abs(e,n);if(0n===t)throw new ne("the log of 0 is undefined");return[e.ln(t),bt(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,r=[e.S,0n],i=n;for(;t>0n;)1n&t&&(r=yt.mul(e,r,i)),i=yt.mul(e,i,i),t>>=1n;return s.n<0n?yt.div(e,[e.S,0n],r):r}return yt.exp(e,yt.mul(e,t,yt.ln(e,n)))},sinh:(e,n)=>(e.exp(n)-e.exp(-n))/2n,cosh:(e,n)=>(e.exp(n)+e.exp(-n))/2n},wt={sin:(e,[n,t])=>[e.mul(e.sin(n),yt.cosh(e,t)),e.mul(e.cos(n),yt.sinh(e,t))],cos:(e,[n,t])=>[e.mul(e.cos(n),yt.cosh(e,t)),-e.mul(e.sin(n),yt.sinh(e,t))],tan:(e,n)=>yt.div(e,wt.sin(e,n),wt.cos(e,n)),ln:(e,n)=>yt.ln(e,n),sqrt:(e,n)=>yt.exp(e,yt.mul(e,[e.S/2n,0n],yt.ln(e,n))),sinh:(e,[n,t])=>[e.mul(yt.sinh(e,n),e.cos(t)),e.mul(yt.cosh(e,n),e.sin(t))],cosh:(e,[n,t])=>[e.mul(yt.cosh(e,n),e.cos(t)),e.mul(yt.sinh(e,n),e.sin(t))]},xt=e=>({q:e}),qt=([e,n])=>0n===n?{f:e}:{z:[e,n]};function kt(e,n,t){const s=e=>((e,n)=>n.z??[$t(e,n),0n])(t,n[e]);switch(e.op){case"+":return qt(yt.add(s(0),s(1)));case"-":return qt(yt.sub(s(0),s(1)));case"neg":return qt([-s(0)[0],-s(0)[1]]);case"*":return qt(yt.mul(t,s(0),s(1)));case"/":return qt(yt.div(t,s(0),s(1)));case"^":return qt(yt.pow(t,s(0),s(1),n[1].q));case"sqrt":return qt(wt.sqrt(t,s(0)));case"root":return qt(yt.pow(t,s(1),yt.div(t,[t.S,0n],s(0)),n[0].q?.inv()));case"abs":return{f:yt.abs(t,s(0))};case"arg":return{f:bt(t,s(0)[1],s(0)[0])};case"re":return{f:s(0)[0]};case"im":return{f:s(0)[1]};case"conj":return qt([s(0)[0],-s(0)[1]]);case"log":return qt(yt.div(t,yt.ln(t,s(1)),yt.ln(t,s(0))));default:{const r=wt[e.op];if(!r||1!==n.length)throw new ne(`no complex value for ${e.op}`);return qt(r(t,s(0)))}}}function $t(e,n){return n.q?e.fromQ(n.q):n.f}const St={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(gt(n)<e.S)throw new ne("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(gt(n)<e.S)throw new ne("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 ne("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(gt(n)>=e.S)throw new ne("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 Mt(e,n,t){if("num"===e.type)return xt(ae(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&&pe.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?ae(String(n)):null;if(!s)throw new ne(`the value of ${e.token} is not a number`);return xt(s)}throw new ne(`${e.token} has no value`)}pe.complex&&e.op.startsWith("\\:")&&Ue[e.op.slice(2)]&&(e=U(Ue[e.op.slice(2)],e.args));const s=e.args.map(e=>Mt(e,n,t));if(s.some(e=>e.z)||["re","im","conj","arg"].includes(e.op)||function(e,n){if(!pe.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 kt(e,s,n);const r=s.every(e=>e.q),i=e=>$t(n,s[e]);switch(e.op){case"+":return r?xt(s[0].q.add(s[1].q)):{f:i(0)+i(1)};case"-":return r?xt(s[0].q.sub(s[1].q)):{f:i(0)-i(1)};case"neg":return s[0].q?xt(s[0].q.neg()):{f:-s[0].f};case"*":return r?xt(s[0].q.mul(s[1].q)):{f:n.mul(i(0),i(1))};case"/":return r?xt(s[0].q.div(s[1].q)):{f:n.div(i(0),i(1))};case"^":return Ot(n,s[0],s[1]);case"sqrt":return Ot(n,s[0],xt(oe.HALF));case"root":return Ot(n,s[1],s[0].q?xt(s[0].q.inv()):{f:n.div(n.S,s[0].f)});case"abs":return s[0].q?xt(s[0].q.abs()):{f:gt(s[0].f)};case"floor":return xt(s[0].q?s[0].q.floor():new oe(Nt(s[0].f,n.S)));case"ceil":return xt(s[0].q?s[0].q.ceil():new oe(-Nt(-s[0].f,n.S)));case"log":return{f:n.div(n.ln(i(1)),n.ln(i(0)))};case"atan2":return{f:bt(n,i(0),i(1))};case"max":case"min":if(!s.length)throw new ne(`${e.op} of nothing`);return r?xt(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)=>i(n)).reduce((n,t)=>"max"===e.op?t>n?t:n:t<n?t:n)};case"sum":return r?xt(s.reduce((e,n)=>e.add(n.q),oe.ZERO)):{f:s.reduce((e,n,t)=>e+i(t),0n)};case"prod":return r?xt(s.reduce((e,n)=>e.mul(n.q),oe.ONE)):{f:s.reduce((e,t,s)=>n.mul(e,i(s)),n.S)};case"mean":if(!s.length)throw new ne("mean of nothing");return r?xt(s.reduce((e,n)=>e.add(n.q),oe.ZERO).div(new oe(BigInt(s.length)))):{f:s.reduce((e,n,t)=>e+i(t),0n)/BigInt(s.length)};case"mod":{if(r){if(s[1].q.isZero)throw new ne("mod 0 is undefined");return xt(s[0].q.sub(s[1].q.mul(s[0].q.div(s[1].q).floor())))}const e=i(1);if(0n===e)throw new ne("mod 0 is undefined");return{f:i(0)-n.mul(e,Nt(n.div(i(0),e),n.S)*n.S)}}case"round":{if(!s[1].q?.isInteger)throw new ne("round needs a whole number of places");const e=10n**gt(s[1].q.n),t=s[0].q??new oe(i(0),n.S),r=s[1].q.sign>=0,o=(r?t.mul(new oe(e)):t.div(new oe(e))).add(oe.HALF).floor();return xt(r?o.div(new oe(e)):o.mul(new oe(e)))}case"!":{if(!s[0].q?.isInteger||s[0].q.sign<0)throw new ne("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)&&re(e)>dt)throw mt();return xt(new oe(e))}default:{const t=St[e.op];if(!t||1!==s.length)throw new ne(`no numeric value for ${e.op}`);return{f:t(n,i(0))}}}}const Nt=(e,n)=>{const t=e/n;return e<0n&&t*n!==e?t-1n:t};function Ot(e,n,t){if(t.q&&t.q.isInteger){if(n.q)return xt(n.q.pow(t.q.n));let s=t.q.n;const r=s<0n;r&&(s=-s);let i=e.S,o=n.f;for(;s>0n;){if(1n&s&&(i=e.mul(i,o)),o=e.mul(o,o),re(i)>dt+4*e.P||re(o)>8e5){if(r)return{f:0n};throw mt()}s>>=1n}return{f:r?e.div(e.S,i):i}}const s=$t(e,n);if(0n===s){if(t.q?t.q.sign>0:t.f>0n)return xt(oe.ZERO);throw new ne("0 to a power that is not positive is undefined")}if(s<0n){if(t.q&&t.q.d%2n==1n){const n=Ot(e,{f:-s},t).f;return{f:t.q.n%2n==0n?n:-n}}throw new ne("a negative number to a fractional power is not real")}if(t.q&&1n===gt(t.q.n)&&t.q.d<=64n){const n=ue(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($t(e,t),e.ln(s)))}}function It(e,n,t){const s=e<0n?"-":"",r=gt(e);if(0n===r)return{sign:"",digits:"0",point:1};const i=r.toString(),o=i.length-n.P;let a=i.slice(0,t);i.length>t&&i[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 At({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 Et(e){let n=0n,t=0n,s=e.d;for(;s%2n==0n;)s/=2n,n++;for(;s%5n==0n;)s/=5n,t++;const r=n>t?n:t;let i=gt(e.n)*10n**r/e.d;if(0n===i)return 1;for(;i%10n==0n;)i/=10n;return i.toString().length}function jt(e){let n=e.d;for(;n%2n==0n;)n/=2n;for(;n%5n==0n;)n/=5n;return 1n===n}function Tt(e){const n=/^(-?[\d.]+)e(-?\d+)$/.exec(e);return n?U("*",[W(n[1]),U("^",[W("10"),W(n[2])])]):W(e)}function zt(e,{digits:n=15,scope:t}={}){if(!Number.isInteger(n)||n<1||n>1e5)throw new ne("digits must be a whole number from 1 to 100000");let s=n+25,r=null;for(let i=0;i<4;i++){const o=new vt(s),a=Mt(e,o,t);if(a.z){const e=Ct(a.z,o,n);if(e.retry&&i<3){s+=e.retry;continue}return void 0===e.real?e:Zt(e.real,o,n,null)}if(a.q&&a.q.isInteger&&gt(a.q.n).toString().length<=n)return{text:a.q.n.toString(),node:W(a.q.n.toString()),number:Number(a.q.n),re:Number(a.q.n),im:0,exact:!0};const u=$t(o,a);if(0n===u&&(!a.q||!a.q.isZero)&&i<3){r=null,s*=4;continue}const l=It(u,o,n);if(r&&l.point<-10&&r.point-l.point>=(s-r.P)/2)return{text:"0",node:W("0"),number:0,re:0,im:0,exact:!1};if(!(l.point<-10&&i<3)||r&&r.point===l.point)return Zt(u,o,n,a.q);r={point:l.point,P:s},s+=10-l.point}throw new ne("could not approximate")}function Zt(e,n,t,s){const r=At(It(e,n,t));return{text:r,node:Tt(r),number:Number(r),re:Number(r),im:0,exact:Boolean(s)&&jt(s)&&Et(s)<=t}}function Ct([e,n],t,s){const r=10n**BigInt(Math.max(0,t.P-s-12)),i=e=>gt(e)>r;if(!i(n))return{real:e};const o=It(n,t,s);if(o.point<-10&&i(n))return{retry:10-o.point};const a=At(o),u="1"===a?"i":"-1"===a?"-i":`${a}i`,l="1"===a?D("i"):U("*",[Tt(a.replace(/^-/,"")),D("i")]);if(!i(e))return{text:u,node:a.startsWith("-")?U("neg",[l]):l,number:NaN,re:0,im:Number(a),exact:!1};const c=At(It(e,t,s)),f=a.startsWith("-"),p="1"===a.replace(/^-/,"")?D("i"):U("*",[Tt(a.replace(/^-/,"")),D("i")]);return{text:`${c} ${f?"-":"+"} ${u.replace(/^-/,"")}`,node:U(f?"-":"+",[Tt(c),p]),number:NaN,re:Number(c),im:Number(a),exact:!1}}function Ft(e,n={}){const t=e=>(e=>0===rn(e).size)(e)?"num"===e.type&&/^-?\d+$/.test(e.token)?e:zt(e,n).node:L(e)?U(e.op,e.args.map(t)):e;return t(e)}const Bt={variable:null},Dt=(e,n)=>null!==n&&rn(e).has(n);function Wt(e){if("num"===e.type)return ae(e.token);if(L(e)&&"/"===e.op&&e.args.every(e=>"num"===e.type)){const n=ae(e.args[0].token),t=ae(e.args[1].token);return n&&t&&!t.isZero?n.div(t):null}return null}const Rt=e=>0===rn(e).size;function Pt(e,n,t){const s=function(e){const n=Ke(e);return"num"===n.k?n.q.isZero?n.q:null:"atom"===n.k&&"sym"===n.node.type&&"pi"===n.node.token?ae("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[r,i="1"]=String(n).split("/");return t(s.compare(ae(r).div(ae(i))))}function Ut(e){if(!Rt(e))return NaN;try{const{number:n}=zt(e,{digits:30});return Math.sign(n)}catch{return NaN}}function Vt(){yn("hasVariable")||(vn("hasVariable",e=>Dt(e,Bt.variable),"mentions the variable being solved for"),vn("freeOfVariable",e=>null!==Bt.variable&&!Dt(e,Bt.variable),"does not mention the variable being solved for"),vn("isRational",e=>null!==Wt(e),"an exact number: 3, -2, 1/2"),vn("isWhole",e=>Wt(e)?.isInteger??!1,"a whole number (any size)"),vn("isEvenWhole",e=>{const n=Wt(e);return Boolean(n?.isInteger&&n.n%2n==0n)},"an even whole number"),vn("isOddWhole",e=>{const n=Wt(e);return Boolean(n?.isInteger&&n.n%2n!=0n)},"an odd whole number"),vn("isPositiveRational",e=>(Wt(e)?.sign??0)>0,"an exact number above 0"),vn("isNegativeRational",e=>(Wt(e)?.sign??0)<0,"an exact number below 0"),vn("isConstant",Rt,"has no unknowns (numbers, π and e only)"),vn("notOne",e=>{const n=Wt(e);return!n||!n.isOne},"anything except the number 1"),vn("notMinusOne",e=>{const n=Wt(e);return!n||!n.equals(ae("-1"))},"anything except the number -1"),vn("hasMinusSign",e=>function(e){const n=Ke(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"),vn("piMultipleAtLeast",(e,n)=>Pt(e,n,e=>e>=0),"a multiple of π, at least k·π"),vn("piMultipleAbove",(e,n)=>Pt(e,n,e=>e>0),"a multiple of π, above k·π"),vn("piMultipleBelow",(e,n)=>Pt(e,n,e=>e<0),"a multiple of π, below k·π"),vn("piMultipleAtMost",(e,n)=>Pt(e,n,e=>e<=0),"a multiple of π, at most k·π"),vn("isPositiveConstant",e=>Ut(e)>0,"no unknowns, and above 0 (e, π, √2, 3)"),vn("isNegativeConstant",e=>Ut(e)<0,"no unknowns, and below 0"),vn("hasImaginaryPart",e=>{if(!pe.complex)return!1;const n=We(Ke(e));return Boolean(n)&&!("num"===n.im.k&&n.im.q.isZero)},"complex mode: has a nonzero imaginary part (unknowns count as real)"),vn("isSymbolNode",e=>"sym"===e.type&&!fe.has(e.token),"a single unknown such as x"))}function Lt(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:U(e.op,e.args.map(s)),r=e=>"sym"===e.type?D(`=${e.token}`):"num"===e.type?e:U(e.op,e.args.map(r)),i=e=>"op"!==e.type?e:t(e)?r(Ye(s(e))):U(e.op,e.args.map(i));return i(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 nt.fromSpecs(t,{strict:!0})}function _t(e,n,t,s){return e.explain?e.explain.replace(/\{(\w+)\}/g,(e,r)=>"result"===r?t?s(t):e:n[r]?s(n[r]):e).trim():""}const Ht=e=>L(e)&&("+"===e.op||"-"===e.op),Qt=e=>L(e)&&("*"===e.op||"/"===e.op);function*Jt(e,n,{order:t="pre"}={}){for(const s of ot(e,n,{order:t})){const n=at(s.rule.outputTemplate,s.bound);yield{rule:s.rule,bound:s.bound,path:s.path,before:s.node,after:n,next:()=>Ye(ee(e,s.path,n))}}for(const{node:s,path:r}of G(e,t)){const t=Ht(s);if(!t&&!Qt(s))continue;const i=t?on(Ke(s)):an(Ke(s));if(i.length<3)continue;const o=t?Ee:Te;for(let t=0;t<i.length;t++)for(let s=t+1;s<i.length;s++){const a=nn(o([i[t],i[s]]));for(const u of it(a,n)){const n=at(u.rule.outputTemplate,u.bound),l=i.filter((e,n)=>n!==t&&n!==s);yield{rule:u.rule,bound:u.bound,path:r,before:a,after:n,next:()=>Ye(ee(e,r,nn(o([Ke(n),...l]))))}}}}}function Kt(e,n,{format:t,order:s="pre",maxSteps:r=200,variable:i=null}={}){const o=Bt.variable;Bt.variable=i;try{let i=Ye(e);const o=new Set([i.s]),a=[];for(let e=0;e<r;e++){let e=null;for(const t of Jt(i,n,{order:s})){const n=t.next();if(n.s!==i.s&&!o.has(n.s)){e={c:t,next:n};break}}if(!e)break;const{c:r,next:u}=e;a.push({id:r.rule.id,name:r.rule.name,tags:r.rule.tags,from:i.s,to:u.s,path:r.path,before:r.before.s,after:r.after.s,explanation:_t(r.rule,r.bound,Ye(r.after),t)}),i=u,o.add(i.s)}return{node:i,steps:a}}finally{Bt.variable=o}}const Yt=(e,n)=>e.length>=n.length&&n.every((n,t)=>e[t]===n),Gt=(e,n)=>{for(const t of e)if(n(t))return t;return null};function Xt(e,n,{diff:t}){let s=null;for(;;){const r=Gt(ot(e,t,{order:"pre"}),e=>"d-variable"===e.rule.id&&e.path.length>n.length&&Yt(e.path,n));if(!r)break;s=X(e,r.path).args[1],e=lt(e,r).expr}const r=n.length?n.slice(0,-1):n,i=ss(X(e,r));return i.s!==X(e,r).s&&(e=r.length?ee(e,r,i):i),{expr:e,variable:s}}function es(e){if(!L(e))return e;const n=e.args.map(es),t=e.op.startsWith("\\:")?e.op.slice(2):null;return t&&A(t)&&I(t).arity===n.length?U(t,n):n.every((n,t)=>n===e.args[t])?e:U(e.op,n)}const ns=e=>"op"!==e.type&&"1"===e.s,ts=e=>"op"!==e.type&&"0"===e.s;function ss(e){if(!L(e))return e;const n=e.args.map(ss),[t,s]=n;if("*"===e.op&&2===n.length){if(ns(s))return t;if(ns(t))return s}if("^"===e.op&&2===n.length&&ns(s))return t;if("+"===e.op&&2===n.length){if(ts(s))return t;if(ts(t))return s}return"-"===e.op&&2===n.length&&ts(s)?t:n.every((n,t)=>n===e.args[t])?e:U(e.op,n)}function rs(e,n,{fold:t=null,format:s,maxSteps:r=200,order:i="pre"}={}){let o=e;const a=new Set([o.s]),u=[];for(let e=0;e<r;e++){let e=null;for(const s of ot(o,n,{order:i})){const n=lt(o,s);let r=n.expr,i=null;if(t&&({expr:r,variable:i}=Xt(r,s.path,t)),r.s!==o.s&&!a.has(r.s)){e={m:s,a:n,expr:r,variable:i};break}}if(!e)break;const{m:r,a:l,expr:c,variable:f}=e;let p=r.path;for(;;)try{X(c,p);break}catch{p=p.slice(0,-1)}const h=X(c,p);let d=_t(r.rule,r.bound,Ye(h),s);f&&d&&!d.endsWith("is 1.")&&(d=d.endsWith(`the derivative of ${s(f)}.`)?`${d.slice(0,-1)}, which is 1.`:`${d} The derivative of ${s(f)} is 1.`),u.push({id:r.rule.id,name:r.rule.name,tags:r.rule.tags,from:o.s,to:c.s,path:p,before:l.before.s,after:h.s,explanation:d}),o=c,a.add(o.s)}return{node:o,steps:u}}const is=new Set(["int","der","lim"]),os=e=>L(e)&&("+"===e.op||"-"===e.op),as=e=>L(e)&&"*"===e.op;function us(e,n=1,t=[]){return L(e)&&"+"===e.op?(us(e.args[0],n,t),us(e.args[1],n,t),t):L(e)&&"-"===e.op&&2===e.args.length?(us(e.args[0],n,t),us(e.args[1],-n,t),t):L(e)&&"neg"===e.op?(us(e.args[0],-n,t),t):(t.push({sign:n,node:e}),t)}const ls=(e,n=[])=>as(e)?(ls(e.args[0],n),ls(e.args[1],n),n):(n.push(e),n),cs=e=>e.reduce((e,n)=>null===e?n.sign<0?U("neg",[n.node]):n.node:U(n.sign<0?"-":"+",[e,n.node]),null),fs=e=>{try{return ke(Ke(e))}catch{return e.s}},ps=e=>fs(e.sign<0?U("neg",[e.node]):e.node);function hs(e,n,t,s=t){const r=e.map((e,n)=>({x:e,i:n,k:t(e)})),i=[];let o=null;for(const e of n){const n=r.findIndex(n=>n.k===s(e));n>=0?(i.push({x:r[n].x,from:e}),r.splice(n,1)):null===o&&(o=i.length,i.push(null))}const a=r.map(e=>({x:e.x,from:null}));return null===o?[...i,...a]:[...i.slice(0,o),...a,...i.slice(o+1)]}function ds(e,n,{tidy:t=!1}={}){if(!n||e.s===n.s)return n&&e.s===n.s?n:e;if(os(e)&&os(n)){const s=hs(us(e),us(n),ps),r=us(n).filter(e=>!s.some(n=>n.from===e));return cs(s.map(({x:e,from:n})=>({sign:e.sign,node:ds(e.node,(n??(1===r.length?r[0]:null))?.node,{tidy:t})})))}if(os(e)&&L(n)&&is.has(n.op)&&os(n.args[0])){const t=e=>L(e.node)&&e.node.op===n.op?ps({sign:e.sign,node:e.node.args[0]}):ps(e),s=hs(us(e),us(n.args[0]),t,ps);return cs(s.map(({x:e})=>e))}if(as(e)&&as(n)){if(t)return e;const s=hs(ls(e),ls(n),fs);return s.map(({x:e,from:n})=>ds(e,n)).reduce((e,n)=>null===e?n:U("*",[e,n]),null)}if(L(e)&&L(n)&&e.op===n.op&&e.args.length===n.args.length){const s=e.args.map((e,s)=>ds(e,n.args[s],{tidy:t}));return s.every((n,t)=>n===e.args[t])?e:U(e.op,s)}return e}const ms=new Set(["normal","normal.collect","normal.expand-collect","simplify.cancel","simplify.expand","cancel","expand","together"]),gs=e=>ms.has(e.id)||(e.tags??[]).includes("tidy");function vs(e,n){if(!e.length)return e;let t=n??_(e[0].from);return e.map(e=>{let n,s=t??_(e.from);try{fs(_(e.from))!==fs(t)&&(s=_(e.from)),n=e.to===e.from?s:ds(_(e.to),s,{tidy:gs(e)})}catch(n){if(n instanceof ReferenceError||n instanceof TypeError)throw n;return t=null,e}if(n.s===s.s&&e.to!==e.from&&gs(e))return null;t=n;let r=e.path;return e.before&&e.before!==e.from&&(r=function(e,n){const t=fs(_(n)),s=(e,r)=>{if(e.s===n||fs(e)===t)return r;if(!L(e))return null;for(let n=0;n<e.args.length;n++){const t=s(e.args[n],r.concat(n));if(t)return t}return null};return s(e,[])}(s,e.before)??null),{...e,from:s.s,to:n.s,path:r}}).filter(Boolean)}const bs={full:[],normal:["hidden","detail"],brief:["hidden","detail","minor","tidy","arithmetic","value"]},ys=(e,n)=>"all"===n||"*"===n||Array.isArray(n)&&n.some(n=>n===e.id||e.tags?.includes(n));function ws(e,n,{parse:t,replaceAt:s}){const r=(e,n,t=[])=>{if(e.s===n)return t;if("op"!==e.type)return null;for(let s=0;s<e.args.length;s++){const i=r(e.args[s],n,t.concat(s));if(i)return i}return null},i=(e,n)=>n.reduce((e,n)=>e.args[n],e);let o=n;const a=[];for(const n of e){let e=r(o,n.from);if(!e){try{o=t(n.from)}catch{a.push(n);continue}e=[]}const u=o;if("solve.reject"===n.id){const n=e.slice(0,-1);e.length&&"|"===i(o,n).op&&(o=s(o,n,i(o,n).args[1-e[e.length-1]]))}else if(n.to!==n.from){let r;try{r=t(n.to)}catch{a.push(n);continue}o=e.length?s(o,e,r):r}a.push({...n,from:u.s,to:o.s,path:e.length?[...e,...n.path??[]]:n.path})}return a}const xs=ge(oe.ONE),qs=(e,n)=>"atom"===e.k&&"sym"===e.node.type&&e.node.token===n;function ks(e){switch(e.k){case"num":default:return e;case"atom":return"op"===e.node.type?Qe(e.node.op,e.node.args.map(e=>ks(Ke(e)))):e;case"add":return Ee(on(e).map(ks));case"mul":{let n=[ge(e.c)];for(const t of e.fs){const e=ks(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=$s(n,on(e));else n=$s(n,[Ze(e,t.e)])}return Ee(n)}}}function $s(e,n){const t=[];for(const s of e)for(const e of n)t.push(Te([s,e]));return on(Ee(t))}function Ss(e,n){const t=new Map;for(const s of on(ks(e))){const{coef:e,rest:r}=Ae(s);let i=0;const o=[ge(e)];for(const e of r?an(r):[]){const{b:t,e:s}="mul"===e.k&&1===e.fs.length&&e.c.isOne?e.fs[0]:{b:e,e:xs};if(qs(t,n)){if(!we(s)||!s.q.isInteger||s.q.sign<0)return null;i+=Number(s.q.n)}else{if(Ms(t,n)||Ms(s,n))return null;o.push(e)}}t.set(i,Ee([t.get(i)??ge(oe.ZERO),Te(o)]))}for(const[e,n]of t)we(n)&&n.q.isZero&&t.delete(e);return t}const Ms=(e,n)=>rn(nn(e)).has(n);function Ns(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)??ge(oe.ZERO);if(!we(n))return null;t.push(n.q)}return t}function Os(e,n){const t=Ke(D(n));return Ee(e.map((e,n)=>Te([ge(e),ze(t,ge(oe.of(n)))])))}const Is=e=>{const n=e.slice();for(;n.length>1&&n[n.length-1].isZero;)n.pop();return n},As=(e,n)=>e.reduceRight((e,t)=>e.mul(n).add(t),oe.ZERO);function Es(e,n){const t=e.length-1,s=new Array(t);let r=oe.ZERO;for(let i=t;i>=1;i--)r=e[i].add(r.mul(n)),s[i-1]=r;return s}function js(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 r of s)for(let s=0,i=1n;s<=t;s++,i*=e)n.push(r*i);if(s=n,s.length>2e4)return null}return s.sort((e,n)=>e<n?-1:e>n?1:0)}function Ts(e){let n=Is(e);const t=[];for(;n.length>1&&n[0].isZero;)t.push(oe.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),r=n.map(e=>e.n*s/e.d),i=js(r[0]),o=js(r[r.length-1]);if(!i||!o)return{roots:t,rest:n};const a=new Map;for(const e of i)for(const n of o)for(const t of[1n,-1n]){const s=new oe(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&&As(n,e).isZero;)t.push(e),n=Es(n,e);return{roots:t.sort((e,n)=>e.compare(n)),rest:n}}function zs(e,n){const t=Is(n);let s=Is(e);const r=t[t.length-1];if(r.isZero)throw new ne("division by the zero polynomial");const i=new Array(Math.max(1,s.length-t.length+1)).fill(oe.ZERO);for(;s.length>=t.length&&(1!==s.length||!s[0].isZero);){const e=s.length-t.length,n=s[s.length-1].div(r);if(i[e]=n,s=Is(s.map((s,r)=>r>=e&&r-e<t.length?s.sub(n.mul(t[r-e])):s)),s.length-1<e+t.length-1&&s[s.length-1].isZero)break;if(s.length<t.length)break}return{q:Is(i),r:s}}function Zs(e){if("num"===e.k)return{coef:e.q,factors:[],notes:[]};if("atom"===e.k)return{coef:oe.ONE,factors:[{base:e,exp:xs}],notes:[]};if("mul"===e.k){let n=e.c;const t=[],s=[];for(const r of e.fs)if("add"===r.b.k&&we(r.e)&&r.e.q.isInteger){const e=Zs(r.b);n=n.mul(e.coef.pow(r.e.q.n));for(const n of e.factors)t.push({base:n.base,exp:Te([n.exp,r.e])});s.push(...e.notes)}else t.push({base:r.b,exp:r.e});return Cs(n,t,s)}return Bs(e)}function Cs(e,n,t){const s=new Map;for(const e of n){const n=ke(e.base),t=s.get(n);t?t.exp=Ee([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 Fs=e=>Ae(on(e)[0]).coef.sign;function Bs(e){const n=on(e),t=[],s=n.map(e=>{const{coef:n,rest:t}=Ae(e);return{coef:n,fs:t?an(t).map(Ds):[]}}),r=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 i=new oe(r.n||1n,r.d);Fs(e)<0&&(i=i.neg());const o=[];for(const e of s[0].fs){if(!we(e.e)){const n=ke(e.b),t=ke(e.e);s.slice(1).every(e=>e.fs.some(e=>ke(e.b)===n&&ke(e.e)===t))&&o.push({base:e.b,exp:e.e});continue}if(e.e.q.sign<=0)continue;let n=e.e.q;const t=ke(e.b);let r=!0;for(const e of s.slice(1)){const s=e.fs.find(e=>ke(e.b)===t&&we(e.e)&&e.e.q.sign>0);if(!s){r=!1;break}s.e.q.compare(n)<0&&(n=s.e.q)}r&&o.push({base:e.b,exp:ge(n)})}let a=e;if(!i.isOne||o.length){const e=Te([ge(i),...o.map(e=>Ze(e.base,e.exp))]);a=Ee(n.map(n=>Te([n,ze(e,ge(oe.MINUS_ONE))]))),t.push({id:"factor.common",values:{common:e}})}const u="add"===a.k&&ke(a)!==ke(e),l="add"!==a.k?Zs(a):u?Bs(a):function(e,n){const t=[...Ws(e)];for(const s of t){const r=Ns(Ss(e,s));if(!r||r.length<3)continue;if(1!==t.length)break;const{roots:i,rest:o}=Ts(r);if(!i.length)break;const a=[];let u=o[o.length-1]??oe.ONE;const l=o.map(e=>e.div(u)),c=[...i].sort((e,n)=>e.abs().compare(n.abs())||n.sign-e.sign);for(const e of c){const t=Os([new oe(-e.n),new oe(e.d)],s);a.push({base:t,exp:xs}),u=u.div(new oe(e.d)),n.push({id:"factor.root",values:{root:ge(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 oe(e))),t=n.reduce((e,n)=>ie(e,n.n),0n)||1n;u=u.mul(new oe(t,e)),a.push({base:Os(n.map(e=>e.div(new oe(t))),s),exp:xs})}return Cs(u,a,[])}const s=on(e);if(2===s.length){const[e,t]=s;for(const s of[2,3]){const r=Rs(e,s),i=Rs(Ve(t),s),o=3===s?Rs(t,s):null;if(r&&i&&2===s){n.push({id:"factor.squares",values:{a:r,b:i}});const e=Zs(Ee([r,Ve(i)])),t=Zs(Ee([r,i]));return Cs(e.coef.mul(t.coef),[...e.factors,...t.factors],[...e.notes,...t.notes])}if(3===s&&r&&(i||o)){const e=i??o,t=i?-1:1;n.push({id:t<0?"factor.cubes-difference":"factor.cubes-sum",values:{a:r,b:e}});const s=Ee(t<0?[r,Ve(e)]:[r,e]),a=Ee([ze(r,ge(oe.of(2))),t<0?Te([r,e]):Ve(Te([r,e])),ze(e,ge(oe.of(2)))]),u=Zs(s);return Cs(u.coef,[...u.factors,{base:a,exp:xs}],u.notes)}}}return{coef:oe.ONE,factors:[{base:e,exp:xs}],notes:[]}}(a,t);if(u&&t.length){const e=l.notes.findIndex(e=>"factor.common"===e.id);e>=0&&(t[0].values.common=Te([t[0].values.common,l.notes.splice(e,1)[0].values.common]))}return Cs(i.mul(l.coef),[...o,...l.factors],[...t,...l.notes.filter(e=>!t.includes(e))])}const Ds=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length?{b:e.fs[0].b,e:e.fs[0].e}:{b:e,e:xs},Ws=e=>rn(nn(e));function Rs(e,n){const{coef:t,rest:s}=Ae(e);if(t.sign<0)return null;const r=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 r=(t+s)/2n;r**BigInt(n)<=e?t=r:s=r}return t**BigInt(n)===e?t:null},s=t(e.n),r=t(e.d);return null!==s&&null!==r?new oe(s,r):null}(t,n);if(!r)return null;const i=[ge(r)];for(const e of s?an(s).map(Ds):[]){if(!we(e.e))return null;const t=e.e.q.div(oe.of(n));if(!t.isInteger)return null;i.push(Ze(e.b,ge(t)))}return Te(i)}function Ps({coef:e,factors:n}){const t=[],s=[];for(const e of n){const n=we(e.exp)&&e.exp.q.sign<0,r=n?ge(e.exp.q.neg()):e.exp,i=nn(Ze(e.base,r));(n?s:t).push(i)}const r=e=>e.reduce((e,n)=>e?U("*",[e,n]):n,null),i=e.n<0n?-e.n:e.n;let o=t.length?r(1n===i?t:[nn(ge(new oe(i))),...t]):nn(ge(new oe(i)));return e.n<0n&&(o=U("neg",[o])),1n!==e.d&&s.unshift(nn(ge(new oe(e.d)))),s.length?U("/",[o,r(s)]):o}function Us(e){if("mul"!==e.k||!e.fs.some(e=>"add"===e.b.k&&we(e.e)&&e.e.q.isInteger))return function(e){if("mul"!==e.k)return{num:e,den:xs};const n=[ge(new oe(e.c.n))],t=[ge(new oe(e.c.d))];for(const s of e.fs)we(s.e)&&s.e.q.sign<0?t.push(Ze(s.b,ge(s.e.q.neg()))):n.push(Ze(s.b,s.e));return{num:Te(n),den:Te(t)}}(e);const n=[ge(new oe(e.c.n))],t=[ge(new oe(e.c.d))];for(const s of e.fs){const e=we(s.e)&&s.e.q.sign<0,r=e?ge(s.e.q.neg()):s.e,i="add"===s.b.k&&we(s.e)&&s.e.q.isInteger?Vs(s.b):null;!i||we(i.den)&&i.den.q.isOne?(e?t:n).push(Ze(s.b,r)):((e?t:n).push(Ze(i.num,r)),(e?n:t).push(Ze(i.den,r)))}return{num:Te(n),den:Te(t)}}function Vs(e){if("add"!==e.k)return Us(e);const n=on(e).map(Us),t=new Map;let s=1n;for(const e of n){const{coef:n,rest:r}=Ae(e.den);s=s*n.n/ie(s,n.n);for(const e of r?an(r).map(Ds):[]){const n=ke(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 r=Te([ge(new oe(s)),...[...t.values()].map(e=>Ze(e.b,e.e))]);if(we(r)&&r.q.isOne)return{num:e,den:xs};return{num:ks(Ee(n.map(e=>Te([e.num,r,ze(e.den,ge(oe.MINUS_ONE))])))),den:r}}function Ls(e){const{num:n,den:t}=Vs(e);if(we(t)&&t.q.isOne)return null;const s=Zs(t),r=e=>{const n=new Set(e.factors.map(e=>ke(e.base))),t=s.factors.filter(e=>n.has(ke(e.base))),r=[...e.factors,...s.factors.map(e=>({base:e.base,exp:Ve(e.exp)}))];return{...Cs(e.coef.div(s.coef),r,[...e.notes,...s.notes]),canceled:t.map(e=>e.base)}},i=r(Zs(n)),o="add"===n.k?ks(n):n;if(ke(o)===ke(n))return i;const a=r(Zs(o));return J(Ps(a))<J(Ps(i))?a:i}const _s=(e,n)=>U("=",[e,n]),Hs=Ye(U("+",[D("x"),U("neg",[D("x")])])),Qs=e=>L(e)&&"="===e.op;function Js(e,n,t,s={}){const r=[],i=(n,t,s,i,o,a={})=>r.push(e.step(n,t,s,i,o,a));i.raw=e=>r.push(e);const o=Qs(n)?n:_s(n,Hs),a=_s(Ye(o.args[0]),Ye(o.args[1]));a.s!==o.s&&i("normal","Work out each side",["tidy","arithmetic"],o,a);const u=[],l=[],c=new Set;u.numeric=c,tr(e,a,t,s,i,u,l,0);const f=[],p=new Set,h=n=>rn(n).size&&e.simplify?e.simplify(n,{steps:!1}).result:Kt(n,e.set.view("simplify"),{format:e.format}).node,d=new Map;for(const e of u){const n=c.has(e)?e:h(e),s=n.s;if(p.has(s))continue;p.add(s);const r=c.has(e)?null:Xs(o,t,n);r?i("solve.reject","Check the answer",["check"],_s(D(t),n),_s(D(t),n),{value:n,reason:r}):(u.periodOf?.has(e)&&d.set(n,u.periodOf.get(e)),f.push(n))}if(f.sort(Ys),s.interval){const n=function(e,n,t,[s,r],i,o,a){const u=Ye(e.node(s)),l=Ye(e.node(r)),c=Gs(u),f=Gs(l);if(!c||!f||Math.abs(c.im)>1e-12||Math.abs(f.im)>1e-12)throw new ne("the interval is two numbers, lo and hi");if(c.re>f.re)throw new ne("the interval starts after it ends");const p=e=>e>=c.re-1e-9&&e<=f.re+1e-9,h=[],d=new Set,m=e=>{d.has(e.s)||(d.add(e.s),h.push(e))};let g=null;for(const e of n){const n=Gs(e);if(!n||Math.abs(n.im)>1e-12)continue;const s=t.get(e);if(void 0===s){p(n.re)&&m(e);continue}if(null===s){g=[o],p(n.re)&&m(e);continue}const r=Gs(s).re,u=Math.ceil((c.re-n.re)/r-1e-9),l=Math.floor((f.re-n.re)/r+1e-9);if(l-u+1>Ks)throw new ne(`more than ${Ks} answers in that interval`);for(let n=u;n<=l;n++){const t=0===n?e:i(nn(Ee([Ke(e),Te([ge(oe.of(n)),Ke(s)])])));Xs(o,a,t)||m(t)}}return h.sort(Ys),{values:h,lo:u,hi:l,uneven:g}}(e,f,d,s.interval,e=>h(e),o,t);return n.uneven&&l.push(...n.uneven),{solutions:n.values,base:f,unsolved:l,steps:r,always:l.some(e=>e.always),periodic:!1,period:null,interval:[n.lo,n.hi]}}const m=u.periods??[],g=f.length&&m.length&&m.every(e=>e&&e.s===m[0].s)?m[0]:null;return{solutions:f,unsolved:l,steps:r,always:l.some(e=>e.always),periodic:m.length>0&&f.length>0,period:g}}const Ks=200;function Ys(e,n){const t=Gs(e),s=Gs(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 Gs(e){if(rn(e).size)return null;try{const{re:n,im:t}=zt(e,{digits:20});return{re:n,im:t}}catch{return null}}function Xs(e,n,t){const[s,r]=e.args,i=new Set([...rn(s),...rn(r),...rn(t)]);if(i.delete(n),i.size)return null;const o=e=>er(e,n,t);try{const e=zt(o(s),{digits:40}),n=zt(o(r),{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 er(e,n,t){return"sym"===e.type?e.token===n?t:e:L(e)?U(e.op,e.args.map(e=>er(e,n,t))):e}const nr=24;function tr(e,n,t,s,r,i,o,a){if(a>nr)return hr(e,n,t,s,r,i,o);const u=function(e){const n=[],t=e=>{if(L(e)&&"|"===e.op)return void e.args.forEach(t);if(!Qs(e))return void n.push(e);const s=e.args[1],r=G(s,"pre").find(({node:e})=>L(e)&&"pm"===e.op);if(!r)return void n.push(e);const i=r.node.args[0],o=Ye(ee(s,r.path,i)),a=Ye(ee(s,r.path,U("neg",[i])));t(_s(e.args[0],o)),a.s!==o.s&&t(_s(e.args[0],a))};return t(e),n}(n);if(u.length>1){r("solve.split","Two cases",["split","minor"],n,u.reduce((e,n)=>e?U("|",[e,n]):n,null));for(const n of u)tr(e,n,t,s,r,i,o,a+1);return}if(1===u.length&&u[0].s!==n.s)return tr(e,u[0],t,s,r,i,o,a+1);const[l,c]=n.args;if("sym"===l.type&&l.token===t&&!Ms(Ke(c),t))return void i.push(c);const f=Ee([Ke(l),Ve(Ke(c))]);if(!Ms(f,t))return we(f)&&f.q.isZero?(r("solve.always","Always true",["check"],n,n,{v:t}),void o.push(Object.assign(Object.create(n),{always:!0}))):void r("solve.never","No solution",["check"],n,n,{v:t});const p=on(f).filter(e=>Ms(e,t)),h=on(f).filter(e=>!Ms(e,t)),d=Ee(p),m=Ve(Ee(h));if(pe.complex){const u=Ss(f,t);if(u&&[...u.values()].every(e=>!Ms(e,t))&&Math.max(...u.keys())>=2){const l=_s(nn(f),Hs);return l.s!==n.s&&r("solve.one-side","Everything on one side",["move","minor"],n,l,{v:t}),ur(e,f,u,t,s,r,i,o,a,l)}}if(1===p.length)return sr(e,n,d,m,t,s,r,i,o,a);const g=_s(nn(f),Hs),v=Ss(f,t);if(v&&[...v.values()].every(e=>!Ms(e,t))&&Math.max(...v.keys())>=2)return g.s!==n.s&&r("solve.one-side","Everything on one side",["move","minor"],n,g,{v:t}),ur(e,f,v,t,s,r,i,o,a,g);if(v&&1===Math.max(...v.keys())&&[...v.values()].every(e=>!Ms(e,t))){const u=v.get(1),l=Te([u,Ke(D(t))]),c=Ve(v.get(0)??ge(oe.ZERO)),f=_s(nn(l),nn(c));return r("solve.collect","Collect the terms",["move","minor"],n,f,{v:t,a:nn(u)}),sr(e,f,l,c,t,s,r,i,o,a)}const b=Zs(f),y=b.factors.filter(e=>(Ms(e.base,t)||Ms(e.exp,t))&&!(we(e.exp)&&e.exp.q.sign<0));if(y.length>=2||1===y.length&&b.factors.length>1){const u=_s(Ps(b),Hs);g.s!==n.s&&r("solve.one-side","Everything on one side",["move","minor"],n,g,{v:t}),u.s!==g.s&&r("solve.factor","Factor",["factor"],g,u,{});const l=y.filter(e=>rr(Ze(e.base,e.exp)));if(l.length){const n=y.filter(e=>!l.includes(e)),c=_s(n.length?Ps({coef:oe.ONE,factors:n}):nn(ge(oe.ONE)),Hs);return r("solve.never-zero","A factor that is never zero",["move"],u,c,{f:nn(Te(l.map(e=>Ze(e.base,e.exp))))}),n.length?1===n.length?tr(e,_s(nn(n[0].base),Hs),t,s,r,i,o,a+1):tr(e,c,t,s,r,i,o,a+1):void r("solve.never","No solution",["check"],c,c,{v:t})}const c=y.map(e=>_s(nn(e.base),Hs));c.length>1&&r("solve.zero-product","A product is zero when a factor is",["split"],u,c.reduce((e,n)=>e?U("|",[e,n]):n,null),{});for(const n of c)tr(e,n,t,s,r,i,o,a+1);return}const w=Vs(f);if(Ms(w.den,t)){const u=_s(nn(w.num),Hs);return r("solve.clear-denominator","Clear the denominator",["move"],n,u,{den:nn(w.den)}),tr(e,u,t,s,r,i,o,a+1)}const x=p.filter(e=>!ar(e,t));if(1===x.length&&/\b(sqrt|root|abs)\b/.test(nn(x[0]).s))return sr(e,n,x[0],Ve(Ee(on(f).filter(e=>e!==x[0]))),t,s,r,i,o,a);const q=function(e,n){let t=null,s=null,r=null;for(const i of on(e)){const e=an(i).map(nn),o=e.filter(e=>Ms(Ke(e),n));if(1!==o.length||!L(o[0])||!["sin","cos"].includes(o[0].op))return null;const a=o[0].args[0];if(r&&a.s!==r.s)return null;r=a;const u=Te(e.filter(e=>e!==o[0]).map(Ke));"sin"===o[0].op?t=t?Ee([t,u]):u:s=s?Ee([s,u]):u}return!t||!s||we(t)&&t.q.isZero?null:{a:t,b:s,u:r}}(f,t);if(q){const u=_s(U("tan",[q.u]),nn(Ve(Le(q.b,q.a))));return g.s!==n.s&&r("solve.one-side","Everything on one side",["move","minor"],n,g,{v:t}),r("solve.sin-cos","Divide by the cosine",["trig"],g,u,{u:q.u}),tr(e,u,t,s,r,i,o,a+1)}const k=function(e,n){const t=nn(e),s={sin:new Set,cos:new Set};let r=null,i=!0;const o=(e,t)=>{if(L(e)){if(("sin"===e.op||"cos"===e.op)&&rn(e).has(n)){r&&e.args[0].s!==r.s&&(i=!1),r=e.args[0];const n=t&&"^"===t.op&&t.args[0]===e?nn(Ke(t.args[1])):null;return void s[e.op].add(n&&we(Ke(n))&&Ke(n).q.isInteger&&Ke(n).q.n%2n==0n?"even":"odd")}["tan","sec","csc","cot"].includes(e.op)&&rn(e).has(n)&&(i=!1);for(const n of e.args)o(n,e)}};if(o(t,null),!(i&&r&&s.sin.size&&s.cos.size))return null;const a=s.cos.has("odd")?s.sin.has("odd")?null:"sin":"cos";if(!a)return null;const u="cos"===a?"sin":"cos",l=e=>{if(!L(e))return e;if("^"===e.op&&L(e.args[0])&&e.args[0].op===a&&e.args[0].args[0].s===r.s){const n=Ke(e.args[1]).q.div(oe.of(2));return U("^",[U("-",[nn(ge(oe.ONE)),U("^",[U(u,[r]),nn(ge(oe.of(2)))])]),nn(ge(n))])}return U(e.op,e.args.map(l))};return{E:ks(Ke(l(t))),u:r,from:a,to:u}}(f,t);if(k)return g.s!==n.s&&r("solve.one-side","Everything on one side",["move","minor"],n,g,{v:t}),r("solve.pythagorean","Use sin² + cos² = 1",["trig"],g,_s(nn(k.E),Hs),{u:k.u,from:D(k.from),to:D(k.to),fromName:D("sin"===k.from?"sine":"cosine"),toName:D("sin"===k.to?"sine":"cosine")}),tr(e,_s(nn(k.E),Hs),t,s,r,i,o,a+1);const $=function(e,n){const t=nn(e),s=new Map;for(const{node:e}of G(t,"pre"))if(L(e)&&rn(e).has(n))if("^"!==e.op||rn(e.args[0]).has(n))(["ln","sqrt","abs"].includes(e.op)&&e.args[0].s===n||["sin","cos","tan"].includes(e.op)&&rn(e.args[0]).has(n))&&s.set(e.s,e);else{const t=Ke(e.args[1]),{coef:r,rest:i}=Ae(t);if(i&&r.isInteger&&nn(i).s===n){const t=nn(ze(Ke(e.args[0]),Ke(D(n))));s.set(t.s,t)}}const r="u"===n?"w":"u";for(const e of s.values()){const s=pr(t,e,n,r);if(!s||rn(s).has(n))continue;const i=Ke(s),o=Ss(i,r);if(o&&Math.max(...o.keys())>=1)return{kernel:Ke(e),poly:i,symbol:r}}return null}(f,t);if($){const n=$.symbol;r("solve.substitute","Substitute",["substitute"],g,_s(nn($.poly),Hs),{u:D(n),kernel:nn($.kernel)});const u=[];tr(e,_s(nn($.poly),Hs),n,s,r,u,o,a+1);for(const l of u){const u=_s(nn($.kernel),l);r("solve.back","Substitute back",["substitute"],_s(D(n),l),u,{u:D(n),kernel:nn($.kernel)}),tr(e,u,t,s,r,i,o,a+1)}return}return hr(e,g,t,s,r,i,o)}function sr(e,n,t,s,r,i,o,a,u,l){let c=_s(nn(t),nn(s));c.s!==n.s&&o("solve.move","Move the terms",["move","minor"],n,c,{v:r});const{coef:f,rest:p}=Ae(t),h=p?an(p):[],d=Te([ge(f),...h.filter(e=>!Ms(e,r))]);if(!we(d)||!d.q.isOne){const e=Te(h.filter(e=>Ms(e,r))),n=_s(nn(e),nn(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","minor"],c,n,{by:nn(t?ge(d.q.inv()):d),v:r}),c=n}if("sym"===c.args[0].type&&c.args[0].token===r)return void a.push(c.args[1]);const m=Ke(c.args[1]);if(we(m)&&m.q.isZero){const n=Ke(c.args[0]),t=an(n).filter(e=>Ms(e,r)&&!ir(e)&&!rr(e)),s=an(n).filter(e=>Ms(e,r)&&!ir(e)&&rr(e));if(s.length&&t.length){const n=_s(nn(Te(t)),Hs);return o("solve.never-zero","A factor that is never zero",["move"],c,n,{f:nn(Te(s))}),tr(e,n,r,i,o,a,u,l+1)}if(s.length&&!an(n).some(e=>Ms(e,r)&&ir(e)))return void o("solve.never","No solution",["check"],c,c,{v:r});if(!t.length&&an(n).some(e=>Ms(e,r)))return void o("solve.never","No solution",["check"],c,c,{});if(t.length>1||t.length<an(n).filter(e=>Ms(e,r)).length){const n=t.map(e=>_s(nn(or(e)),Hs));o("solve.zero-product","A product is zero when a factor is",["split"],c,n.reduce((e,n)=>e?U("|",[e,n]):n,null),{});for(const t of n)tr(e,t,r,i,o,a,u,l+1);return}}const g=Kt(c,e.set.view("isolate"),{format:e.format,maxSteps:1,variable:r});if(g.steps.length){const n=function(e,n,t,s){const r=(e.tags??[]).find(e=>"period-2pi"===e||"period-pi"===e);if(!r)return;s.periods??=[];const i=n.args[0].args?.[0];let o=null;try{const e=i?Ss(ks(Ke(i)),t):null,n=e&&[...e.keys()].every(e=>0===e||1===e)?e.get(1):null;n&&!Ms(n,t)&&we(n)&&!n.q.isZero&&(o=nn(Te([ge(new oe("period-2pi"===r?2n:1n,1n).div(n.q.abs())),Ke(D("pi"))])))}catch{}return s.periods.push(o),o}(g.steps[0],c,r,a);!function(e,n){for(const t of n)e.raw(t)}(o,g.steps);const t=a.length;if(tr(e,g.node,r,i,o,a,u,l+1),void 0!==n){a.periodOf??=new Map;for(const e of a.slice(t))a.periodOf.has(e)||a.periodOf.set(e,n)}return}const v=an(Ke(c.args[0])).filter(e=>Ms(e,r)&&ir(e));if(v.length&&(!we(m)||!m.q.isZero)){const n=ze(Te(v),ge(oe.MINUS_ONE)),t=_s(nn(Te([Ke(c.args[0]),n])),nn(ks(Te([m,n]))));return o("solve.clear-denominator","Clear the denominator",["move"],c,t,{den:nn(n)}),tr(e,t,r,i,o,a,u,l+1)}const b=Ke(c.args[0]),y=ks(b),w=ke(y)!==ke(b)?Ss(y,r):null;if(w&&[...w.values()].every(e=>!Ms(e,r))&&on(y).length>1){const n=_s(nn(y),c.args[1]);return o("solve.expand","Multiply out",["expand"],c,n,{v:r}),tr(e,n,r,i,o,a,u,l+1)}return hr(e,c,r,i,o,a,u)}function rr(e){const n=nn(e);if(!L(n)||"^"!==n.op)return!1;const t=Ke(n.args[0]);return"sym"===t.type&&("e"===t.token||"=e"===t.token)||we(t)&&t.q.sign>0||"e"===nn(t).s}const ir=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&we(e.fs[0].e)&&e.fs[0].e.q.sign<0,or=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,ar=(e,n)=>{const t=Ss(e,n);return Boolean(t)&&[...t.values()].every(e=>!Ms(e,n))};function ur(e,n,t,s,r,i,o,a,u,l){const c=Math.max(...t.keys()),f=Ns(t);if(pe.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=ze(ge(n.abs()),ge(new oe(1n,BigInt(c)))),r=[];for(let s=0;s<c;s++){const i=Te([ge(new oe(BigInt((n.sign<0?1:0)+2*s),BigInt(c))),Ke(D("pi"))]),o=U("*",[nn(t),U("+",[U("cos",[nn(i)]),U("*",[D("i"),U("sin",[nn(i)])])])]);r.push(Kt(o,e.set.view("simplify"),{format:e.format}).node)}return i("solve.roots","All n roots",["complex"],l,r.map(e=>_s(D(s),e)).reduce((e,n)=>e?U("|",[e,n]):n),{v:s,n:String(c),last:String(c-1),r:nn(ge(n))}),void o.push(...r)}if(cr(t)===c/2&&c>=4)return fr(e,t,c/2,s,r,i,o,a,u,l);if(f){const{roots:t}=Ts(f);if(t.length){const t=Zs(n),c=_s(Ps(t),Hs);if(t.factors.length>1||t.factors.some(e=>!(we(e.exp)&&e.exp.q.isOne))){i("solve.factor","Factor",["factor"],l,c,{});const n=t.factors.filter(e=>Ms(e.base,s)).map(e=>_s(nn(e.base),Hs));n.length>1&&i("solve.zero-product","A product is zero when a factor is",["split"],c,n.reduce((e,n)=>e?U("|",[e,n]):n,null),{});for(const t of n)tr(e,t,s,r,i,o,a,u+1);return}}}const p=cr(t);if(p>=2&&c>2&&c/p<=4)return fr(e,t,p,s,r,i,o,a,u,l);if(2===c){const e=t.get(2),n=t.get(1)??ge(oe.ZERO),r=t.get(0)??ge(oe.ZERO),a=Ee([ze(n,ge(oe.of(2))),Te([ge(oe.of(-4)),e,r])]);if(we(a)&&a.q.sign<0&&!pe.complex)return void i("solve.no-real","No real solutions",["quadratic"],l,l,{D:nn(a)});const u=Te([ge(oe.of(2)),e]),c=ze(a,ge(oe.HALF)),f=nn(Le(Ee([Ve(n),c]),u)),p=nn(Le(Ee([Ve(n),Ve(c)]),u)),h=f.s===p.s?_s(D(s),f):U("|",[_s(D(s),f),_s(D(s),p)]);return i(pe.complex&&we(a)&&a.q.sign<0?"solve.quadratic-complex":"solve.quadratic","The quadratic formula",["quadratic"],l,h,{a:nn(e),b:nn(n),c:nn(r),D:nn(a),root:nn(c),v:s}),o.push(f),void(p.s!==f.s&&o.push(p))}return hr(e,l,s,r,i,o,a)}const lr=(e,n)=>n?lr(n,e%n):e,cr=e=>[...e.keys()].filter(e=>e>0).reduce((e,n)=>lr(e,n),0);function fr(e,n,t,s,r,i,o,a,u,l){const c="u"===s?"w":"u",f=ze(Ke(D(s)),ge(oe.of(t))),p=Ee([...n.entries()].map(([e,n])=>Te([n,ze(Ke(D(c)),ge(oe.of(e/t)))])));i("solve.substitute","Substitute",["substitute"],l,_s(nn(p),Hs),{u:D(c),kernel:nn(f)});const h=[];tr(e,_s(nn(p),Hs),c,r,i,h,a,u+1);for(const n of h){const t=_s(nn(f),n);i("solve.back","Substitute back",["substitute"],_s(D(c),n),t,{u:D(c),kernel:nn(f)}),tr(e,t,s,r,i,o,a,u+1)}}function pr(e,n,t,s){if(e.s===n.s)return D(s);if(!L(e))return e;if("^"===e.op&&"^"===n.op&&e.args[0].s===n.args[0].s){const n=Ke(e.args[1]),{coef:r,rest:i}=Ae(n);if(i&&nn(i).s===t&&r.isInteger)return U("^",[D(s),nn(ge(r))])}return U(e.op,e.args.map(e=>pr(e,n,t,s)))}function hr(e,n,t,s,r,i,o){if(s.approximate){const e="number"==typeof s.approximate?s.approximate:15,o=Ke(U("-",[n.args[0],n.args[1]])),a=pe.complex?Ns(Ss(o,t)):null,u=a&&a.length>2?function(e,n){const t=e.length-1,s=e[t],r=e.map(e=>e/s),i=(e,n)=>{let s=1,i=0;for(let o=t-1;o>=0;o--)[s,i]=[s*e-i*n+r[o],s*n+i*e];return[s,i]};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],r)=>{let[a,u]=i(n,s);for(let e=0;e<t;e++){if(e===r)continue;const t=n-o[e][0],i=s-o[e][1],l=t*t+i*i;[a,u]=[(a*t+u*i)/l,(u*t-a*i)/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=dr(e);if(0===n)return t;const s=U("*",[dr(Math.abs(n)),D("i")]);return 0===e?n<0?U("neg",[s]):s:U(n<0?"-":"+",[t,s])})}(a.map(e=>e.toNumber()),Math.min(e,14)):function(e,n,t){const s=Ke(U("-",[e.args[0],e.args[1]])),r=nn(s),i=e=>{try{return zt(er(r,n,mr(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],r=i(n);const u=i(s);if(Number.isNaN(r)||Number.isNaN(u))continue;if(0===r){o.push(mr(n));continue}if(r*u>0)continue;for(let e=0;e<200&&s-n>1e-16*Math.abs(n);e++){const e=(n+s)/2,t=i(e);if(Number.isNaN(t))break;r*t<=0?s=e:(n=e,r=t)}const l=(n+s)/2;Math.abs(i(l))<1e-6&&o.push(mr(Number(l.toPrecision(Math.min(t,15)))))}return o}(n,t,e);for(const e of u)i.numeric?.add(e);return r("solve.numeric","Numeric solutions",["numeric"],n,u.length?u.map(e=>_s(D(t),e)).reduce((e,n)=>e?U("|",[e,n]):n):n,{v:t,count:String(u.length)}),void i.push(...u)}r("solve.unsolved","No exact method",["unsolved"],n,n,{v:t}),o.push(n)}const dr=e=>W(String(e).includes("e")?e.toFixed(20):String(e)),mr=e=>W(Number.isInteger(e)?String(e):e.toFixed(17)),gr=["first","second","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth"];const vr=()=>W("1"),br={"<":e=>e<0,">":e=>e>0,"≤":e=>e<=0,"≥":e=>e>=0},yr=new Set(["sin","cos","tan","csc","sec","cot"]);function wr(e,n,t,s={}){const r=[],i=[],o=[];let a=n;for(;L(a.args[0])&&br[a.args[0].op];)o.unshift({op:a.op,right:a.args[1]}),a=a.args[0];const u=[a.args[0],a.args[1],...o.map(e=>e.right)];[a.op,...o.map(e=>e.op)].forEach((e,n)=>i.push({h:Ye(U("-",[u[n],u[n+1]])),op:e}));const l=new Set(i.flatMap(e=>[...rn(e.h)]));if(l.delete(t),l.size)throw new ne(`an inequality in ${t} with other unknowns (${[...l].join(", ")}) can't be charted`);const c=s.interval?s.interval.map(n=>Ye(e.node(n))):null;if(!c&&i.some(e=>G(e.h,"pre").some(({node:e})=>L(e)&&yr.has(e.op)&&rn(e).has(t))))return{pieces:null,steps:r,unsolved:!0};const f=[];for(const{h:e}of i){f.push(e);for(const{node:n}of G(e,"pre"))L(n)&&rn(n).has(t)&&("/"===n.op&&f.push(n.args[1]),"sqrt"!==n.op&&"ln"!==n.op||f.push(n.args[0]),"root"===n.op&&f.push(n.args[1]),"log"===n.op&&f.push(n.args[1],n.args[0],U("-",[n.args[0],vr()])),["arcsin","arccos","arctanh","arcsec","arccsc"].includes(n.op)&&f.push(U("-",[n.args[0],vr()]),U("+",[n.args[0],vr()])),"arccosh"===n.op&&f.push(U("-",[n.args[0],vr()])),"^"===n.op&&we(Ke(n.args[1]))&&Ke(n.args[1]).q.sign<0&&f.push(n.args[0]),"^"===n.op&&we(Ke(n.args[1]))&&!Ke(n.args[1]).q.isInteger&&f.push(n.args[0]))}const p=new Map;for(const n of f){const s=Js(e,_s(n,Hs),t,{...c?{interval:c}:{}});if(s.unsolved.length&&!s.always)return{pieces:null,steps:r,unsolved:!0};if(!s.always)for(const e of s.solutions){const n=Gs(e);!n||Math.abs(n.im)>1e-12||p.set(e.s,{node:e,x:n.re})}}let h=[...p.values()].sort((e,n)=>e.x-n.x).filter((e,n,t)=>0===n||Math.abs(e.x-t[n-1].x)>1e-12),d=null;if(c){const[e,n]=c.map(e=>({node:e,x:Gs(e)?.re}));if(!Number.isFinite(e.x)||!Number.isFinite(n.x)||e.x>n.x)throw new ne("the interval is two numbers, lo then hi");d={lo:e,hi:n},h=h.filter(t=>t.x>e.x+1e-12&&t.x<n.x-1e-12)}const m=e=>i.every(({h:n,op:s})=>{try{const r=zt(er(n,t,W(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(r.re)||Math.abs(r.im)>1e-12)&&br[s](Math.abs(r.re)<1e-30?0:r.re)}catch{return!1}}),g=e=>i.every(({h:n,op:s})=>{try{const r=zt(Ye(er(n,t,e.node)),{digits:30});return!(!Number.isFinite(r.re)||Math.abs(r.im)>1e-12)&&br[s](Math.abs(r.re)<1e-15?0:r.re)}catch{return!1}});if(d)return function(e,n,t,s,r,{lo:i,hi:o},a,u){const l=[i,...r,o],c=l.map(u),f=l.slice(1).map((e,n)=>a((l[n].x+e.x)/2)),p=[];let h=null;for(let e=0;e<l.length;e++){const n=l[e];if(c[e]&&!h?h={lo:n.node,loClosed:!0}:!c[e]&&h&&(p.push({...h,hi:n.node,hiClosed:!1}),h=null),e===l.length-1)break;f[e]?h??={lo:n.node,loClosed:!1}:h&&(p.push({...h,hi:n.node,hiClosed:c[e]}),h=null)}h&&p.push({...h,hi:o.node,hiClosed:c[l.length-1]});for(const e of p)e.lo.s===e.hi.s&&(e.loClosed=!0,e.hiClosed=!0);const d=r.length?r.map(n=>e.format(n.node)).join(", "):"none";return s.push(e.step("solve.sign-chart","A sign chart",["inequality"],n,n,{points:D(d),v:t})),{pieces:p,steps:s,interval:[i.node,o.node]}}(e,n,t,r,h,d,m,g);const v=h.map(e=>e.x),b=[];if(v.length){b.push(v[0]-Math.max(1,Math.abs(v[0])));for(let e=0;e+1<v.length;e++)b.push((v[e]+v[e+1])/2);b.push(v[v.length-1]+Math.max(1,Math.abs(v[v.length-1])))}else b.push(0);const y=b.map(m),w=h.map(g),x=[];let q=null;const k=(e,n)=>{x.push({...q,hi:e,hiClosed:n}),q=null};for(let e=0;e<=h.length;e++){const n=0===e?null:h[e-1].node;if(y[e]?q??={lo:n,loClosed:!1}:q&&k(n,e>0&&w[e-1]),e===h.length)break;const t=h[e];if(w[e]){if(q)continue;y[e+1]?q={lo:t.node,loClosed:!0}:x.push({lo:t.node,hi:t.node,loClosed:!0,hiClosed:!0})}else q&&k(t.node,!1)}q&&k(null,!1);const $=h.length?h.map(n=>e.format(n.node)).join(", "):"none";return r.push(e.step("solve.sign-chart","A sign chart",["inequality"],n,n,{points:D($),v:t})),{pieces:x,steps:r}}const xr={tan:"cos",sec:"cos",csc:"sin",cot:"sin"};class qr extends Error{}const kr=e=>({fin:e}),$r={bnd:!0},Sr=e=>({inf:e}),Mr=D("∞");function Nr(e){try{const n=zt(e,{digits:15});return Math.abs(n.im??0)>1e-12?NaN:n.re??n.number}catch{return NaN}}function Or(e){if(!pe.complex)return Number.isFinite(Nr(e));try{const n=zt(e,{digits:15});return Number.isFinite(n.re??n.number)&&Number.isFinite(n.im??0)}catch{return!1}}function Ir(e,n,t){if(!Number.isFinite(t))return!1;try{const s=zt(er(e,n,W(Er(t))),{digits:15});return Math.abs(s.im??0)>1e-12}catch(e){return/not real/.test(e.message)}}function Ar(e,n,t){return Number.isFinite(t)?Nr(er(e,n,W(Er(t)))):NaN}function Er(e){const n=Math.min(40,Math.max(0,16-Math.floor(Math.log10(Math.abs(e)||1))));return e.toFixed(n)}function jr(e,n,t,s){const r=Tr(t,s).map(t=>Ar(e,n,t)).filter(Number.isFinite);if(r.length<3)return NaN;const[i,o,a]=r.slice(-3),u=Math.max(1,Math.abs(a));return Math.abs(a-o)<1e-4*u&&Math.abs(o-i)<.01*u?a:NaN}function Tr(e,n){if(e.inf)return[100,1e3,1e4,1e5,1e6].map(n=>n*e.inf);const t=Nr(e.fin);return[.001,1e-4,1e-5,1e-6,1e-7].map(e=>t+n*e*Math.max(1,Math.abs(t)))}function zr(e,n,t,s){const r=Tr(t,s).map(t=>Ar(e,n,t)).filter(Number.isFinite);if(!r.length)return 0;const i=Math.sign(r[r.length-1]);return r.slice(-3).every(e=>Math.sign(e)===i)?i:0}function Zr(e,n,t,s,r=0){const i=[];if(!r&&!s.inf){const[e,r]=[jr(n,t,s,-1),jr(n,t,s,1)];if(Number.isFinite(e)&&Number.isFinite(r)&&Math.abs(e-r)>.001*Math.max(1,Math.abs(e),Math.abs(r)))throw new qr(`from the left it goes to ${+e.toPrecision(6)}, from the right to ${+r.toPrecision(6)}`)}if(!s.inf&&!pe.complex)for(const e of r?[r]:[-1,1])if(Tr(s,e).every(e=>Ir(n,t,e)))throw new qr(`it has no real values ${e<0?"to the left":"to the right"} of ${+Nr(s.fin).toPrecision(6)}`);const o=new Fr(e,t,s,r,i);let a;try{if(a=o.of(Ye(function(e,n){const{v:t,a:s,side:r}=e,i=s.inf?s.inf:r;if(!i)return n;let o=n;const a=n=>{if(!L(n))return n;const r=n.args.map(a),u=r.some((e,t)=>e!==n.args[t])?U(n.op,r):n;if("abs"!==u.op||!rn(u.args[0]).has(t))return u;const l=zr(u.args[0],t,s,i);if(!l)return u;const c=l>0?u.args[0]:Ye(U("neg",[u.args[0]])),f=Ye(Cr(o,u,c));return e.step("limit.abs","Absolute value",o,f,{inside:u.args[0],abs:u,to:c,sign:l>0?"positive":"negative",where:s.inf?"that far out":"on this side"}),o=f,c};return a(n),o}(o,n)),0),a.bnd)throw new qr("it keeps swinging between bounds")}catch(e){if(e instanceof qr){const e=(s.inf?[s.inf]:r?[r]:[-1,1]).map(e=>jr(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 ne(`numbers near the point settle on ${+e[0].toPrecision(6)}: not answered`)}throw e}return function(e,n,t,s,r){const i=s?[s]:t.inf?[-1]:[-1,1];for(const s of i){const i=Tr(t,s).map(t=>Ar(e,n,t)).filter(Number.isFinite);if(i.length<3)continue;const o=i[i.length-1];if(r.inf){if(Math.sign(o)!==r.inf||Math.abs(o)<Math.abs(i[0]))throw new ne(`numbers near the point don't go to ${r.inf>0?"∞":"-∞"}: not answered`)}else{const e=Nr(r.fin);if(!Number.isFinite(e))continue;const n=i.map(n=>Math.abs(n-e)),t=Math.abs(i[i.length-1]-i[i.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 ne(`numbers near the point go to ${o.toPrecision(6)}, not ${e.toPrecision(6)}: not answered`)}}}(n,t,s,r,a),{value:a,steps:i}}function Cr(e,n,t){return e.s===n.s?t:L(e)?U(e.op,e.args.map(e=>Cr(e,n,t))):e}class Fr{constructor(e,n,t,s,r){Object.assign(this,{cas:e,v:n,a:t,side:s,steps:r}),this.point=t.inf?t.inf>0?Mr:D("-∞"):t.fin}step(e,n,t,s,r={}){this.steps.push(this.cas.step(e,n,["limit"],t,s,{v:D(this.v),a:this.point,...r}))}of(e,n){if(n>8)throw new ne("this limit went too deep");const{v:t,a:s}=this;if(!rn(e).has(t))return kr(e);if("sym"===e.type)return s.inf?Sr(s.inf):kr(s.fin);if(s.inf){const r=Ns(Ss(Ke(e),t));if(r&&r.length>1){const i=r.length-1,o=r[i].sign*(i%2&&s.inf<0?-1:1);return 0===n&&this.step("limit.leading","The leading term",e,Ye(U("*",[nn(ge(r[i])),U("^",[D(t),W(String(i))])])),{f:e,lead:Ye(U("*",[nn(ge(r[i])),U("^",[D(t),W(String(i))])]))}),Sr(o)}}if(!s.inf&&0===n){const n=er(e,t,s.fin);let r=null;if(Or(n)&&!this.pole(n)&&!Br(n))try{r=Ye(n)}catch{}if(r&&Or(r)){const n=this.cas.simplify(r,{steps:!1}).result;return this.step("limit.substitute","Put the point in",e,n,{f:e}),kr(n)}}if(!L(e))return kr(e);switch(e.op){case"+":case"-":return this.sum(e,n);case"neg":return Wr(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(Nr(e));if(!n)throw new ne(`the sign of ${this.cas.format(e)} is not known`);return n}pole(e){return Dr(e).some(e=>L(e)&&xr[e.op]&&this.isExactZero(U(xr[e.op],[e.args[0]])))}isExactZero(e){try{const n=this.cas.simplify(Ye(e),{steps:!1}).result;return V(n)&&0===Number(n.value)}catch{return!1}}sum(e,n){const[t,s]=e.args;let r,i;try{r=this.of(t,n+1),i=this.of(s,n+1)}catch(t){if(!(t instanceof qr))throw t;const s=Vs(Ke(e)),r=Ye(U("/",[nn(s.num),nn(s.den)]));if(r.s===e.s)throw t;return this.step("limit.combine","One fraction",e,r,{f:e}),this.of(r,n+1)}const o="-"===e.op?Wr(i):i;if(r.bnd||o.bnd)return r.inf||o.inf?r.inf?r:o:$r;if(r.fin&&o.fin)return kr(Ye(U("+",[r.fin,o.fin])));if(r.inf&&o.inf&&r.inf!==o.inf){const r="-"===e.op?s:U("neg",[s]);if([t,s].some(e=>L(e)&&"sqrt"===e.op)||L(s)&&"neg"===s.op&&L(s.args[0])&&"sqrt"===s.args[0].op){const s=Ye(U("/",[U("-",[U("^",[t,W("2")]),U("^",[r,W("2")])]),U("+",[t,r])]));return this.step("limit.conjugate","∞ − ∞: the conjugate",e,s,{f:e}),this.of(s,n+1)}const i=Vs(Ke(e)),o=Ye(U("/",[nn(i.num),nn(i.den)]));if(o.s===e.s)throw new ne("∞ − ∞ that does not become one fraction");return this.step("limit.combine","∞ − ∞: one fraction",e,o,{f:e}),this.of(o,n+1)}return r.inf?r:o}product(e,n){const[t,s]=e.args,r=this.of(t,n+1),i=this.of(s,n+1),o=e=>e.fin&&Math.abs(Nr(e.fin))<1e-300;if(r.bnd||i.bnd){const n=r.bnd?i:r;if(o(n))return this.step("limit.squeeze","The squeeze theorem",e,W("0"),{f:e,bounded:r.bnd?t:s}),kr(W("0"));if(n.inf)throw new qr("a growing factor times one that keeps swinging");return $r}if(r.fin&&i.fin)return kr(Ye(U("*",[r.fin,i.fin])));if(o(r)&&i.inf||r.inf&&o(i)){const[i,a]=o(r)?[t,s]:[s,t],u=e=>e.s.split(" ").length,[l,c]=[Ye(U("/",[W("1"),i])),Ye(U("/",[W("1"),a]))],f=u(l)<=u(c)?U("/",[a,l]):U("/",[i,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 Sr(a(r)*a(i))}quotient(e,n,t,s){const{v:r,a:i}=this;if(i.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(Nr(e.fin))<1e-300;if(o.bnd&&a.inf)return this.step("limit.squeeze","The squeeze theorem",e,W("0"),{f:e,bounded:n}),kr(W("0"));if(o.bnd&&a.fin&&!u(a))return $r;if(a.bnd)throw new ne("a quotient over something that keeps swinging is not worked out here");if(o.inf&&a.inf&&i.inf){const r=this.dividePower(e,n,t,s);if(r)return r}if(a.fin&&!u(a))return o.fin?kr(this.cas.simplify(Ye(U("/",[o.fin,a.fin])),{steps:!1}).result):Sr(o.inf*this.signOf(a.fin));if(a.inf&&o.fin)return kr(W("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=Ye(this.cas.differentiate(n,r)),p=Ye(this.cas.differentiate(t,r)),h=Ye(U("/",[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:r,a:i}=this;if(!Dr(e).some(e=>L(e)&&(["sqrt","root","sin","cos"].includes(e.op)||"^"===e.op&&!rn(e.args[1]).size&&!Number.isInteger(Nr(e.args[1]))))||this.divided?.has(e.s))return null;const[o,a]=[1e4*i.inf,1e6*i.inf],u=Math.log(Math.abs(Ar(t,r,a)/Ar(t,r,o)))/Math.log(100),l=Math.round(2*u)/2;if(!Number.isFinite(u)||Math.abs(u-l)>.05||l<=0||i.inf<0&&!Number.isInteger(l))return null;const c=U("^",[D(r),W(String(l))]),f=e=>{if(L(e)&&("+"===e.op||"-"===e.op))return U(e.op,e.args.map(f));if(L(e)&&"neg"===e.op)return U("neg",[f(e.args[0])]);if(L(e)&&"sqrt"===e.op){const n=U("sqrt",[Ye(U("/",[e.args[0],U("^",[D(r),W(String(2*l))])]))]);return i.inf<0&&l%2?U("neg",[n]):n}return Ye(U("/",[e,c]))},p=U("/",[Ye(f(n)),Ye(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:r,den:i}=Vs(Ke(e)),o=Ns(Ss(r,t)),a=Ns(Ss(i,t));if(!o||!a||a.length<2)return null;if(s.inf){const[n,r]=[o.length-1,a.length-1],i=Ye(U("/",[U("*",[nn(ge(o[n])),U("^",[D(t),W(String(n))])]),U("*",[nn(ge(a[r])),U("^",[D(t),W(String(r))])])]));if(i.s!==e.s&&this.step("limit.leading","The leading terms",e,i,{f:e,lead:i}),n<r)return kr(W("0"));if(n===r)return kr(nn(ge(o[n].div(a[r]))));const u=o[n].div(a[r]).sign*((n-r)%2&&s.inf<0?-1:1);return Sr(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=er(u,t,s.fin);return Number.isFinite(Nr(l))?kr(this.cas.simplify(Ye(l),{steps:!1}).result):this.blowUp(u)}blowUp(e){const{v:n,a:t,side:s}=this,r=(s?[s]:[-1,1]).map(s=>zr(e,n,t,s));if(r.includes(0))throw new ne("the sign near the point could not be told");if(2===r.length&&r[0]!==r[1])throw this.step("limit.one-sided","The two sides differ",e,e,{f:e,left:r[0]>0?Mr:D("-∞"),right:r[1]>0?Mr:D("-∞")}),new qr(`from the left it goes to ${r[0]>0?"∞":"-∞"}, from the right to ${r[1]>0?"∞":"-∞"}`);return Sr(r[0])}power(e,n){const{v:t}=this,[s,r]=e.args,i=this.of(s,n+1);let o;const a=this.steps.length;try{o=this.of(r,n+1)}catch(t){if(!(t instanceof qr)||!i.fin||Math.abs(Nr(i.fin)-1)>1e-12)throw t;return this.steps.length=a,this.expLog(e,s,r,"1^∞",n)}if(i.bnd||o.bnd)throw new ne("a power of something that keeps swinging is not worked out here");const u=e=>e.fin?Nr(e.fin):e.inf*(1/0),l=u(i),c=u(o);if(i.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 kr(this.cas.simplify(Ye(U("^",[i.fin,o.fin])),{steps:!1}).result)}const f=!rn(s).has(t),p=!rn(r).has(t),h=i.fin&&Math.abs(l)<1e-300,d=i.fin&&Math.abs(l-1)<1e-12;if(i.fin&&o.inf&&(!d||f)){if(d)return kr(W("1"));if(h){if(o.inf<0){if(f)throw new qr("0 to a negative power has no value");return Sr(1)}return kr(W("0"))}if(l>1)return o.inf>0?Sr(1):kr(W("0"));if(l>0)return o.inf>0?kr(W("0")):Sr(1);throw new qr("a negative number to a growing power swings between signs")}if(i.inf<0&&!p)throw new ne("a power of something going to -∞ is not worked out here");if(i.inf&&(p||o.fin&&Math.abs(c)>1e-300||o.inf)){if(c>0)return Sr(i.inf>0?1:p&&Number.isInteger(c)&&c%2?-1:1);if(c<0)return kr(W("0"))}if(p&&h&&c>0)return kr(W("0"));const m=d?"1^∞":h?"0^0":i.inf&&o.fin?"∞^0":null;if(!m)throw new ne("a power of this shape is not worked out here");return this.expLog(e,s,r,m,n)}expLog(e,n,t,s,r){const i=Ye(U("*",[t,U("ln",[n])]));this.step("limit.exp-log","Take logs",e,U("^",[D("e"),i]),{f:e,form:D(s)});const o=this.of(i,r+1);if(o.bnd)throw new ne("a power of something that keeps swinging is not worked out here");return o.inf?o.inf>0?Sr(1):kr(W("0")):kr(this.cas.simplify(Ye(U("^",[D("e"),o.fin])),{steps:!1}).result)}func(e,n){const t=e.op,s=e.args;if(1!==s.length){if("log"===t&&!rn(s[0]).has(this.v)){const e=this.of(s[1],n+1);if(e.fin){const n=Ye(U("log",[s[0],e.fin]));if(Number.isFinite(Nr(n)))return kr(this.cas.simplify(n,{steps:!1}).result)}return this.of(Ye(U("/",[U("ln",[s[1]]),U("ln",[s[0]])])),n+1)}throw new ne(`a limit of ${t} is not worked out here`)}let r;try{r=this.of(s[0],n+1)}catch(e){if(e instanceof qr&&("sin"===t||"cos"===t))return $r;throw e}if(r.bnd){if("sin"===t||"cos"===t||"arctan"===t||"abs"===t)return $r;throw new ne(`${t} of something that keeps swinging is not worked out here`)}if(r.fin){if(xr[t]&&this.isExactZero(U(xr[t],[r.fin])))return this.blowUp(e);const n=Ye(U(t,[r.fin]));if(Or(n))return kr(this.cas.simplify(n,{steps:!1}).result);if("ln"===t&&Math.abs(Nr(r.fin))<1e-300)return Sr(-1);if(["tan","sec","csc","cot"].includes(t))return this.blowUp(e);throw new ne(`${t} has no value at the limit of its argument`)}const i=r.inf;switch(t){case"sqrt":case"ln":case"cosh":if(i<0&&"cosh"!==t)throw new qr(`${t} has no value as its argument goes to -∞`);return Sr(1);case"abs":return Sr(1);case"sinh":return Sr(i);case"tanh":return kr(W(String(i)));case"arctan":return kr(Ye(U("/",[i>0?D("pi"):U("neg",[D("pi")]),W("2")])));case"arccot":return kr(i>0?W("0"):D("pi"));case"arcsec":case"arccsc":return kr("arcsec"===t?Ye(U("/",[D("pi"),W("2")])):W("0"));case"sin":case"cos":return $r;case"tan":case"sec":case"csc":case"cot":throw new qr(`${t} keeps swinging as its argument grows`);default:throw new ne(`a limit of ${t} at ∞ is not worked out here`)}}}const Br=e=>Dr(e).some(e=>L(e)&&("/"===e.op&&Math.abs(Nr(e.args[1]))<1e-300||"^"===e.op&&Nr(e.args[1])<0&&Math.abs(Nr(e.args[0]))<1e-300)),Dr=(e,n=[])=>(n.push(e),L(e)&&e.args.forEach(e=>Dr(e,n)),n),Wr=e=>e.bnd?e:e.inf?Sr(-e.inf):kr(Ye(U("neg",[e.fin])));function Rr(e){if(!L(e)||"lim"!==e.op)return null;const[n,t,s,r]=e.args;if(L(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"===r?.token?1:"l"===r?.token?-1:0;return{f:n,v:t.token,to:s,side:e}}return null}function Pr(e){return"sym"!==e.type||"∞"!==e.token&&"oo"!==e.token&&"infinity"!==e.token?"sym"===e.type&&"-∞"===e.token||L(e)&&"neg"===e.op&&"sym"===e.args[0].type&&"∞"===e.args[0].token?Sr(-1):kr(Ye(e)):Sr(1)}const Ur=e=>e.inf?e.inf>0?Mr:D("-∞"):e.fin,Vr=new Set(["sin","cos","tan","sec","csc","cot"]),Lr=()=>W("2");function _r(e,n){if(!Hr(n))return[];let t,s;try{const e=Jr(n);t=new Map;s=Vs(Ke(Kr(e,t)))}catch{return[]}const r=[],i=Qr(n);for(const n of["sin","cos","none"])try{const o=[ks(s.num),ks(s.den)],a="none"===n?o[0]:Yr(s.num,t,n),u="none"===n?o[1]:Yr(s.den,t,n);if(!a||!u)continue;const l=nn(a).s!==nn(o[0]).s||nn(u).s!==nn(o[1]).s,c=[{p:ei(a,u),how:l?"pythagorean":i?"expand-double":"sin-cos"}],f=[Gr(a,t),Gr(u,t)];f[0]&&f[1]&&c.push({p:ei(f[0],f[1]),how:"double-angle"});for(const n of c)r.push({node:ti(e,ni(n.p,t)),how:n.how})}catch{}return r}const Hr=e=>L(e)&&(Vr.has(e.op)||e.args.some(Hr)),Qr=e=>L(e)&&(("sin"===e.op||"cos"===e.op)&&L(e.args[0])&&"*"===e.args[0].op&&V(e.args[0].args[0])&&2===Number(e.args[0].args[0].value)||e.args.some(Qr));function Jr(e){if(!L(e))return e;const n=e.args.map(Jr),[t]=n,s=e=>U("sin",[e]),r=e=>U("cos",[e]),i=e=>L(e)&&"*"===e.op&&V(e.args[0])&&2===Number(e.args[0].value)?2===e.args.length?e.args[1]:U("*",e.args.slice(1)):null;switch(e.op){case"tan":return U("/",[s(t),r(t)]);case"sec":return U("/",[W("1"),r(t)]);case"csc":return U("/",[W("1"),s(t)]);case"cot":return U("/",[r(t),s(t)]);case"sin":{const e=i(t);return e?U("*",[U("*",[Lr(),s(e)]),r(e)]):s(t)}case"cos":{const e=i(t);return e?U("-",[U("^",[r(e),Lr()]),U("^",[s(e),Lr()])]):r(t)}default:return U(e.op,n)}}function Kr(e,n){if(!L(e))return e;if(("sin"===e.op||"cos"===e.op)&&!Hr(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 U(e.op,e.args.map(e=>Kr(e,n)))}function Yr(e,n,t){let s=ks(e);for(const{s:e,c:r}of n.values()){const[n,i]="sin"===t?[e,r]:[r,e],o=Ss(s,n);if(!o)return null;const a=[];for(const[e,t]of o){const s=Math.floor(e/2),r=[t];e%2&&r.push(Ke(D(n))),s&&r.push(Ke(U("^",[U("-",[W("1"),U("^",[D(i),Lr()])]),W(String(s))]))),a.push(Te(r))}if(s=ks(Ee(a)),on(s).length>200)return null}return s}function Gr(e,n){let t=ks(e);for(const{u:e,s:s,c:r}of n.values()){const n=U("sin",[U("*",[Lr(),e])]),i=U("cos",[U("*",[Lr(),e])]),o=[];for(const e of on(t)){const t=nn(e),a=Xr(t,s),u=Xr(t,r);if(a+u===0){o.push(e);continue}if(a+u!==2)return null;const l=er(er(t,s,W("1")),r,W("1")),c=U("/",1===a?[n,Lr()]:2===a?[U("-",[W("1"),i]),Lr()]:[U("+",[W("1"),i]),Lr()]);o.push(Ke(U("*",[l,c])))}t=ks(Ee(o))}return t}function Xr(e,n){const t=Ss(Ke(e),n);return t?Math.max(0,...t.keys()):0}function ei(e,n){const t=Ke(U("/",[nn(e),nn(n)])),s=Ls(t);return s?Ps(s):nn(t)}function ni(e,n){let t=e;for(const{u:e,s:s,c:r}of n.values())t=er(er(t,s,U("sin",[e])),r,U("cos",[e]));return Ye(t)}function ti(e,n){const t=e=>{if(!L(e))return e;const n=e.args.map(t);if("/"===e.op&&V(n[0])){const e=n[1],[t,s]=L(e)&&"^"===e.op&&V(e.args[1])?[e.args[0],e.args[1]]:[e,null],r=L(t)&&{cos:"sec",sin:"csc"}[t.op];if(r){const e=U(r,t.args),i=s?U("^",[e,s]):e;return 1===Number(n[0].value)?i:U("*",[n[0],i])}}return U(e.op,n)},s=Kt(Ye(t(n)),e.set.view("simplify"),{format:e.format}).node;try{const{num:e,den:n}=Vs(Ke(s)),t=Ye(U("/",[nn(e),nn(n)]));return t.s.split(" ").length<s.s.split(" ").length?t:s}catch{return s}}const si=(e,n)=>U("int",[e,"string"==typeof n?D(n):n]);function ri(e,n,t,s=0){if(s>6)throw new ne("integration went too deep");const r=[],i=e.set.view("integrate"),o=Kt(n,e.set.view("simplify"),{format:e.format});r.push(...ii(o.steps,e=>Ye(si(e,t))));let a=Ye(si(o.node,t));for(let n=0;n<40;n++){const n=Kt(a,i,{format:e.format});r.push(...n.steps),a=n.node;const t=G(a,"pre").find(({node:e})=>{return L(n=e)&&"int"===n.op&&2===n.args.length;var n});if(!t)return{node:a,steps:r};const o=oi(e,t.node,s);if(!o)throw new ne(`no rule for ∫ ${e.format(t.node.args[0])} d${t.node.args[1].token}`);const u=a;r.push(...ii(o.steps,e=>Ye(ee(u,t.path,e)))),a=Ye(ee(a,t.path,o.node))}throw new ne("integration did not finish")}function ii(e,n){return e.map(e=>{const t=n(_(e.from)).s,s=n(_(e.to)).s;return t===e.from&&s===e.to?e:{...e,from:t,to:s,path:null}})}function oi(e,n,t){const[s,r]=n.args,i=r.token,o=Ke(s),a=function(e,n){const{num:t,den:s}=Vs(e),r=Zs(t),i=Zs(s),o=r.coef.div(i.coef);if(o.isOne||!Ms(e,n))return null;const a=Te([...r.factors.map(e=>Ze(e.base,e.exp)),...i.factors.map(e=>Ze(e.base,Ve(e.exp)))]);return{c:o,rest:a}}(o,i);if(a){const t=U("*",[nn(ge(a.c)),si(nn(a.rest),r)]);return{node:t,steps:[e.step("integrate.constant","Take the number out",["split","minor"],n,t,{c:nn(ge(a.c))})]}}const u=Ls(o),l=u&&Ps(u);if(l&&J(l)<J(s)&&rn(l).has(i)){const t=si(l,r);return{node:t,steps:[e.step("integrate.cancel","One fraction",["cancel"],n,t,{})]}}const c=hi(e,n,o,i,!0);if(c)return c;const f=ks(o);if(nn(f).s!==s.s&&"add"===f.k){const t=si(nn(f),r);return{node:t,steps:[e.step("integrate.expand","Multiply out",["expand"],n,t,{})]}}const p=function(e,n){const t=new Map;for(const{node:s}of G(e,"pre")){if(!L(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||!rn(s).has(n))continue;const e=Ss(Ke(s),n);if(!e||1!==Math.max(...e.keys()))continue;const r=e.get(1);Ms(r,n)||we(r)&&r.q.isZero||t.set(s.s,{node:s,a:r})}}for(const s of t.values()){if(!rn(vi(e,s.node,D("§"))).has(n))return s}return null}(s,i);if(p){const r="u"===i?"t":"u",o=vi(s,p.node,D(r));if(!rn(o).has(i)){const s=ri(e,Ye(o),r,t+1),a=Ye(er(s.node,r,p.node)),u=nn(Le(Ke(a),p.a)),l=e=>nn(Le(Ke(e),p.a));return{node:u,steps:[e.step("integrate.substitute","Substitute",["substitute"],n,l(Ye(si(Ye(o),r))),{u:D(r),inside:p.node,a:nn(p.a),v:i,du:ai(e,p.a,i)}),...ii(s.steps,l),e.step("integrate.back","Substitute back",["substitute"],l(s.node),u,{u:D(r),inside:p.node})]}}}const h=hi(e,n,o,i);if(h)return h;const d=pi(e,n,i);if(d)return d;const m=function(e,n,t,s){if(s>=3)return null;const[r,i]=n.args,o="u"===t?"t":"u",a=new Set;for(const{node:i}of G(r,"pre")){if(i===r||!L(i)||i.s===r.s||a.has(i.s)||!rn(i).has(t)||["der","int"].includes(i.op))continue;let u,l,c;a.add(i.s);try{u=Ye(e.differentiate(i,t))}catch{continue}if(V(u)&&0===Number(u.value))continue;try{l=vi(Ye(U("/",[r,u])),i,D(o))}catch{continue}if(rn(l).has(t))continue;try{c=ri(e,Ye(l),o,s+1)}catch{continue}const f=Ye(er(c.node,o,i));return{node:f,steps:[e.step("integrate.u-substitution","Substitute",["substitute"],n,Ye(si(l,o)),{u:D(o),inside:i,du:u,v:t}),...c.steps,e.step("integrate.back","Substitute back",["substitute"],c.node,f,{u:D(o),inside:i})]}}return null}(e,n,i,t);return m||function(e,n,t,s,r){if(r>=6)return null;const i=an(t),o=i.filter(e=>bi(e,s)||!Ms(e,s)),a=i.filter(e=>!o.includes(e));if(1!==a.length)return null;const u=Te(o),l=a[0],c=nn(l),f=L(c)?c.op:"",p=["ln","arctan","arcsin","arccos","arcsec","arccsc","arccot"];if(!Ms(u,s)&&!p.includes(f))return null;let h,d,m;p.includes(f)?(h=l,d=u):(h=u,d=l);try{m=ri(e,nn(d),s,r+1)}catch{return null}const g=Ke(e.differentiate(nn(h),s)),v=Te([h,Ke(m.node)]),b=si(nn(Te([g,Ke(m.node)])),D(s)),y=Ye(U("-",[nn(v),b]));return{node:y,steps:[e.step("integrate.parts","Integration by parts",["parts"],n,y,{u:nn(h),dv:nn(d),V:m.node,du:nn(g),v:s})]}}(e,n,o,i,t)}const ai=(e,n,t)=>we(n)&&n.q.isOne?`d${t}`:we(n)&&n.q.neg().isOne?`-d${t}`:`${e.format(nn(n))} d${t}`,ui=e=>nn(ge(e)),li=e=>W(String(e));function ci(e,n){if(!e||!rn(e).has(n))return null;const t=Ss(Ke(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 fi(e){return L(e)&&"^"===e.op&&V(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 pi(e,n,t){const[s,r]=n.args,i=an(Ke(s)).map(nn).map(fi),o=(e,...n)=>L(e.base)&&n.includes(e.base.op),a=(s,r,i,o={})=>({node:i,steps:[e.step(s,r,["rewrite"],n,i,{v:t,...o})]});if(2===i.length&&i.every(e=>1===e.n)){const e=i.find(e=>L(e.base)&&"^"===e.base.op&&"sym"===e.base.args[0].type&&"e"===e.base.args[0].token),n=i.find(e=>o(e,"sin","cos")),s=e&&ci(e.base.args[1],t),r=n&&ci(n.base.args[0],t);if(s&&r){const[t,i]=[s.a,r.a],o=t.mul(t).add(i.mul(i)),[u,l]=[U("sin",[r.node]),U("cos",[r.node])],c="sin"===n.base.op?U("-",[U("*",[ui(t),u]),U("*",[ui(i),l])]):U("+",[U("*",[ui(t),l]),U("*",[ui(i),u])]);return a("integrate.parts-twice","By parts twice",Ye(U("/",[U("*",[e.base,c]),ui(o)])),{e:e.base,t:n.base})}}if(2===i.length&&i.every(e=>1===e.n&&o(e,"sin","cos")&&ci(e.base.args[0],t))&&i[0].base.args[0].s!==i[1].base.args[0].s){const[e,n]="sin"===i[0].base.op?i:[i[1],i[0]],[t,s]=[e.base.args[0],n.base.args[0]],o=(e,n)=>U(e,[U(n,[t,s])]);let u;u="sin"===e.base.op&&"cos"===n.base.op?U("+",[o("sin","+"),o("sin","-")]):"cos"===e.base.op?U("+",[o("cos","-"),o("cos","+")]):U("-",[o("cos","-"),o("cos","+")]);return a("integrate.product-to-sum","Product to sum",Ye(si(U("/",[u,li(2)]),r)))}const u=i.find(e=>o(e,"sin")),l=i.find(e=>o(e,"cos")),c=!u||!l||u.base.args[0].s===l.base.args[0].s;if((u||l)&&c&&i.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=i.filter(e=>e!==n).map(e=>U("^",[e.base,li(e.n)])),c=[...l,U("^",[U("-",[li(1),U("^",[U(s,[o]),li(2)])]),li(u)]),U(n.base.op,[o])].reduce((e,n)=>U("*",[e,n])),f=Ye(si(c,r)),p=a("integrate.odd-power","An odd power",f,{f:n.base,other:U(s,[o])});if("sym"!==o.type||o.token!==t)return p;const h="u"===t?"t":"u",d=l.length?i.find(e=>e!==n).n:0;if(2*u+d>100)throw new ne(`a power this high (${n.n+d}) is not integrated here`);const m="sin"===n.base.op?-1:1,g=U(s,[o]),v=U("*",[U("^",[U("-",[li(1),U("^",[D(h),li(2)])]),li(u)]),U("^",[D(h),li(d)])]),b=Ye(si(m<0?U("neg",[v]):v,D(h))),y=Ss(ks(Ke(v)),h);if(!y)return p;const w=[...y].map(([e,n])=>U("*",[nn(n),U("/",[U("^",[g,li(e+1)]),li(e+1)])])).reduce((e,n)=>U("+",[e,n])),x=Ye(m<0?U("neg",[w]):w);return{node:x,steps:[...p.steps,e.step("integrate.u-substitution","Substitute",["substitute"],f,b,{u:D(h),inside:g,du:m<0?U("neg",[n.base]):n.base,v:t}),e.step("integrate.back","Back to "+t,["substitute"],b,x,{u:D(h),inside:g})]}}if(1===i.length&&i[0].n>=3&&o(i[0],"sec","csc")&&"sym"===i[0].base.args[0].type&&i[0].base.args[0].token===t){const{base:e,n:n}=i[0],t=e.args[0],s="sec"===e.op?U("tan",[t]):U("cot",[t]),o=U("/",[U("*",[U("^",[e,li(n-2)]),s]),li(n-1)]),u=U("*",[U("/",[li(n-2),li(n-1)]),si(U("^",[e,li(n-2)]),r)]);return a("integrate.reduction","Reduction formula",Ye(U("+",["sec"===e.op?o:U("neg",[o]),u])),{f:e,n:li(n)})}const f=e=>{if(!L(e)||"sqrt"!==e.op)return null;const n=Ss(Ke(e.args[0]),t);if(!n||2!==n.size||!n.has(2)||!n.has(0))return null;const[s,r]=[n.get(2),n.get(0)];return!we(s)||!we(r)||s.q.sign>=0||r.q.sign<=0?null:{k:s.q.neg(),c:r.q,root:e}},p=D(t),h=e=>U("sqrt",[ui(e)]),d=f(s),m=L(s)&&"/"===s.op&&V(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=U("arcsin",[U("*",[p,h(e.div(n))])]);return a("integrate.trig-substitution","A trig substitution",Ye(d?U("+",[U("/",[U("*",[p,t]),li(2)]),U("*",[U("/",[ui(n),U("*",[li(2),h(e)])]),s])]):U("/",[s,h(e)])),{x:p,a:Ye(h(n.div(e)))})}return null}function hi(e,n,t,s,r=!1){const{num:i,den:o}=Vs(t);if(!Ms(o,s))return null;const a=Ns(Ss(i,s)),u=Ns(Ss(o,s));if(!a||!u||u.length<2)return null;const l=Ke(D(s)),c=e=>Os(e,s);if(a.length>=u.length){const{q:t,r:r}=zs(a,u),i=si(nn(Ee([c(t),Le(c(r),c(u))])),D(s));return{node:i,steps:[e.step("integrate.divide","Divide the polynomials",["divide"],n,i,{})]}}if(r)return null;const{roots:f,rest:p}=Ts(u),h=new Set(f.map(String)).size===f.length,d=3===p.length&&p[1].mul(p[1]).sub(oe.of(4).mul(p[0]).mul(p[2])).sign<0;if(!h||1!==p.length&&!d||!f.length&&!d)return null;const m=(e=>e.length<=1?[oe.ZERO]:e.slice(1).map((e,n)=>e.mul(oe.of(n+1))))(u),g=f.map(e=>As(a,e).div(As(m,e))),v=f.map((e,n)=>Le(ge(g[n]),Ee([l,ge(e.neg())])));if(!d){const t=si(nn(Ee(v)),D(s));return{node:t,steps:[e.step("integrate.partial-fractions","Partial fractions",["partial-fractions"],n,t,{})]}}let b=a;f.forEach((e,n)=>{b=gi(b,mi(zs(u,[e.neg(),oe.of(1)]).q,g[n]))});const y=f.reduce((e,n)=>di(e,[n.neg(),oe.of(1)]),[oe.of(1)]),{q:w}=zs(b,y),[x,q]=[w[0]??oe.ZERO,w[1]??oe.ZERO],[k,$,S]=zs(u,y).q,M=oe.of(4).mul(S).mul(k).sub($.mul($)),N=Os([k,$,S],s),O=q.div(oe.of(2).mul(S)),I=x.sub(q.mul($).div(oe.of(2).mul(S))),A=U("sqrt",[ui(M)]),E=U("*",[ui(O),U("ln",[U("abs",[nn(N)])])]),j=U("*",[U("/",[U("*",[li(2),ui(I)]),A]),U("arctan",[U("/",[nn(Os([$,S.mul(oe.of(2))],s)),A])])]),T=v.length?si(nn(Ee(v)),D(s)):li(0),z=Ye(U("+",[U("+",[T,E]),j]));return{node:z,steps:[e.step("integrate.complete-square","Complete the square",["partial-fractions"],n,z,{Q:nn(N)})]}}const di=(e,n)=>{const t=Array.from({length:e.length+n.length-1},()=>oe.ZERO);return e.forEach((e,s)=>n.forEach((n,r)=>{t[s+r]=t[s+r].add(e.mul(n))})),t},mi=(e,n)=>e.map(e=>e.mul(n)),gi=(e,n)=>Array.from({length:Math.max(e.length,n.length)},(t,s)=>(e[s]??oe.ZERO).sub(n[s]??oe.ZERO));function vi(e,n,t){return e.s===n.s?t:L(e)?U(e.op,e.args.map(e=>vi(e,n,t))):e}const bi=(e,n)=>{const t=Ss(e,n);return Boolean(t)&&[...t.values()].every(e=>!Ms(e,n))&&Math.max(...t.keys())>=1};function yi(e,n,t,s,r,i){if([s,r].some(e=>Pr(e).inf))return function(e,n,t,s,r,i){const o=[s,r].map(e=>Pr(e)),a=e=>e.inf?e.inf*(1/0):zt(e.fin,{digits:20}).number,[u,l]=o.map(a).sort((e,n)=>e-n);for(const n of i?wi(i,t):[]){let s=[];try{s=e.solve(U("=",[n,W("0")]),t,{steps:!1}).solutions}catch{continue}for(const n of s){const s=zt(n,{digits:20});if(Number.isFinite(s.number)&&!s.im&&s.number>u&&s.number<l)throw new ne(`the integrand has no value at ${t} = ${e.format(n)}, between the limits: split the integral there`)}}const c=(s,r,i)=>{if(!r.inf)try{const e=Ye(er(n,t,s));if(Number.isFinite(zt(e,{digits:15}).number))return e}catch{}const o=e.limit(n,t,s,{steps:!1,side:r.inf?void 0:i});if(!o.exists)throw new ne(`the integral diverges: as ${t} → ${e.format(s)}, ${e.format(n)} has no limit (${o.reason})`);if(o.infinite)throw new ne(`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(r,o[1],f?"left":"right")],d=Ye(U("-",[h,p])),m=U("-",[h,p]);return{value:d,shown:m,step:e.step("integrate.improper","Limits at the ends",["evaluate"],n,m,{a:s,b:r,F:n,v:t})}}(e,n,t,s,r,i);if(i&&!rn(s).size&&!rn(r).size){const o=zt(s,{digits:20}).number,a=zt(r,{digits:20}).number,u=[...rn(i)].filter(e=>e!==t);if(!u.length){const[s,r]=o<=a?[o,a]:[a,o];for(const o of wi(i,t)){let i=[];try{i=e.solve(U("=",[o,W("0")]),t,{steps:!1}).solutions}catch{continue}for(const o of i){const i=zt(o,{digits:20});if(!Number.isFinite(i.number)||i.im||i.number<s||i.number>r)continue;if(i.number>s&&i.number<r)throw new ne(`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=zt(Ye(er(n,t,o)),{digits:15}).number}catch{}if(!Number.isFinite(a))throw new ne(`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=zt(er(i,t,W(n.toFixed(15))),{digits:15}).number;if(!Number.isFinite(e))throw new ne("not finite")}catch(e){throw new ne(`the integrand has no value at ${t} = ${n.toPrecision(6)}, between the limits, so F(b) - F(a) would be wrong`)}}}const o=e=>Ye(er(n,t,e)),a=Ye(U("-",[o(r),o(s)])),u=U("-",[o(r),o(s)]);return{value:a,shown:u,step:e.step("integrate.evaluate","Between the limits",["evaluate"],n,u,{a:s,b:r,F:n,v:t})}}function wi(e,n){const t=[],s={tan:"cos",sec:"cos",csc:"sin",cot:"sin"};return G(e,"pre").forEach(({node:e})=>{if(!L(e))return;let r=null;"/"===e.op?r=e.args[1]:"^"===e.op&&"num"===e.args[1].type&&e.args[1].value<0||"^"===e.op&&L(e.args[1])&&"neg"===e.args[1].op?r=e.args[0]:s[e.op]&&(r=U(s[e.op],[e.args[0]])),r&&rn(r).has(n)&&!t.some(e=>e.s===r.s)&&t.push(r)}),t}const xi={"=":1,"≠":1,"<":1,">":1,"≤":1,"≥":1,"+":2,"-":2,"±":2,"*":3,"/":3,neg:4,pm:4,"^":5},qi={pi:"π","≤":"≤","≥":"≥"};function ki(e){return Oi(e).text}function $i(e,n,t=!1){return e.prec<n||t&&e.prec===n?`(${e.text})`:e.text}const Si=e=>"op"===e.type?e.op:null,Mi=e=>e.text.startsWith("-"),Ni={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]};function Oi(e){if("num"===e.type)return{text:e.token,prec:e.token.startsWith("-")?4:9};if("sym"===e.type)return{text:qi[e.token]??e.token,prec:9};const n=e.args.map(Oi),t=xi[e.op];switch(e.op){case"+":case"-":case"±":{const s="+"===e.op&&["+","-"].includes(Si(e.args[1])),r=Mi(n[1])?`(${n[1].text})`:s?n[1].text:$i(n[1],t,!0);return{text:`${$i(n[0],t)} ${"±"===e.op?"±":e.op} ${r}`,prec:t}}case"*":{const s=$i(n[0],t),r=Mi(n[1])?`(${n[1].text})`:"*"===Si(e.args[1])?n[1].text:$i(n[1],t,!0);return{text:"num"===e.args[0].type&&"num"!==e.args[1].type&&!/^[\d(-]/.test(r)||"sym"===e.args[1].type&&"i"===e.args[1].token&&!/[\dA-Za-z]$/.test(s)?`${s}${r}`:`${s}·${r}`,prec:t}}case"/":return{text:`${$i(n[0],t)}/${$i(n[1],t,!0)}`,prec:t};case"^":return{text:`${$i(n[0],t+1)}^${$i(n[1],t)}`,prec:t};case"neg":return{text:`-${$i(n[0],3)}`,prec:4};case"pm":return{text:`±${$i(n[0],4)}`,prec:4};case"!":return{text:`${$i(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:`${$i(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:`${Ni[e.op][0]}${n.map(e=>e.text).join(", ")}${Ni[e.op][1]}`,prec:9};case"&":return{text:`${n[0].text} and ${n[1].text}`,prec:0};default:return void 0!==t?{text:`${$i(n[0],t)} ${e.op} ${$i(n[1],t,!0)}`,prec:t}:{text:`${e.op.replace(/^\\:?/,"")}(${n.map(e=>e.text).join(", ")})`,prec:9}}}const Ii=['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, minor]\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, minor]\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, minor]\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, minor]\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, minor]\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, minor]\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, minor]\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: "Apply the quotient rule: 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: "A natural log differentiates to 1 over {u}, times the derivative of {u}."\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: "A square root differentiates to 1 over twice the square root of {u}, times the derivative 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 negative 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: "Tangent differentiates to 1 over cosine squared of {u}, times the derivative 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 negative 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: "Cotangent differentiates to negative 1 over sine squared of {u}, times the derivative 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: "Inverse sine differentiates to 1 over the square root of 1 minus {u} squared, times the derivative of {u}."\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: "Inverse cosine differentiates to negative 1 over the square root of 1 minus {u} squared, times the derivative of {u}."\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: "Inverse tangent differentiates to 1 over 1 plus {u} squared, times the derivative of {u}."\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: "Inverse secant differentiates to 1 over the absolute value of {u} times the square root of {u} squared minus 1, times the derivative of {u}."\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: "Inverse cosecant differentiates to negative 1 over the absolute value of {u} times the square root of {u} squared minus 1, times the derivative of {u}."\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: "Inverse cotangent differentiates to negative 1 over 1 plus {u} squared, times the derivative of {u}."\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: "Hyperbolic tangent differentiates to 1 over hyperbolic cosine squared of {u}, times the derivative 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: "Inverse hyperbolic sine differentiates to 1 over the square root of {u} squared plus 1, times the derivative of {u}."\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: "Inverse hyperbolic cosine differentiates to 1 over the square root of {u} squared minus 1, times the derivative of {u}."\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: "Inverse hyperbolic tangent differentiates to 1 over 1 minus {u} squared, times the derivative of {u}."\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: "A base {a} logarithm differentiates to 1 over {u} times the natural log of {a}, times the derivative of {u}."\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: "Write the root as a power, then bring the power down and drop it by one: the derivative of {u}, over {n} times the same 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: "The variable is in the base and in the exponent, so write {u}^{w} as e to the {w} times the natural log of {u}. By the chain rule, the derivative is the same power, times the derivative of that exponent."\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, minor]\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, minor]\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, minor]\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}: {u} is arcsin {r} or π - arcsin {r} (and any whole number of turns, 2πk, more)."\n tags: [inverse, trig, period-2pi]\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}: {u} is ±arccos {r} (and any whole number of turns, 2πk, more)."\n tags: [inverse, trig, period-2pi]\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 ({u} can also be any whole number of half turns, πk, more)."\n tags: [inverse, trig, period-pi]\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'],Ai=['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'],Ei=new Set(["<",">","≤","≥"]),ji=new Set(["sin","cos","tan","sec","csc","cot"]),Ti=new Set(["arcsin","arccos","arctan","arcsec","arccsc","arccot"]),zi={normal:"Work out the numbers and collect like terms.","normal.numbers":"Work out the numbers.","normal.collect":"Collect like terms.","normal.expand-collect":"Multiply out the brackets and collect like terms.","solve.both-add":"Add {t} to both sides.","solve.both-subtract":"Subtract {t} from both sides.","solve.both-divide":"Divide both sides by {t}.","solve.both-multiply":"Multiply both sides by {t}.","solve.each-side":"Work out each side.","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.collect":"Collect the terms with {v} on the left, where {v} is multiplied by {a} in all, and move the others to the right.","solve.expand":"Multiply out the brackets.","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.back":"Put {kernel} back for {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.interval":"In the interval from {lo} to {hi}, that is {count} answer(s): each one, and the same plus or minus a whole number of periods.","solve.never-zero":"{f} is never 0, so the rest must be: divide both sides by it.","solve.sin-cos":"Divide both sides by cos({u}): sine over cosine is the tangent.","solve.pythagorean":"Write {from}² as 1 - {to}², so there is only {to}({u}).","simplify.trig":"Write it with sin and cos, use sin² + cos² = 1 and the double-angle formulas, and cancel.","simplify.trig.sin-cos":"Write tan, sec, csc and cot with sin and cos, and cancel.","simplify.trig.pythagorean":"Write it with sin and cos, and use sin² + cos² = 1.","simplify.trig.expand-double":"Write the double angles out (sin 2u = 2 sin u cos u, cos 2u = cos²u − sin²u), and cancel.","simplify.trig.double-angle":"Read the double-angle formulas backward: 2 sin u cos u = sin 2u, cos²u − sin²u = cos 2u.","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.abs":"{inside} is {sign} {where}, so {abs} is {to}.","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.swap":"Swap the {row} and {other} equations, so that the {row} one has {v} in it.","system.scale":"Divide the {row} equation by {by}, so that {v} stands alone in front.","system.subtract":"Subtract the {from} equation from the {row} one: {v} goes from it.","system.subtract-multiple":"Subtract {k} times the {from} equation from the {row} one: {v} goes from it.","system.add":"Add the {from} equation to the {row} one: {v} goes from it.","system.add-multiple":"Add {k} times the {from} equation to the {row} one: {v} goes from it.","integrate.cancel":"Write the integrand as one fraction and cancel what the top and bottom share.","integrate.expand":"Multiply out, then integrate term by term.","integrate.substitute":"Let {u} = {inside}, so d{u} = {du}.","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."},Zi=["normal","rewrite","simplify","expand","factor","cancel","diff","differentiate","integrate","solve","solveSystem","substitute","approximate","equivalent","limit"];class Ci{constructor(e,n,t,s,r){this.set=e,this.messages=n,this.format=t,this.read=s,this.complex=r;for(const e of Zi){const n=Ci.prototype[e];this[e]=(...e)=>he(r,()=>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 ne("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||!L(e)||!e.s.includes("= der"))return e;const n=e.args.map(e=>this.atPoints(e)),[t,s]=n;if("der"===e.op&&L(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 U(e.op,n)}step(e,n,t,s,r,i={},o=e){return function(e,n,t,s,r,i,o,a,u=[]){const l=(i??"").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:r.s,path:u,before:s.s,after:r.s,explanation:l}}(e,n,t,s,r,this.messages[o]??this.messages[e]??"",i,this.format)}select(e,n,t=null){const s=function(e){if(!1===e)return null;if(void 0===e||!0===e)return{show:"all",hide:bs.normal,explain:!0,detail:"normal"};if("string"==typeof e){if(!bs[e])throw new Error(`steps: "${e}" is not one of ${Object.keys(bs).join(", ")}`);return{show:"all",hide:bs[e],explain:!0,detail:e}}const n=e.detail??"normal";if(!bs[n])throw new Error(`steps.detail: "${n}" is not one of ${Object.keys(bs).join(", ")}`);return{show:e.show??"all",hide:[...bs[n],...e.hide??[]],explain:e.explain??!0,detail:n}}(n);return"full"===s?.detail&&(s.split=e=>this.splitTidy(e)),vs(function(e,n){if(!n)return[];e="full"===n.detail?n.split?e.flatMap(n.split):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],r=` The derivative of ${n} is 1.`;s.explanation=e.explanation.endsWith(`the derivative of ${n}.`)?`${e.explanation.slice(0,-1)}, which is 1.`:e.explanation.endsWith(r)||e.explanation.endsWith(`the derivative of ${n}, which is 1.`)?e.explanation:`${e.explanation}${r}`}n[n.length-1]=s}return n}(e);const t=[];let s=null;for(const r of e){if(!ys(r,n.show)||ys(r,n.hide)){s=s??{from:r.from,ids:[]},s.ids.push(r.id);continue}const e={...r};s&&(e.from=s.from,e.also=s.ids,e.path=null,s=null),!0===n.explain||!1!==n.explain&&ys(r,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}(e,s),t)}splitTidy(e){if(["solve.move","solve.divide","solve.multiply"].includes(e.id))return this.splitBothSides(e);if("normal"!==e.id)return[e];let n,t;try{n=_(e.from),t=ut(n)}catch{return[e]}return t.s===n.s||t.s===e.to?[e]:[this.step("normal.numbers","Work out the numbers",["arithmetic"],n,t),{...this.step("normal.collect","Collect like terms",["tidy"],t,_(e.to),{},G(t,"pre").some(({node:e})=>L(e)&&"*"===e.op&&e.args.some(e=>L(e)&&("+"===e.op||"-"===e.op)))?"normal.expand-collect":"normal.collect"),path:e.path}]}splitBothSides(e){try{return this.bothSides(e)}catch{return[e]}}bothSides(e){let n,t;try{n=_(e.from),t=_(e.to)}catch{return[e]}const s=e.path??[],r=(e,n)=>n.reduce((e,n)=>e?.args?.[n],e),i=r(n,s),o=r(t,s);if(!i||!o||"="!==i.op||"="!==o.op)return[e];const a=e=>s.length?ee(n,s,e):e,[u,l]=i.args,[c,f]=o.args,p=[];let h=n;const d=(e,n,t,r)=>{const i=a(n);p.push({...this.step(e,"The same on both sides",["move"],h,i,{t:r}),path:s}),h=a(t),p.push({...this.step("solve.each-side","Work out each side",["arithmetic"],i,h),path:s})};if("solve.move"===e.id){const n=Ke(U("-",[u,c]));if(ke(n)!==ke(Ke(U("-",[l,f])))||we(n)&&n.q.isZero)return[e];const t=on(n).sort((e,n)=>Number(rn(n).size>0)-Number(rn(e).size>0));let s=u,r=l;t.forEach((e,n)=>{const i=we(e)?e.q.sign>0:!nn(e).s.endsWith(" neg"),a=nn(i?e:Ve(e)),u=U("=",[U(i?"-":"+",[s,a]),U(i?"-":"+",[r,a])]),l=n===t.length-1?o:U("=",[Ye(u.args[0]),Ye(u.args[1])]);d(i?"solve.both-subtract":"solve.both-add",u,l,a),[s,r]=l.args})}else{const n=Ke(U("/",[u,c])),t=e=>{const n=Ke(e);return we(n)&&n.q.isZero};if(!(!(!t(l)||!t(f))||!t(f)&&ke(n)===ke(Ke(U("/",[l,f]))))||rn(n).size||we(n)&&n.q.isZero)return[e];const s=we(n)&&!n.q.isInteger&&(1n===n.q.n||-1n===n.q.n),r=nn(s?Le(Ke(D("1")),n):n);d(s?"solve.both-multiply":"solve.both-divide",U("=",[U(s?"*":"/",[u,r]),U(s?"*":"/",[l,r])]),o,r)}return p.length&&p.at(-1).to===e.to?p:[e]}result(e,n,t,s={},r=null){let i=e;if(t.approximate&&i){i=Ft(i,{digits:"number"==typeof t.approximate?t.approximate:15})}return{result:i,text:i?this.format(i):"",steps:this.select(n,t.steps,r),...s}}variable(e,n){if(n&&!/^\\?[A-Za-z\u0370-\u03FF][A-Za-z0-9_\u0370-\u03FF′]*$/.test(n))throw new ne(`"${n}" is not a variable name; for a derivative at a point write der(f, x = a)`);if(n)return n;const t=[...rn(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 Ye(this.node(e))}rewrite(e,n,t={}){const s=this.node(e),r=this.set.view(n);if(!r.size)throw new ne(`no rules in mode "${n}" (modes: ${this.set.modes().join(", ")})`);const i=Kt(s,r,{format:this.format,order:t.order,variable:t.variable});return this.result(i.node,[...this.tidyStep(s,Ye(s)),...i.steps],t,{},s)}simplify(e,n={}){const t=this.node(e),s=[...this.tidyStep(t,Ye(t))],r=Kt(t,this.set.view("simplify"),{format:this.format});s.push(...r.steps);let i=r.node;const o=Ke(i),a=[],u=0===rn(i).size,l=u?null:Ls(o);l&&a.push({node:Ps(l),id:"simplify.cancel",name:"Cancel"});const c=Kt(nn(ks(o)),this.set.view("simplify"),{format:this.format});a.push({node:c.node,id:"simplify.expand",name:"Multiply out"}),"add"!==o.k||u||a.push({node:Ps(Zs(o)),id:"simplify.factor",name:"Factor"});const f=e=>G(e,"pre").some(({node:e})=>L(e)&&ji.has(e.op)&&G(e.args[0],"pre").some(({node:e})=>L(e)&&Ti.has(e.op)));for(const e of _r(this,i))a.push({node:e.node,id:"simplify.trig",wording:`simplify.trig.${e.how}`,name:"Trigonometric identities",prefer:f(i)&&!f(e.node)});let p=!1;for(const e of a)p&&"simplify.trig"===e.id&&!e.prefer||(e.prefer&&(p=!0),(J(e.node)<J(i)||e.prefer)&&(s.push(this.step(e.id,e.name,["shorter"],i,e.node,{},e.wording)),i=e.node));return this.result(i,s,n,{},t)}expand(e,n={}){const t=this.node(e),s=nn(ks(Ke(t)));return this.result(s,t.s===s.s?[]:[this.step("expand","Multiply out",["expand"],t,s)],n,{},t)}factor(e,n={}){const t=this.node(e),s=Zs(Ke(t)),r=Ps(s),i=[],o=s.notes.find(e=>"factor.common"===e.id);return r.s!==Ye(t).s&&i.push(this.step(o?"factor.common":"factor","Factor",["factor"],t,r,o?{common:nn(o.values.common)}:{})),this.result(r,i,n,{},t)}cancel(e,n={}){const t=this.node(e),s=Ke(t),r=Ls(s);if(!r)return this.result(Ye(t),this.tidyStep(t,Ye(t)),n,{},t);const i=Ps(r),o=Vs(s),a=U("/",[nn(o.num),nn(o.den)]),u=[];return"/"===t.op&&a.s===Ye(t).s||u.push(this.step("together","One fraction",["together"],t,a)),i.s!==a.s&&u.push(this.step("cancel","Cancel",["cancel"],a,i,{canceled:r.canceled.length?r.canceled.map(e=>this.format(nn(e))).join(", "):"numbers"})),this.result(i,u,n,{},t)}diff(e,n,t={}){const s=this.node(e),r=this.variable(s,n),i="string"==typeof t.steps?t.steps:t.steps?.detail,o=es(s),a={diff:this.set.view("differentiate"),simp:this.set.view("simplify")};let u=o;const l=[];for(let e=0;e<(t.order??1);e++){const e=rs(U("der",[u,D(r)]),a.diff,{fold:"full"===i?null:a,format:this.format}),n=rs(e.node,a.simp,{format:this.format,order:"post",maxSteps:40}),t=Ye(n.node),s=Kt(t,a.simp,{format:this.format});l.push(...e.steps,...n.steps,...this.tidyStep(n.node,t),...s.steps),u=s.node}const c=Ke(u),f=rn(u).size?Ls(c):null,p=[f&&{node:Ps(f),id:"simplify.cancel",name:"Cancel"},{node:nn(ks(c)),id:"simplify.expand",name:"Multiply out"}].find(e=>e&&J(e.node)<J(u));return p&&(l.push(this.step(p.id,p.name,["shorter"],u,p.node)),u=p.node),this.result(u,l,t,{variable:r},U("der",[s,D(r)]))}differentiate(e,n){const t=Kt(U("der",[e,D(n)]),this.set.view("differentiate"),{format:this.format,order:"pre"});return Kt(t.node,this.set.view("simplify"),{format:this.format}).node}integrate(e,n,t={}){n&&"object"==typeof n&&(t=n,n=void 0);let s=this.node(e);const r=s,i=e=>void 0===e?null:this.node("number"==typeof e?String(e):e);let o=i(t.from),a=i(t.to);if(L(s)&&"int"===s.op){const[e,t,r,i]=s.args;n=t.token,r&&i&&(o=r,a=i),s=e}const u=this.variable(s,n),l=ri(this,s,u),c=Kt(l.node,this.set.view("simplify"),{format:this.format}),f=[...l.steps,...c.steps];if(o&&a){const e=yi(this,c.node,u,o,a,s);f.push(e.step);const n=Kt(e.value,this.set.view("simplify"),{format:this.format});return f.push(...this.tidyStep(e.shown,e.value),...n.steps),this.result(n.node,f,t,{antiderivative:c.node,variable:u},L(r)&&"int"===r.op?r:null)}let p=c.node;if(t.constant){const e=new Set([...rn(s),u]);p=U("+",[p,D(!0===t.constant?["C","c","K"].find(n=>!e.has(n))??"C":String(t.constant))])}return this.result(p,f,t,{variable:u},L(r)&&"int"===r.op?r:U("int",[r,D(u)]))}solve(e,n,t={}){const s=this.node(e),r=this.variable(s,n);if(L(s)&&Ei.has(s.op))return this.inequality(s,r,t);const i=Js(this,s,r,t);let o=i.solutions;if(t.approximate){const e="number"==typeof t.approximate?t.approximate:15;o=o.map(n=>Ft(n,{digits:e}))}const a=e=>e.length?e.map(e=>U("=",[D(r),e])).reduce((e,n)=>e?U("|",[e,n]):n,null):null,u=(i.base??o).map(e=>U("=",[D(r),e])),l=a(i.base??o),c=ws(i.steps,s,{parse:_,replaceAt:ee}),f=e=>L(e)&&"|"===e.op?e.args.flatMap(f):[e.s],p=c[c.length-1];if(p&&l&&!t.approximate){let e=null;try{e=_(p.to)}catch{}if(e&&e.s!==l.s&&f(e).sort().join("\n")===f(l).sort().join("\n"))p.to=l.s;else if(e&&e.s!==l.s){const n=e=>L(e)&&"|"===e.op?e.args.flatMap(n):[e],t=n(e);t.length>=u.length&&t.every(e=>L(e)&&"="===e.op&&e.args[0].s===r)&&c.push(this.step("normal","Work out and collect",["tidy","arithmetic"],e,l))}}const h=i.base?a(o):l;if(i.base&&l&&!t.approximate){const e=c.length?_(c[c.length-1].to):l;h&&h.s===e.s||c.push(this.step("solve.interval","The answers in the interval",["interval"],e,h??e,{lo:i.interval[0],hi:i.interval[1],v:D(r),count:String(o.length)}))}return i.steps=c,{solutions:o,result:h,variable:r,text:i.always?`true for every ${r}`:h?this.format(h):i.unsolved.length?`no exact solution found for ${r}`:"no solution",unsolved:i.unsolved.filter(e=>!e.always),always:i.always,periodic:Boolean(i.periodic),period:i.period??null,...i.interval?{interval:i.interval}:{},steps:this.select(i.steps,t.steps,s)}}inequality(e,n,t){const s=wr(this,e,n,t),r={solutions:[],variable:n,unsolved:[],always:!1,steps:this.select(s.steps,t.steps,e)};if(!s.pieces)return{...r,pieces:null,intervals:"",result:null,unsolved:[e],text:`no exact solution found for ${n}`};const i=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?U("=",[i,e]):e||n?e?n?U(s?"≤":"<",[U(t?"≤":"<",[e,i]),n]):U(t?"≥":">",[i,e]):U(s?"≤":"<",[i,n]):null).filter(Boolean).reduce((e,n)=>e?U("|",[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{...r,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 r=this.node(e),i=Rr(r);if(!i&&G(r,"pre").some(({node:e})=>Rr(e))){let e=r;for(const{node:n,path:t}of G(r,"post").filter(({node:e})=>Rr(e)).reverse()){const s=this.limit(n,void 0,void 0,{steps:!1});if(!s.exists)return s;if(s.infinite)throw new ne("a limit inside an expression that is infinite is not worked out here");e=ee(e,t,s.result)}return{...this.simplify(e,s),exists:!0,infinite:!1}}const o=i?i.f:r,a=i?i.v:this.variable(r,n),u=i?i.to:"number"==typeof t?W(String(t)):this.node(t??"0"),l="right"===s.side||"+"===s.side?1:"left"===s.side||"-"===s.side?-1:i?i.side:0;try{const{value:e,steps:n}=Zr(this,o,a,Pr(u),l);return{...this.result(Ur(e),ws(n,Ye(o),{parse:_,replaceAt:ee}),s),exists:!0,infinite:Boolean(e.inf)}}catch(e){if(!(e instanceof qr))throw e;const n={result:null,text:"does not exist",exists:!1,reason:e.message,steps:[]};if(!l&&!Pr(u).inf){const e=e=>{try{return Ur(Zr(this,o,a,Pr(u),e).value)}catch{return null}};n.left=e(-1),n.right=e(1)}return n}}solveSystem(e,n,t={}){const s=e.map(e=>this.node(e)),r=n??[...new Set(s.flatMap(e=>[...rn(e)]))].sort(),i=function(e,n,t){const s=[],r=n.map(n=>{const s=Qs(n)?Ee([Ke(n.args[0]),Ve(Ke(n.args[1]))]):Ke(n),r=t.map(n=>{const t=Ss(s,n);if(!t||Math.max(0,...t.keys())>1)throw new ne(`not linear in ${n}`);const r=t.get(1)??ge(oe.ZERO);if(!we(r))throw new ne(`the coefficient of ${n} must be a number (it is ${e.format(nn(r))})`);return r.q});let i=s;for(let e=0;e<t.length;e++)i=Ee([i,Te([ge(r[e].neg()),Ke(D(t[e]))])]);for(const e of t)if(Ms(i,e))throw new ne(`not linear in ${e}`);return{coeffs:r,rhs:Ve(i)}}),i=()=>r.map(e=>_s(nn(Ee(e.coeffs.map((e,n)=>Te([ge(e),Ke(D(t[n]))])))),nn(e.rhs))).reduce((e,n)=>e?U("&",[e,n]):n,null),o=e=>gr[e]??`${e+1}th`,a=(n,t,r,o)=>{const a=i();a.s!==r.s&&s.push(e.step(n,t,["eliminate"],r,a,o))};let u=0;const l=[];for(let e=0;e<t.length&&u<r.length;e++){const n=r.findIndex((n,t)=>t>=u&&!n.coeffs[e].isZero);if(n<0)continue;const s=D(t[e]);if(n!==u){const e=i();[r[u],r[n]]=[r[n],r[u]],a("system.swap","Swap",e,{v:s,row:o(u),other:o(n)})}const c=r[u],f=c.coeffs[e];if(!f.equals(oe.ONE)){const e=i();c.coeffs=c.coeffs.map(e=>e.div(f)),c.rhs=Te([ge(f.inv()),c.rhs]),a("system.scale","Divide",e,{v:s,row:o(u),by:nn(ge(f))})}for(let n=0;n<r.length;n++){if(n===u||r[n].coeffs[e].isZero)continue;const t=i(),l=r[n].coeffs[e];r[n].coeffs=r[n].coeffs.map((e,n)=>e.sub(l.mul(c.coeffs[n]))),r[n].rhs=Ee([r[n].rhs,Te([ge(l.neg()),c.rhs])]);const f=l.sign<0?l.neg():l,p=f.equals(oe.ONE);a(`system.${l.sign<0?"add":"subtract"}${p?"":"-multiple"}`,"Eliminate",t,{v:s,row:o(n),from:o(u),k:nn(ge(f))})}l.push(e),u++}for(const e of r.slice(u))if(!we(e.rhs)||!e.rhs.q.isZero)return{solution:null,steps:s,status:"none"};if(l.length<t.length)return{solution:null,steps:s,status:"many"};const c=new Map;return l.forEach((e,n)=>c.set(t[e],nn(r[n].rhs))),{solution:c,steps:s,status:"one"}}(this,s,r),o=i.solution?Object.fromEntries([...i.solution].map(([e,n])=>[e,n])):null,a="one"===i.status?r.map(e=>`${e} = ${this.format(o[e])}`).join(", "):"none"===i.status?"no solution":"infinitely many solutions";return{solution:o,status:i.status,text:a,steps:this.select(i.steps,t.steps)}}substitute(e,n,t={}){const s=this.node(e);let r=s;for(const[e,t]of Object.entries(n))r=er(r,e,"number"==typeof t?this.node(String(t)):this.node(t));const i=this.simplify(r,t),o=[this.step("substitute","Substitute",["substitute"],s,r)];return{...i,steps:[...this.select(o,t.steps),...i.steps]}}defined(e){const n=this.set.view("define");return n.size?Kt(e,n,{format:this.format}).node:e}approximate(e,n={}){const t=this.defined(this.node(e));if(rn(t).size&&!n.scope){const e=Ft(Ye(t),n);return{result:e,text:this.format(e),number:null,exact:!1}}const s=zt(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),r=this.defined(U("-",[t,s])),i=this.simplify(r,{steps:!1}).result;if("num"===i.type&&"0"===i.token)return{equal:!0,how:"exact"};const o=[...rn(r)];if(!o.length)try{return{equal:Math.abs(zt(r,{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=zt(r,{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 Fi(e={}){const n=!1===e.defaults?[]:[...Ii,...e.complex?Ai:[]],{specs:t,messages:s}=function(e){Vt();const n=[],t={};for(const s of e){const e="string"==typeof s?Bn(s):s,r=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)||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 r)n.push(e)}return{specs:n,messages:t}}([...n,...e.rules??[]]),r=he(e.complex,()=>Lt(t)),i={...zi};for(const e of Object.keys(s))for(const n of Object.keys(i))n.startsWith(`${e}.`)&&!(n in s)&&delete i[n];return new Ci(r,{...i,...s},e.format??ki,e.read??null,Boolean(e.complex))}function Bi(n){const t=n=>e("op"===n.type?Ri(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 Di={"+":"+","-":"-","*":"*","/":"/","^":"^",mod:"mod","±":"±","=":"=","===":"===","≠":"≠","≠=":"≠","<":"<",">":">","≤":"≤","≥":"≥","∈":"∈","∉":"∉","→":"→","≈":"≈","∪":"∪","∩":"∩","≡":"≡","&":"∧","|":"∨","\\xor":"⊕","\\nand":"↑","\\nor":"↓","\\implies":"⇒","\\iff":"⇔"},Wi={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]};function Ri(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=>d(m,e)?`(${c(e)})`:c(e);if("*"===m&&n(e))return Ri({...e,op:"neg",args:[b]},c);if("+"===m&&n(b))return Ri({...e,op:"-",args:[v,b.args[1]]},c);if("-"===m&&n(b))return Ri({...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(Di[m])return`${y(v,"left")} ${Di[m]} ${y(b,"right")}`;if(t[m])return`${m}(${s(e).map(e=>`[${e.map(c).join(", ")}]`).join(", ")})`;if(Wi[m])return Wi[m][0]+w()+Wi[m][1];if(r(m))return`${i(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"setbuilder":return`{${g.map(c).join(" : ")}}`;case"evaluated":return`evaluated(${g.map(c).join(", ")})`;case"der":{const{n:n,body:t,by:s,at:r,variable:i}=o(e);if(r)return`der(${c(t)}, ${c(s)} = ${c(r)}${n>1?`, ${n}`:""})`;const a=n>1?`^${n}`:"";return i?`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,r,i]=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,r,i]=e;return 4===e.length?`lim(${n(t)}, ${n(s)}, ${n(r)}, ${p(i).toLowerCase().startsWith("r")?"r":"l"})`:`lim(${e.map(n).join(", ")})`}(g,c);case"\\sumidx":return Pi("∑",g,c);case"\\prodidx":return Pi("∏",g,c)}return`${m}(${w()})`}function Pi(e,n,t){const[s,r,i]=n,o="∑"===e?"sum":"prod";if(3===n.length&&"op"===r.type&&"="===r.op)return`${o}(${t(s)}, ${t(r)}, ${t(i)})`;if(2===n.length&&"op"===r.type&&"∈"===r.op)return`${o}(${t(s)}, ${t(r)})`;const a=f(s);return 3===n.length&&a?`${o}(${t(s)}, ${a} = ${t(r)}, ${t(i)})`:1===n.length?`${e} ${t(s)}`:2===n.length?`${e}[${t(r)}] ${t(s)}`:`${e}[${t(r)}, ${t(i)}] ${t(s)}`}for(const e of[Di,Wi])Object.setPrototypeOf(e,null);const Ui=Symbol.for("inlinemath.expressions"),Vi=new Map,Li={re:"Re",im:"Im",conj:"overline"},_i=["Re","Im","re","im","conj","arg"];function Hi(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),`\\:${Li[e.op]??e.op}`)):n.push(e.token)};return t(e),n}function Qi(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=y(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 w(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 Ji={right:"right",r:"right","+":"right",left:"left",l:"left","-":"left"},Ki=new Set(["simplify","expand","factor","cancel","diff","integrate","solve","approx","limit"]),Yi={integral:"integrate",differentiate:"diff",approximate:"approx",simp:"simplify"};function Gi(e={}){const n=e.rules||e.names?null:e.complex?"complex":"default";if(n&&Vi.has(n))return Vi.get(n);const t=[...e.names??[],...e.complex?_i:[],...Ki,...Object.keys(Yi)],s=Fi({...e,read:e=>v(e,{names:t}),format:ki});return n&&Vi.set(n,s),s}function Xi(e={}){const n=e.cas??Gi(),t=void 0===e.steps?{}:{steps:e.steps},s=(e,r)=>{let i;try{i=n.read(e)}catch{return x(e,r)}const o=r&&r[Ui];o&&(i=i.flatMap(e=>Object.hasOwn(o,e)?o[e]:[e])),i=Qi(i,r);const a=i[i.length-1],u=a?.startsWith("\\:")?Yi[a.slice(2)]??a.slice(2):null,l=u&&Ki.has(u),c="der"===a||"int"===a||"lim"===a;if(!l&&!c)return x(e,r);const f=n.node(i),p=c&&f.op!==a,h=l?f.args:[f],d=e=>e?e.s:void 0,v=(e,s,r)=>{if(!s||"="!==s.op)return n.diff(e,d(s),{...t,order:r});const i=s.args[0].s,o=n.diff(e,i,{...t,order:r}),a=n.substitute(o.result,{[i]: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,r,i])=>{let o=i?Ji[i.s.replace(/^\\/,"")]:void 0;if(i&&!o)throw new Error(`a side is right or left, not ${i.s}`);if(s&&"→"===s.op){[s,r]=s.args;const e="^"===r.op?r.args[1].s.replace(/^\\/,""):null;"+"!==e&&"-"!==e||(o=Ji[e],r=r.args[0])}return n.limit(e,d(s),r,{...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 y=(w=Hi(b.result),m(w)?"":Bi(g(w)));var w;return/^-?\d+(\.\d+)?$/.test(y)?y:`(${y})`};return s}const eo=e=>String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function no(e,n={}){return`<ol class="mv-steps">${e.map(e=>{const t=Hi(_(e.from)),s=q(t,{...n,highlight:e.path&&e.path.length?{path:e.path}:void 0}),r=e.to===e.from?"":`<span class="mv-step-arrow" aria-label="becomes">⟶</span>${q(Hi(_(e.to)),n)}`,i=e.explanation?`<p class="mv-step-why">${eo(e.explanation)}</p>`:"";return`<li class="mv-step" data-rule="${eo(e.id)}"><span class="mv-step-name">${eo(e.name)}</span><div class="mv-step-maths">${s}${r}</div>${i}</li>`}).join("")}</ol>`}export{Xi as casBlocks,Gi as mathCAS,no as stepsHTML,Hi as tokensOf};