@mathzetta/inlinemath 0.4.0 → 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.
@@ -1,2 +1,2 @@
1
- /* Inline Math 0.4.0 — MIT license; MathZetta not included: load a MathZetta <script> (mathzetta.min.js or mathzetta.maths-display.min.js) first */
2
- var InlineMath=function(e,t,n,s,i){"use strict";const r={"(":{fill:"M0.92,0 C0.1,0.2 0.1,0.8 0.92,1 L1,0.975 C0.48,0.75 0.48,0.25 1,0.025 Z"},")":{fill:"M0.08,0 C0.9,0.2 0.9,0.8 0.08,1 L0,0.975 C0.52,0.75 0.52,0.25 0,0.025 Z"},"{":{fill:"M1,0 C0.45,0 0.5,0.05 0.5,0.2 L0.5,0.38 C0.5,0.46 0.35,0.49 0.05,0.5 C0.35,0.51 0.5,0.54 0.5,0.62 L0.5,0.8 C0.5,0.95 0.45,1 1,1 L1,0.985 C0.68,0.985 0.64,0.95 0.64,0.8 L0.64,0.62 C0.64,0.53 0.55,0.505 0.3,0.5 C0.55,0.495 0.64,0.47 0.64,0.38 L0.64,0.2 C0.64,0.05 0.68,0.015 1,0.015 Z"},"}":{fill:"M0,0 C0.55,0 0.5,0.05 0.5,0.2 L0.5,0.38 C0.5,0.46 0.65,0.49 0.95,0.5 C0.65,0.51 0.5,0.54 0.5,0.62 L0.5,0.8 C0.5,0.95 0.55,1 0,1 L0,0.985 C0.32,0.985 0.36,0.95 0.36,0.8 L0.36,0.62 C0.36,0.53 0.45,0.505 0.7,0.5 C0.45,0.495 0.36,0.47 0.36,0.38 L0.36,0.2 C0.36,0.05 0.32,0.015 0,0.015 Z"},sqrt:{stroke:"M0,0.62 L0.18,0.55 L0.45,0.97 L0.98,0"},cancel:{stroke:"M0,1 L1,0"},int:{stroke:"M0.95,0.09 C0.9,0.01 0.72,0 0.66,0.12 C0.6,0.25 0.42,0.75 0.34,0.88 C0.28,0.99 0.1,0.99 0.05,0.91"},sum:{fill:"M0.04,0 L0.94,0 L0.98,0.24 L0.94,0.24 C0.9,0.1 0.8,0.07 0.62,0.07 L0.24,0.07 L0.58,0.5 L0.2,0.93 L0.64,0.93 C0.82,0.93 0.92,0.9 0.95,0.76 L0.99,0.76 L0.94,1 L0.02,1 L0.47,0.47 Z"},prod:{fill:"M0,0 L1,0 L1,0.04 L0.88,0.05 L0.88,0.95 L1,0.96 L1,1 L0.62,1 L0.62,0.96 L0.74,0.95 L0.74,0.06 L0.26,0.06 L0.26,0.95 L0.38,0.96 L0.38,1 L0,1 L0,0.96 L0.12,0.95 L0.12,0.05 L0,0.04 Z"}};function o(e,t,n=""){const s=r[e];return`<svg class="${t}" viewBox="0 0 1 1" preserveAspectRatio="none" aria-hidden="true"${n?` style="${n}"`:""}>${s.fill?`<path d="${s.fill}" fill="currentColor"/>`:`<path d="${s.stroke}" fill="none" stroke="currentColor" vector-effect="non-scaling-stroke"/>`}</svg>`}const a=.8,u=.2,l=.25,c=.7,p="−",h={"+":"add","-":"sub","*":"mul","/":"frac","^":"pow",_:"subscript",neg:"neg",pm:"pm","!":"factorial","=":"eq","===":"eq","≠":"neq","≠=":"neq","<":"lt",">":"gt","≤":"le","≥":"ge","≈":"approx","≡":"equiv","∈":"in","∉":"notin","∪":"union","∩":"intersect","→":"to","±":"pm","&":"and","|":"or","\\not":"not","\\xor":"xor","\\nand":"nand","\\nor":"nor","\\implies":"implies","\\iff":"iff","?:":"cases","()":"tuple","[]":"list","{}":"set","(]":"interval","[)":"interval","\\sumidx":"sum","\\prodidx":"prod",mod:"mod",pmod:"pmod",pmatrix:"matrix",bmatrix:"matrix",vmatrix:"matrix"},f={"=":"=","===":"=","≠":"≠","≠=":"≠","<":"<",">":">","≤":"≤","≥":"≥","∈":"∈","∉":"∉","→":"→","≈":"≈","≡":"≡","&":"∧","|":"∨","\\xor":"⊕","\\nand":"↑","\\nor":"↓","\\implies":"⇒","\\iff":"⇔"},d={"±":"±","∪":"∪","∩":"∩",mod:"mod"},m=["sin","cos","tan","csc","sec","cot","sinh","cosh","tanh"],g={arcsin:"sin",arccos:"cos",arctan:"tan",arcsec:"sec",arccsc:"csc",arccot:"cot",arcsinh:"sinh",arccosh:"cosh",arctanh:"tanh"},v=[...m,...Object.keys(g),"ln","det"],b={atan2:"atan2",max:"max",min:"min",gcd:"gcd",mean:"mean",round:"round",fixed:"fixed",expm1:"expm1",random:"random"},y={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]},w=["int","lim","\\sumidx","\\prodidx"],x={"\\partial":"∂","\\nabla":"∇","\\ell":"ℓ","\\infty":"∞","\\emptyset":"∅"},k={vec:"→",hat:"ˆ",widehat:"ˆ",tilde:"˜",dot:"˙",ddot:"¨"},q=/^[acegmnopqrsuvwxyzαγεημνοπρστυχω]$/,$=e=>"symbol"===e?.type&&q.test(n.GREEK[e.value]??e.value),S=["boxed","overline","bar","underline","cancel",...Object.keys(k)],M={prefix:"mv",display:!0,fnParens:"auto",trigPowers:!0,inverseTrig:"arc",derivativeBrackets:"[",scriptFractions:"slash",cases:!0,label:!0,mathml:null,attributes:null,style:null},O=e=>String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),A=e=>+e.toFixed(3)+"em",N=(e,t=a,n=u)=>({html:e,h:t,d:n});function E(...e){const t=e.flat().filter(Boolean);return{html:t.map(e=>e.html).join(""),h:Math.max(a,...t.map(e=>e.h)),d:Math.max(u,...t.map(e=>e.d))}}function I(e,t={}){const n=new T({...M,...t}),i=n.render(e,{level:0}),r=`${n.p}${n.o.display?` ${n.p}-display`:""}`,o="function"==typeof n.o.mathml?function(e,t,n,s){try{return String(e(t)).replace(/ id="mz-\d+"/g,"").replace(/^<math>/,`<math class="${n}-sr-math"${s?' display="block"':""}>`)}catch{return""}}(n.o.mathml,e,n.p,n.o.display):"",a=o?null:function(e,t){if(!1===t||null===t)return null;if("string"==typeof t)return t;try{return"function"==typeof t?t(e):s.toAudioSpeech(e)}catch{return null}}(e,n.o.label),u=null!==a||o?i.html.replace(/^<span /,'<span aria-hidden="true" '):i.html;return{html:`<span class="${r}"${null===a?"":` role="math" aria-label="${O(a)}"`}>${u}${o}</span>`,h:i.h,d:i.d}}class T{constructor(e){this.o=e,this.p=e.prefix}el(e,t,n="",s=""){return`<span class="${e.split(" ").map(e=>`${this.p}-${e}`).join(" ")}"${n?` style="${n}"`:""}${s}>${t}</span>`}text(e,t){const n=N(this.el(e,O(t)));return n.leaf={kind:e,content:O(t)},n}bin(e){return this.text("bin",e)}rel(e){return this.text("rel",e)}punct(e){return this.text("punct",e)}word(e){return this.text("word",e)}wrap(e,t,n){let s="";void 0!==e.id&&(s+=` data-node="${e.id}"`),"op"===e.type&&(s+=` data-op="${O(e.op)}"`);const i=this.o.attributes&&this.o.attributes(e)||{};for(const[e,t]of Object.entries(i))"class"!==e&&"style"!==e&&/^[A-Za-z_:][\w:.-]*$/.test(e)&&(s+=` ${e}="${O(t)}"`);const r=[i.style,this.o.style&&this.o.style(e)].filter(Boolean).join(";"),o=(n.leaf?["n",...t,n.leaf.kind]:["n",...t]).map(e=>`${this.p}-${e}`).concat(i.class?[O(i.class)]:[]).join(" "),a=n.leaf?n.leaf.content:n.html;return{html:`<span class="${o}"${r?` style="${O(r)}"`:""}${s}>${a}</span>`,h:n.h,d:n.d}}render(e,t){return"number"===e.type?this.number(e):"string"===e.type?this.wrap(e,["text"],this.text("text",e.value.replace(/^["'`]|["'`]$/g,""))):"symbol"===e.type?this.wrap(e,["symbol"],this.symbol(e.value)):this.operation(e,t)}number(e){const t=/^(-?\d*\.)(\d*)\.\.$/.exec(e.value);if(t){const[,n,s]=t;let i=1;for(let e=1;2*e<=s.length;e++)if(s.slice(-e)===s.slice(-2*e,-e)){i=e;break}let r=s;for(;r.endsWith(s.slice(-i))&&r.length>=i;)r=r.slice(0,-i);const o=this.text("num",(n+r).replace(/^-/,p)),a=this.text("num",s.slice(-i));return this.wrap(e,["number"],E(o,N(this.el("over",a.html),a.h+.14,a.d)))}return this.wrap(e,["number"],this.text("num",e.value.replace(/^-/,p)))}symbol(e){return n.GREEK[e]&&(e=n.GREEK[e]),x[e]?this.text("ord",x[e]):"\\+"===e||"\\-"===e?this.text("ord",e[1]):"-∞"===e?this.text("ord","−∞"):/^[A-Za-z]$/.test(e)||/^[α-ω]$/.test(e)?this.text("var",e):/^[A-Za-z]′+$/.test(e)?N(this.el("var",O(e[0]))+this.el("prime",O(e.slice(1)))):/^Δ[A-Za-z]$/.test(e)?N(this.el("ord","Δ")+this.el("var",e[1])):/^d[A-Za-zα-ω]$/.test(e)?N(this.el("ord","d")+this.el("var",e[1])):e.endsWith("⁻¹")?this.script(this.symbol(e.slice(0,-2)),this.text("num","−1"),{level:0}):/^\\[A-Za-z]+$/.test(e)?this.text("name",e.slice(1)):/^[A-Za-z]{2,}$/.test(e)?this.text("name",e):this.text("ord",e)}operation(e,t){const{op:s,args:i}=e,[r,o]=i,a=(e,n={})=>this.render(e,{...t,...n,forceParens:n.forceParens||!1,before:n.before||!1,leftFactor:!1}),u=h[s]??(/^[a-z0-9]+$/i.test(s)?s:"other"),l=t=>this.wrap(e,["op",`op-${u}`],t),c=(t,s)=>n.needsBrackets(e,t,s)&&"/"!==t.op?this.fence(a(t)):a(t);if(v.includes(s)||"log"===s)return l(this.named(e,t));if(b[s])return l(E(this.word(b[s]),this.fence(this.list(i,t))));if(n.isCustomFunction(s))return l(this.custom(e,t));const m=n.matrixRows(e);if(m)return l(this.matrix(e,m,t));if("{}"===s&&!i.length)return l(this.text("op","∅"));if(y[s])return l(this.fence(this.list(i,t),...y[s]));if(("|"===s||"&"===s)&&i.length>=2&&i.every(z)){const e=e=>"|"!==e.op&&"&"!==e.op||e.op===s?a(e):this.fence(a(e));return l(E(i.map((t,n)=>n?[this.text("conj","|"===s?"or":"and"),e(t)]:[e(t)]).flat()))}if(f[s]&&2===i.length)return l(E(c(r,"left"),this.rel(f[s]),c(o,"right")));if(d[s]&&2===i.length)return l(E(c(r,"left"),this.bin(d[s]),c(o,"right")));switch(s){case"+":if(n.isMinusOneTimes(o)){const e=o.args[1],t=n.needsBrackets({op:"-"},e,"right")?this.fence(a(e)):a(e);return l(E(c(r,"left"),this.bin(p),this.wrap(o,["op","op-mul"],t)))}return"number"===o.type&&o.value.startsWith("-")?l(E(c(r,"left"),this.bin(p),this.wrap(o,["number"],this.text("num",o.value.slice(1))))):l(E(c(r,"left"),this.bin("+"),this.signed(o,c(o,"right"))));case"-":return l(E(c(r,"left"),this.bin(p),this.signed(o,c(o,"right"))));case"*":return l(this.product(e,t));case"/":return l(this.fraction(e,t));case"^":return l(this.power(e,t));case"_":{const e=n.bracketOp(r)&&n.precedenceOf(n.bracketOp(r))<100;return l(this.script(e?this.fence(a(r)):a(r,{forceParens:!0}),null,t,a(o,{level:t.level+1})))}case"neg":return l(E(this.text("sign",p),n.unaryNeedsBrackets(s,r)?this.fence(a(r)):a(r,{before:t.before})));case"pm":return l(E(this.text("sign","±"),n.unaryNeedsBrackets(s,r)?this.fence(a(r)):a(r)));case"!":return l(E(n.unaryNeedsBrackets(s,r)?this.fence(a(r)):a(r,{forceParens:!0}),this.text("ord","!")));case"\\not":return l(E(this.text("sign","¬"),n.unaryNeedsBrackets(s,r)?this.fence(a(r)):a(r)));case"pmod":return l(E(a(r),this.fence(E(this.word("mod"),this.text("space",""),a(o)))));case"sqrt":return l(this.radical(a(r)));case"root":return l(this.radical(a(o),this.render(r,{level:t.level+2})));case"abs":return l(this.fence(a(r),"|","|"));case"floor":return l(this.fence(a(r),"⌊","⌋"));case"ceil":return l(this.fence(a(r),"⌈","⌉"));case"loglog":return l(E(this.word("ln"),this.fence(E(this.word("ln"),this.fence(a(r))))));case"logloglog":return l(E(this.word("ln"),this.fence(E(this.word("ln"),this.fence(E(this.word("ln"),this.fence(a(r))))))));case"perm":return l(this.script(this.script(N(""),this.render(r,{level:t.level+1}),t),null,t,this.render(o,{level:t.level+1}),this.word("P")));case"comb":return l(this.fence(this.stack(a(r),a(o),!1)));case"?:":return l(this.o.cases?this.cases(e,t):E(a(r),this.bin("?"),a(o),this.bin(":"),a(i[2])));case"sum":case"prod":{const e={op:"sum"===s?"+":"*"},t=(t,s)=>n.needsBrackets(e,t,s?"right":"left")?this.fence(a(t)):a(t);return l(E(i.map((e,n)=>n?[this.bin("sum"===s?"+":"·"),t(e,n)]:[t(e,n)]).flat()))}case"setbuilder":return l(this.fence(E(a(r),this.bin("|"),a(o)),"{","}"));case"evaluated":{const e=e=>this.render(e,{...t,level:t.level+1});return l(this.script(this.fence(a(r),"[","]"),e(i[3]),t,e(i[2])))}case"der":return l(this.derivative(e,t));case"int":return l(this.integral(i,t));case"lim":return l(this.limit(i,t));case"\\sumidx":return l(this.bigOperator("sum",i,t));case"\\prodidx":return l(this.bigOperator("prod",i,t))}throw new Error(`Inline Math cannot draw '${s}'`)}signed(e,t){return("number"===e.type?e.value.startsWith("-"):"neg"===e.op||"pm"===e.op)&&!t.fenced?this.fence(t):t}list(e,t){return E(e.map((e,n)=>n?[this.punct(","),this.render(e,t)]:[this.render(e,t)]).flat())}product(e,t){const[s,i]=e.args;if(n.isMinusOneTimes(e))return E(this.text("sign",p),n.unaryNeedsBrackets("neg",i)?this.fence(this.render(i,t)):this.render(i,t));const r=n.bracketedSides(e);w.includes(s.op)&&(r.left=!0);const o=!e.written&&n.isImplicitProduct(s,i,r),a=function(e){for(;"op"===e.type;){if(v.includes(e.op)||"log"===e.op||b[e.op]||n.isCustomFunction(e.op))return!0;if("^"!==e.op&&"*"!==e.op)return!1;e=e.args[0]}return!1}(i),u=r.left?this.fence(this.render(s,t)):this.render(s,{...t,before:o&&!a,leftFactor:!0}),l=r.right?this.fence(this.render(i,t)):this.render(i,{...t,before:t.before});return E(u,o?N(this.el(a?"fnspace":"times","")):this.bin("cross"===e.written?"×":"·"),l)}named(e,t,n=null){const{op:s,args:i}=e,r="log"===s?i[1]:i[0];let o;o=g[s]&&"power"===this.o.inverseTrig?this.script(this.word(g[s]),this.text("num","−1"),t):this.word(s),n&&(o=this.script(o,n,t)),"log"===s&&(o=this.script(o,null,t,this.render(i[0],{level:t.level+1})));const a="auto"===this.o.fnParens&&!t.forceParens&&!t.before&&L(r),u=this.render(r,{...t,forceParens:!1,before:!1});return E(o,a?E(N(this.el("fnspace","")),u):this.fence(u))}custom(e,t){const s=n.customName(e.op),i=e.args;if(S.includes(s)&&1===i.length)return this.decorate(s,this.render(i[0],t),i[0]);return E(/^[A-Za-z]′*(⁻¹)?$/.test(s)?this.symbol(s):this.word(s),N(this.el("callgap","")),this.fence(this.list(i,t)))}decorate(e,t,n){switch(e){case"boxed":return N(this.el("boxed",t.html),t.h+.22,t.d+.22);case"cancel":return N(this.el("cancel",t.html+o("cancel",`${this.p}-cancel-line`)),t.h,t.d);case"underline":return N(this.el("underline",t.html),t.h,t.d+.12);case"overline":case"bar":return N(this.el("over"+($(n)?" over-low":""),t.html),t.h+.14,t.d);default:{const s=$(n);return N(this.el("accent"+(s?" accent-low":""),this.el(`accent-mark accent-${e}`,k[e])+t.html),t.h+.3,t.d)}}}fraction(e,t){const[s,i]=e.args;if(t.level>0&&"slash"===this.o.scriptFractions&&L(s,!0)&&L(i,!0)){const e={...t,leftFactor:!1},r=(t,s)=>"op"!==t.type||L(t)&&(!s||"*"!==t.op||n.isMinusOneTimes(t))?this.render(t,e):this.fence(this.render(t,e)),o=E("op"===s.type&&"neg"===s.op?this.render(s,e):r(s,!1),this.text("ord","/"),r(i,!0));return t.leftFactor?this.fence(o):o}const r=t.level>0||t.inFraction||!this.o.display?.8:1,o={...t,inFraction:!0,forceParens:!1,before:!1};return this.stack(this.render(s,o),this.render(i,o),!0,r)}stack(e,t,n=!0,s=1){const i=e=>1===s?e.html:this.el("scaled",e.html,`font-size:${A(s)}`),r=n?.06:0,o=l+r/2+.1+Math.max(u,s*e.d),c=this.el("frac"+(n?"":" frac-nobar"),this.el("numer",i(e))+this.el("denom",i(t)),`vertical-align:${A(o)}`);return N(c,o+Math.max(a,s*e.h),Math.max(a,s*t.h)+Math.max(u,s*t.d)+.1+r/2-l)}power(e,t){const[s,i]=e.args,r={...t,level:t.level+1,forceParens:!1,before:!1,inFraction:!1,leftFactor:!1},o=()=>this.render(i,r);if(this.o.trigPowers&&m.includes(s.op)&&Z(i))return this.wrap(s,["op",`op-${s.op}`],this.named(s,t,o()));if("_"===s.op){const e=this.render(s.args[1],r);return this.wrap(s,["op","op-subscript"],this.script(this.render(s.args[0],{...t,forceParens:!0}),o(),t,e))}const a=n.needsBrackets(e,s,"left")||"number"===s.type&&s.value.startsWith("-")||"/"===s.op||v.includes(s.op)||w.includes(s.op)?this.fence(this.render(s,t)):this.render(s,{...t,forceParens:!0});return this.script(a,o(),t)}script(e,t,n,s=null,i=null){const r=n.level>0?.8:c,o=i?E(e,i):e;let a=t?Math.max(.42,e.h-.38,r*t.d+.12):0,u=s?Math.max(.2,e.d-.05,r*s.h-.45):0;if(t&&s){const e=.1-(a-r*t.d-(r*s.h-u));e>0&&(u+=e)}const l=e=>this.el("script",e.html,`font-size:${A(r)}`);if(t&&!s)return N(e.html+this.el("sup",t.html,`font-size:${A(r)};vertical-align:${A(a/r)}`),Math.max(o.h,a+r*t.h),Math.max(o.d,r*t.d-a));if(s&&!t)return N(o.html+this.el("sub",s.html,`font-size:${A(r)};vertical-align:${A(-u/r)}`),Math.max(o.h,r*s.h-u),Math.max(o.d,u+r*s.d));const p=a+r*t.h,h=u+r*s.d,f=this.el("subsup",l(t)+l(s),`vertical-align:${A(a)};height:${A(p+h)}`);return N(o.html+f,Math.max(o.h,p),Math.max(o.d,h))}radical(e,t=null){const n=Math.max(e.h,a)+.1+.06,s=Math.max(e.d,u),i=n+s,r=.5+.06*(i-1),l=o("sqrt",`${this.p}-hook`,`width:${A(r)};left:${A(-r)}`);let p="";if(t){const e=.8*c;p=this.el("rootindex",t.html,`font-size:${A(e)};vertical-align:${A((.55*i-s)/e)}`)}return N(this.el("sqrt",p+this.el("radicand",l+e.html,`margin-left:${A(r+.05)}`)),n,s)}fence(e,t="(",n=")"){const s=Math.max(e.h,a)+Math.max(e.d,u),i=s>1.25,r=i?.1:0,l=(e,t)=>{if(!e)return{html:"",w:0};const n={"(":.26,")":.26,"{":.36,"}":.36}[e];if(n){const r=n+(i?Math.min(.2,.05*(s-1)):0);return{html:o(e,`${this.p}-delim ${this.p}-delim-${t}`,`width:${A(r)}`),w:r+.1}}const r={"[":"lbrack","]":"rbrack","|":"vert","⌊":"lfloor","⌋":"rfloor","⌈":"lceil","⌉":"rceil"}[e];return{html:this.el(`delim ${r} delim-${t}`,""),w:"|"===e?.18:.3}},c=l(t,"l"),p=l(n,"r"),h=`padding:${A(r)} ${A(p.w)} ${A(r)} ${A(c.w)}`,f=N(this.el("fence",c.html+e.html+p.html,h),Math.max(e.h,a)+r,Math.max(e.d,u)+r);return f.fenced=!0,f}derivative(e,t){const s=this.leibniz(e,t),{by:i,at:r}=n.derivativeOrder(e);if(!r)return s;const o=e.args[1],a=this.render({...o,args:[{...i,id:void 0},r]},{...t,level:t.level+1});return this.script(this.fence(s,"","|"),null,t,a)}leibniz(e,t){const{n:s,body:i,by:r,variable:o}=n.derivativeOrder(e),a={...t,level:t.level+1},u=()=>this.text("d","d"),l=()=>s>1?this.render({type:"number",value:String(s)},a):null,c={...t,inFraction:!0},p=E(u(),l()?this.script(this.render(r,c),l(),c):this.render(r,c)),h=e=>E(l()?this.script(u(),l(),c):u(),e||[]),f=t.level>0||t.inFraction||!this.o.display?.8:1;if(o)return this.stack(h(this.render(i,c)),p,!0,f);const d=n.bracketOp(i)&&n.precedenceOf(n.bracketOp(i))<100,[m,g]="("===this.o.derivativeBrackets?["(",")"]:["[","]"],v=d?this.fence(this.render(i,t),m,g):this.render(i,t);return E(this.stack(h(),p,!0,f),v)}integral(e,t){const[s,i,r,o]=e,a=e=>this.render(e,t),u=e=>e?this.render(e,{...t,level:t.level+1}):null,l=()=>this.text("var",n.firstVariable(s)||"x");let c,p=null,h=null;switch(e.length){case 1:c=l();break;case 2:n.isVariable(i)?c=a(i):(c=l(),p=u(i));break;case 3:n.isVariable(i)?(c=a(i),p=u(r)):(c=l(),p=u(i),h=u(r));break;default:c=a(i),p=u(r),h=u(o)}const f=a(s),d=N(this.el("dx",this.el("d","d")+c.html),c.h,c.d);return E(this.bigSign("int",f,p,h,t),f,d)}bigSign(e,t,n,s,i){const r=!this.o.display||i.level>0,a=Math.max(r?.6:.95,Math.max(t.h-l,t.d+l)+.12),u=o(e,`${this.p}-bigsign ${this.p}-${e}sign`,`height:${A(2*a)};width:${A(r?.38:.5)};vertical-align:${A(l-a)}`);if(!n&&!s)return N(u,l+a,a-l);const p=c,h=s||N(""),f=n||N(""),d=l+a-p*h.h;f.d;const m=this.el("limits",this.el("script",h.html,`font-size:${A(p)}`)+this.el("script lower",f.html,`font-size:${A(p)}`),`vertical-align:${A(d)};height:${A(2*a)}`);return N(u+m,l+a,a-l)}limit(e,t){const[s,i,r,o]=e,a={...t,level:t.level+1},u=e=>this.render(e,a),l=()=>this.rel("→");let c;switch(e.length){case 1:return E(this.word("lim"),N(this.el("fnspace","")),this.body(s,t));case 2:{const e=n.firstVariable(s),t="number"===i.type||"symbol"===i.type&&i.value.includes("∞");c=e&&t?E(this.text("var",e),l(),u(i)):u(i);break}case 3:c=E(u(i),l(),u(r));break;default:{const e=n.firstLeaf(o).toLowerCase().startsWith("r")?"+":p;c=E(u(i),l(),this.script(u(r),this.wrap(o,["symbol"],this.text("ord",e)),a))}}return E(this.under(this.word("lim"),c,t),this.body(s,t))}under(e,t,n){return!this.o.display||n.level>0?this.script(e,null,n,t):N(this.el("under",e.html+this.el("script",t.html,`font-size:${A(.7)}`)),e.h,Math.max(e.d,u)+.05+.7*(t.h+t.d))}body(e,t){const s=n.bracketOp(e);return s&&n.precedenceOf(s)<n.precedenceOf("*")?this.fence(this.render(e,t)):this.render(e,t)}bigOperator(e,t,n){const[s,i,r]=t,a={...n,level:n.level+1},u=i?this.render(i,a):null,p=r?this.render(r,a):null,h=this.body(s,n);if(!this.o.display||n.level>0){const t=.55,s=o(e,`${this.p}-bigsign`,`height:${A(2*t)};width:${A(.8)};vertical-align:${A(l-t)}`);return E(this.script(N(s,l+t,t-l),p,n,u),h)}const f=.68,d=c,m=o(e,`${this.p}-bigsign`,`height:${A(1.36)};width:${A("sum"===e?1:1.05)}`),g=p?1.01+d*p.d:l-f,v=e=>this.el("script",e.html,`font-size:${A(d)}`),b=this.el("bigop",(p?v(p):"")+m+(u?v(u):""),`vertical-align:${A(g)}`);return E(N(b,.93+(p?.08+d*(p.h+p.d):0),f-l+(u?.08+d*(u.h+u.d):0)),h)}matrix(e,t,s){const i=t.map(e=>e.map(e=>this.render(e,s))),r=i.map(e=>({h:Math.max(a,...e.map(e=>e.h)),d:Math.max(u,...e.map(e=>e.d))})),o=r.reduce((e,t)=>e+t.h+t.d,0)+.3*(t.length-1),c=l+o/2-r[0].h,p=i.map((t,n)=>{const s=t.map(e=>this.el("matrix-cell",e.html)).join(""),i=e.args[n];return i&&"op"===i.type&&"[]"===i.op?this.wrap(i,["op","op-list","matrix-row"],N(s)).html:s}).join(""),h=t[0].length,f=N(this.el("matrix",p,`grid-template-columns:repeat(${h},auto);vertical-align:${A(c)}`),l+o/2,o/2-l),[d,m]=n.MATRICES[e.op]??["[","]"];return this.fence(f,d,m)}cases(e,t){const n=[];let s=e;for(;"op"===s.type&&"?:"===s.op;)n.push([this.render(s.args[1],t),E(this.word("if"),this.text("space",""),this.render(s.args[0],t))]),s=s.args[2];"symbol"===s.type&&"unchanged"===s.value||n.push([this.render(s,t),this.word("otherwise")]);const i=n.map(([e,t])=>({h:Math.max(e.h,t.h),d:Math.max(e.d,t.d)})),r=i.reduce((e,t)=>e+t.h+t.d,0)+.25*(n.length-1),o=l+r/2-i[0].h,a=n.map(([e,t])=>this.el("case-value",e.html)+this.el("case-cond",t.html)).join(""),u=N(this.el("cases",a,`vertical-align:${A(o)}`),l+r/2,r/2-l);return this.fence(u,"{","")}}function L(e,t=!1){return"number"===e.type?!e.value.startsWith("-")||t:"symbol"===e.type||"op"===e.type&&("abs"===e.op||n.matrixRows(e)?!t:!t||"neg"!==e.op&&"^"!==e.op?"*"===e.op&&!n.isMinusOneTimes(e)&&e.args.every(e=>"number"===e.type&&!e.value.startsWith("-")||C(e)||"*"===e.op&&L(e,t)):L(e.args[0],!0)&&("neg"===e.op||L(e.args[1],!0)))}const j=["=","===","≠","≠=","<",">","≤","≥","≈","≡","∈","∉"],z=e=>"op"===e.type&&e.args.length>=2&&(2===e.args.length&&j.includes(e.op)||("|"===e.op||"&"===e.op)&&e.args.every(z)),C=e=>"symbol"===e.type&&(1===e.value.length||/^[α-ωΑ-Ω]$/.test(e.value)||Boolean(n.GREEK[e.value])),Z=e=>"number"===e.type&&/^[1-9]\d*$/.test(e.value)&&Number(e.value)<10;for(const e of[h,f,d,g,b,y,x,k])Object.setPrototypeOf(e,null);function F(e){const{id:t,from:n,...s}=e;return s.args&&(s.args=s.args.map(F)),s}const B=e=>n.toPostfix(e).join(" ");function D(e,t){const s=new Set;P(e,t,s);const i=[];return n.walk(e,e=>{s.has(e)&&i.push(e)}),i}function P(e,t,s){if(null!=t)if(Array.isArray(t))t.forEach(t=>P(e,t,s));else if("number"!=typeof t)if("function"!=typeof t){if("string"==typeof t){const i=B(n.parseTree(t));return void n.walk(e,e=>{B(e)===i&&s.add(e)})}if(t.path){const n=R(e,t.path);return void(n&&s.add(n))}if(t.type){const i=B(t);n.walk(e,e=>{e!==t&&B(e)!==i||s.add(e)})}}else n.walk(e,(e,n)=>{t(e,n)&&s.add(e)});else n.walk(e,e=>{e.id===t&&s.add(e)})}function R(e,t){let n=e;for(const e of t){if("op"!==n.type||!n.args[e])return null;n=n.args[e]}return n}function _(e,t){const n=[],s=e=>{if(e.id===t)return!0;if("op"!==e.type)return!1;for(let t=0;t<e.args.length;t++){if(n.push(t),s(e.args[t]))return!0;n.pop()}return!1};return s(e)?n:null}function V(e){let t=0;const s=e=>{"op"===e.type&&(e.args.forEach(s),n.operator(e.op)?.arity===n.VARIADIC&&t++),e.id=t++};return s(e),e}function W(e,t={}){const{blocks:s}=t;if("string"==typeof e)return n.parseTree(e,s?{blocks:e=>s(e,t.scope)}:{});if(Array.isArray(e))return n.fromPostfix(e);if(e&&"object"==typeof e&&e.type){if(void 0!==e.id)return e;const t=structuredClone(e);return n.walk(t,e=>{"op"!==e.type&&void 0!==e.value&&(e.value=String(e.value))}),V(t)}throw new Error("Inline Math needs an expression, standard postfix or a tree")}function U(e,t){const{colors:n,highlight:s,scope:i,blocks:r,...o}=t,a=new Map;for(const[t,s]of function(e){return e?Array.isArray(e)?e:Object.entries(e).map(([e,t])=>[/^\d+$/.test(e)?Number(e):e,t]):[]}(n))if(H(s))for(const n of D(e,t))a.set(n,`color:${s}`);const u=new Set(void 0===s?[]:D(e,s));if(!a.size&&!u.size)return o;const l=o.prefix||"mv";return{...o,style:e=>[a.get(e),o.style&&o.style(e)].filter(Boolean).join(";"),attributes:e=>{const t={...o.attributes?o.attributes(e):{}};return u.has(e)&&(t.class=[t.class,`${l}-hl`].filter(Boolean).join(" ")),t}}}function H(e){return"string"==typeof e&&/^[#\w\s.,%()/+-]+$/.test(e)&&!/url\s*\(|expression/i.test(e)}function K(e,n={}){return W(e,{...n,blocks:n.blocks??t.calculateBlock})}function J(e,n={}){return function(e,t={}){const n=W(e,t);return I(n,U(n,t)).html}(e,{...n,blocks:n.blocks??t.calculateBlock})}function Q(e,t,n){const s=(e,i)=>i===t.length?n:{...e,args:e.args.map((e,n)=>n===t[i]?s(e,i+1):e)};return F(s(e,0))}function Y(e,t,{parse:n,commit:s,cancel:i,label:r="Edit",prefix:o="mv"}){const a=e.ownerDocument;if(!a||!a.body)return null;const u=a.defaultView,l=e.getBoundingClientRect(),c=a.createElement("input");c.type="text",c.className=`${o}-edit`,c.value=t,c.spellcheck=!1,c.autocomplete="off",c.setAttribute("aria-label",r);const p=()=>{c.style.width=`${Math.max(4,c.value.length+2)}ch`},h=u.getComputedStyle(e);Object.assign(c.style,{position:"absolute",left:`${l.left+u.scrollX}px`,top:`${l.top+u.scrollY+l.height/2}px`,minWidth:`${Math.max(l.width,32)}px`,fontSize:h.fontSize}),p(),a.body.appendChild(c),u.getSelection?.()?.removeAllRanges(),c.focus(),c.select();let f=!1;const d=()=>{f=!0,c.remove()};c.cancelEdit=()=>{f||(d(),i&&i())};const m=e=>{if(f)return!0;if(!e||c.value===t)return d(),i&&i(),!0;let r;try{r=n(c.value)}catch(e){return c.setAttribute("aria-invalid","true"),c.title=e.message,!1}return d(),s(r,c.value),!0};return c.addEventListener("keydown",e=>{e.stopPropagation(),"Enter"===e.key&&(e.preventDefault(),m(!0)),"Escape"===e.key&&(e.preventDefault(),m(!1))}),c.addEventListener("input",()=>{p(),c.removeAttribute("aria-invalid"),c.removeAttribute("title")}),c.addEventListener("blur",()=>{m(!0)||m(!1)}),c}class G{constructor(e,t,n={}){this.element=e,this.options=n,this.p=n.prefix||"mv",this.handlers=[],this.clicks=[],this.active=null,this.live=X(e,n.announce,this.p),this.set(t)}set(e,{animate:t=!1,duration:n=600,easing:s="ease-in-out"}={}){const i=K(e,this.options),{html:r}=I(i,U(i,this.options));if(this.editor){const e=this.editor;this.editor=null,e.cancelEdit?.()}const o=ee(t)&&this.tree?this.snapshot():null,a=void 0!==this.tree;return this.tree=i,this.element.innerHTML=r,this.root=this.element.firstElementChild,this.handlers.length&&this.root.classList.add(`${this.p}-clickable`),this.editing&&this.root.classList.add(`${this.p}-editable`),this.active=null,(this.clicks.length||this.editing)&&this.focusable(),o&&this.morph(o,{duration:n,easing:s}),a&&this.live&&this.announce(this.spoken()),this}spoken(){const e=this.root&&this.root.getAttribute&&this.root.getAttribute("aria-label");if(e)return e;try{return s.toAudioSpeech(this.tree)}catch{return""}}announce(e){return this.say(this.live,e)}say(e,t){if(!e)return this;e.textContent="";const n=()=>{e.textContent=t};return"function"==typeof requestAnimationFrame?requestAnimationFrame(()=>requestAnimationFrame(n)):setTimeout(n,50),this}nodes(e){return D(this.tree,e)}elements(e){return this.nodes(e).map(e=>this.elementOf(e)).filter(Boolean)}elementOf(e){return void 0===e.id?null:this.root.querySelector(`[data-node="${e.id}"]`)}highlight(e,t=`${this.p}-hl`){return this.elements(e).forEach(e=>e.classList.add(t)),this}unhighlight(e=null,t=`${this.p}-hl`){return(null===e?this.root.querySelectorAll(`.${t}`):this.elements(e)).forEach(e=>e.classList.remove(t)),this}color(e,t){return this.elements(e).forEach(e=>{e.style.color=t||""}),this}on(e,t){const n=e=>{const n=e.target.closest?.("[data-node]");if(!n||!this.root.contains(n))return;const s=Number(n.dataset.node),i=D(this.tree,s)[0];t({node:i,id:s,path:_(this.tree,s),element:n,event:e})};this.element.addEventListener(e,n);const s=[e,n];return this.handlers.push(s),this.root.classList.add(`${this.p}-clickable`),"click"===e&&(this.clicks.push(t),this.keyboard()),()=>{this.element.removeEventListener(e,n),this.clicks=this.clicks.filter(e=>e!==t),this.handlers=this.handlers.filter(e=>e!==s),!this.handlers.length&&this.root&&this.root.classList.remove(`${this.p}-clickable`)}}destroy(){if(this.editor){const e=this.editor;this.editor=null,e.cancelEdit?.()}for(const[e,t]of this.handlers)this.element.removeEventListener(e,t);this.handlers=[],this.clicks=[],this.keyListener&&this.element.removeEventListener("keydown",this.keyListener),this.editListener&&this.element.removeEventListener("dblclick",this.editListener),this.keyListener=this.editListener=null,this.keysOn=this.editOn=!1;for(const e of new Set([this.live,this.partsLive]))e&&"view"===e.dataset?.mvMadeBy&&e.remove();return this.live=this.partsLive=null,this}editable({toText:e,onEdit:t}={}){if("function"!=typeof e)throw new Error("editable needs { toText } (import { toText } from 'mathzetta/text')");return this.editing={toText:e,onEdit:t},this.root&&this.root.classList&&this.root.classList.add(`${this.p}-editable`),this.keyboard(),!this.editOn&&this.element.addEventListener&&(this.editOn=!0,this.editListener=e=>{const t=e.target.closest?.("[data-node]");t&&this.root.contains(t)&&(e.preventDefault(),this.edit(D(this.tree,Number(t.dataset.node))[0]))},this.element.addEventListener("dblclick",this.editListener)),this}edit(e=this.tree,{returnFocus:t=!1}={}){if(!this.editing)throw new Error("call editable({ toText }) first");const n="object"==typeof e&&e&&e.type?e:this.nodes(e)[0];if(!n)return null;const i=_(this.tree,n.id)||[],r=this.elementOf(n)||this.root;let o="Edit";try{o=`Edit ${s.toAudioSpeech(n)}`}catch{}const a=()=>{t&&this.root.focus&&this.root.focus()};return this.editor=Y(r,this.editing.toText(n),{label:o,prefix:this.p,parse:e=>K(e,this.options),commit:(e,n)=>{this.set(Q(this.tree,i,e),{animate:!0});const s=R(this.tree,i);t&&s&&this.focusPart(s===this.tree?null:s),a(),this.editing.onEdit&&this.editing.onEdit({tree:this.tree,text:this.editing.toText(this.tree),path:i,part:n})},cancel:a}),this.editor}focusable(){this.root&&this.root.setAttribute&&(this.root.setAttribute("tabindex","0"),this.root.getAttribute("aria-label")||(this.root.setAttribute("role","math"),this.root.setAttribute("aria-label",this.spoken())),this.root.setAttribute("aria-description",this.editing?"Arrow keys move between parts, F2 edits one.":"Arrow keys move between parts, Enter selects one."))}keyboard(){this.focusable(),!this.keysOn&&this.element.addEventListener&&(this.keysOn=!0,this.partsLive=this.live||X(this.element,!0,this.p),this.keyListener=e=>this.key(e),this.element.addEventListener("keydown",this.keyListener))}key(e){if(!this.root||!this.root.contains(e.target))return;const t=this.active;let n;switch(e.key){case"ArrowDown":n=t?this.partsOf(t)[0]:this.partsOf(this.tree)[0];break;case"ArrowUp":n=t?this.outerOf(t):void 0;break;case"ArrowRight":n=t?this.neighbor(t,1):this.partsOf(this.tree)[0];break;case"ArrowLeft":n=t?this.neighbor(t,-1):void 0;break;case"Home":case"Escape":n=null;break;case"F2":if(!this.editing)return;return e.preventDefault(),void this.edit(t||this.tree,{returnFocus:!0});case"Enter":case" ":{e.preventDefault();const n=t||this.tree,s=this.elementOf(n)||this.root,i={node:n,id:n.id,path:_(this.tree,n.id),element:s,event:e};for(const e of this.clicks)e(i);return}default:return}e.preventDefault(),void 0!==n&&this.focusPart(n)}focusPart(e){const t=`${this.p}-focus`;this.root.querySelectorAll(`.${t}`).forEach(e=>e.classList.remove(t)),this.active=e;const n=e&&this.elementOf(e);n&&n.classList.add(t);let i="";try{i=e?s.toAudioSpeech(e):this.spoken()}catch{i=""}return this.say(this.partsLive,i),this}partsOf(e){const t=[],n=e=>{this.elementOf(e)?t.push(e):"op"===e.type&&e.args.forEach(n)};return e&&"op"===e.type&&e.args.forEach(n),t}outerOf(e){const t=_(this.tree,e.id);for(let e=t?t.length-1:-1;e>0;e--){const n=R(this.tree,t.slice(0,e));if(n&&this.elementOf(n))return n}return null}neighbor(e,t){const n=this.partsOf(this.outerOf(e)||this.tree),s=n.indexOf(e);return s<0?void 0:n[s+t]}segments(e={}){return s.toSpeechSegments(this.tree,e)}showSegment(e,t=`${this.p}-hl`){return this.unhighlight(null,t),e&&void 0!==e.id&&this.highlight(e.id,t),this}snapshot(){const e=new Map,t=n=>{const s=this.elementOf(n);if(s){const t=B(n);e.has(t)||e.set(t,[]),e.get(t).push({rect:s.getBoundingClientRect(),node:n,sig:t})}"op"===n.type&&n.args.forEach(t)};return t(this.tree),e}morph(e,{duration:t,easing:n}){if("undefined"==typeof Element||!Element.prototype.animate)return;const s=t=>{if("op"===t.type)for(const n of t.args){const t=e.get(B(n)),i=t?t.findIndex(e=>e.node===n):-1;i>-1&&t.splice(i,1),s(n)}},i=r=>{const o=this.elementOf(r),a=o&&e.get(B(r));if(a&&a.length){const{rect:e,node:i}=a.shift();s(i);const r=o.getBoundingClientRect(),u=e.left-r.left,l=e.top-r.top,c=r.width?e.width/r.width:1,p=r.height?e.height/r.height:1;return void((Math.abs(u)+Math.abs(l)>.5||Math.abs(c-1)+Math.abs(p-1)>.01)&&o.animate([{transformOrigin:"0 0",transform:`translate(${u}px, ${l}px) scale(${c}, ${p})`},{transformOrigin:"0 0",transform:"none"}],{duration:t,easing:n}))}"op"===r.type?r.args.forEach(i):o&&o.animate([{opacity:0},{opacity:0},{opacity:1}],{duration:t,easing:n})};i(this.tree)}}function X(e,t,n){if(!t)return null;if("object"==typeof t&&1===t.nodeType)return t;if("undefined"==typeof document||!e.insertAdjacentElement)return null;const s=e.nextElementSibling;if(s&&"view"===s.dataset?.mvMadeBy&&s.classList.contains(`${n}-sr-only`))return s;const i=document.createElement("span");return i.dataset.mvMadeBy="view",i.className=`${n}-sr-only`,i.setAttribute("aria-live","polite"),i.setAttribute("aria-atomic","true"),e.insertAdjacentElement("afterend",i),i}function ee(e){return!!e&&("always"===e||!("function"==typeof matchMedia&&matchMedia("(prefers-reduced-motion: reduce)").matches))}const te=Symbol.for("inlinemath.expressions"),ne=new Set(["symbol","number"]);function se(e){return e?"symbol"===e.type?e.value:"op"===e.type&&"_"===e.op&&2===e.args.length&&"symbol"===e.args[0].type&&ne.has(e.args[1].type)?`${e.args[0].value}_${e.args[1].value}`:null:null}function ie(e){const{id:t,...n}=e;return n.args&&(n.args=n.args.map(ie)),n}function re(e,t){const n=(e,s)=>{if(!s&&void 0!==e.from)return t(e.from);const{id:i,from:r,...o}=e;return o.args&&(o.args=o.args.map(e=>n(e,!1))),o};return n(e,!0)}const oe=new Set;function ae(e,t){let s=!1;const i=new Set,r=(e,o=oe)=>{const a=se(e);if(null!==a){if(!i.has(a)&&!o.has(a)){const e=t(a);if(e){s=!0,i.add(a);const t={...r(F(e)),from:a};return i.delete(a),t}}return e}if(e.args){const t=function(e){const[t,s]=e.args,i=e=>e&&"symbol"===e.type?e.value:null;switch(e.op){case"der":return"="===s?.op?i(s.args[0])&&{name:i(s.args[0]),where:e=>0===e,index:1}:i(s)&&{name:i(s),where:e=>e<=1};case"int":{const r=i(s)??(3===e.args.length||1===e.args.length?n.firstVariable(t)||"x":null);return r&&{name:r,where:e=>0===e||1===e&&i(s)===r}}case"lim":return"→"===s?.op&&i(s.args[0])&&{name:i(s.args[0]),where:e=>0===e,index:1};case"\\sumidx":case"\\prodidx":return("="===s?.op||"∈"===s?.op)&&i(s.args[0])&&{name:i(s.args[0]),where:e=>0===e,index:1};default:return null}}(e);if(!t)return{...e,args:e.args.map(e=>r(e,o))};const s=new Set([...o,t.name]);return{...e,args:e.args.map((e,n)=>n===t.index?{...e,args:e.args.map((e,t)=>r(e,0===t?s:o))}:r(e,t.where(n)?s:o))}}return e},o=r(e);return{tree:s?ie(o):e,changed:s}}const ue="[-+]?(?:\\d+\\.?\\d*|\\.\\d+)",le=new RegExp(`^(${ue})\\s*\\.\\.\\s*(${ue})(?:\\s+step\\s+(${ue}))?(?:\\s*=\\s*(${ue}))?$`);function ce(e){const t=/^\s*\[\[([\s\S]*)\]\]\s*$/.exec(e);if(!t||/\]\s*,\s*\[/.test(t[1]))return null;const n=t[1].trim(),s=le.exec(n);if(s){const e=Number(s[1]),t=Number(s[2]);if(!(t>e))return null;const n=void 0!==s[3]?Number(s[3]):Number.isInteger(e)&&Number.isInteger(t)?1:(t-e)/100;if(!(n>0))return null;const i=void 0!==s[4]?Math.min(t,Math.max(e,Number(s[4]))):e;return{kind:"slider",min:e,max:t,step:n,default:String(i)}}if(n.includes("|")){const e=n.split("|").map(e=>e.trim()).filter(Boolean);if(e.length)return{kind:"dropdown",options:e,default:e[0]}}return{kind:"textbox",default:n}}const pe=Symbol("set on the page");class he{constructor(){this.owners=new Map,this.chosen=new Map,this.listeners=new Set}definitions(e){const t=new Map;for(const[n,s]of this.owners)if(n!==e)for(const[e,n]of s)t.delete(e),t.set(e,n);return t}textOf(e){const t=this.chosen.get(e.name);return t&&t.key===e.key?t.text:e.text}get(e){const t=this.definitions().get(e);return t?this.textOf(t):void 0}names(){return[...this.definitions().keys()]}set(e,t){t=String(t);const n=this.definitions().get(e);if(n&&n.input){const s=this.chosen.get(e);if(s&&s.key===n.key&&s.text===t)return this;this.chosen.set(e,{key:n.key,text:t})}else{const n=new Map(this.owners.get(pe));n.set(e,{name:e,text:t,key:`page:${t}`,input:null}),this.owners.delete(pe),this.owners.set(pe,n)}return this.notify(null,e),this}clear(e){return void 0===e?(this.owners.clear(),this.chosen.clear()):(this.owners.get(pe)?.delete(e),this.chosen.delete(e)),this.notify(null,e),this}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}own(e,t){const n=this.owners.get(e);var s,i;(s=n,i=t,(s?.size??0)===(i?.size??0)&&[...s??[]].every(([e,t])=>i?.get(e)?.key===t.key))?t&&this.owners.set(e,t):(t&&t.size?this.owners.set(e,t):this.owners.delete(e),this.notify(e))}notify(e,t){for(const n of[...this.listeners])n(e,t)}}function fe(){return new he}const de=fe(),me=new RegExp("(\\d+)","g");function ge(e,{delimiters:t=["$$","$","\\[","\\("]}={}){const n=[];let s="",i=0;const r=String(e).replace(/[\uE000-\uE003]/g,"�"),o=e=>0===e||"\n"===r[e-1],a=function(e){const t=new Map,n=e=>/^( {4}|\t)/.test(e);let s=0,i=!0,r=!1,o=-1;for(const a of e.split("\n")){const e=!a.trim();o>-1&&!e&&!n(a)&&(t.set(o,s-1),o=-1),o<0&&!e&&n(a)&&i&&!r&&(o=s),e||n(a)||(r=Me.test(a)||r&&/^\s/.test(a)),i=e,s+=a.length+1}o>-1&&t.set(o,e.length);return t}(r);let u=-1;const l=new Set,c=(e,t,s)=>(n.push({source:e,display:t,raw:s,start:i,end:i+s.length}),`${n.length-1}`);for(;i<r.length;){if(a.has(i)){s+=r.slice(i,a.get(i)),i=a.get(i);continue}if(o(i)){const e=/^( {0,3})(`{3,}|~{3,})([^\n]*)\n?/.exec(r.slice(i));if(e){const t=e[2],n=new RegExp(`\\n {0,3}${"`"===t[0]?"`":"~"}{${t.length},}[ \\t]*(?=\\n|$)`),o=r.slice(i+e[0].length),a=n.exec(`\n${o}`),u=a?o.slice(0,Math.max(0,a.index-1)):o,l=e[0].length+(a?a.index-1+a[0].length:o.length),p=r.slice(i,i+l);"math"===e[3].trim()?s+=c(u,!0,p):s+=p,i+=l;continue}}const e=r[i];if("`"===e){const e=/^`+/.exec(r.slice(i))[0],t=r.indexOf(e,i+e.length);if(t>-1){s+=r.slice(i,t+e.length),i=t+e.length;continue}s+=e,i+=e.length;continue}if("\\"===e){const e=r.slice(i,i+2),n="\\["===e?"\\]":"\\("===e?"\\)":null;if(n&&t.includes(e)){const t=l.has(n)?-1:r.indexOf(n,i+2);if(t<0&&l.add(n),t>-1){s+=c(r.slice(i+2,t),"\\["===e,r.slice(i,t+2)),i=t+2;continue}}s+=e,i+=2;continue}if("$"===e)if("$"===r[i+1]&&t.includes("$$")){const e=r.indexOf("$$",i+2);if(e>-1){s+=c(r.slice(i+2,e),!0,r.slice(i,e+2)),i=e+2;continue}}else if(t.includes("$")&&r[i+1]&&!/\s/.test(r[i+1])&&i+1>=u){const{end:e,stop:t}=ve(r,i+1);if(e>-1){s+=c(r.slice(i+1,e),!1,r.slice(i,e+1)),i=e+1;continue}u=t}s+=e,i++}return{text:s,math:n}}function ve(e,t){for(let n=t;n<e.length;n++){const t=e[n];if("\\"!==t){if("`"===t)return{end:-1,stop:n};if("\n"===t&&/^\n[ \t]*\n/.test(e.slice(n,n+64)))return{end:-1,stop:n};if("$"===t&&!/\s/.test(e[n-1])&&!/\d/.test(e[n+1]??"")&&"$"!==e[n+1])return{end:n,stop:n}}else n++}return{end:-1,stop:e.length}}const be=e=>String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),ye=/^\s*([A-Za-z\u0370-\u03ff](?:_\{?\w+\}?)?)\s*=\s*([^=<>≤≥]+)$/;function we(e,s,i,r){const{text:o,math:a}=ge(e,s),u=i?i.definitions(r):new Map,l=e=>i?i.textOf(e):e.text,c={...s.scope??{}},p={},h=new Map,f=new Set,d=[],m=e=>{const t=new Map;return n=>{const s=u.get(n);if(!s)return null;if(!t.has(n)){let i=null;try{i=K(l(s),e)}catch{}t.set(n,i)}return t.get(n)}};let g=!0;const v=a.map((e,i)=>{const{source:r,display:o}=e;g&&r.includes("{{")&&((()=>{for(const e of Object.keys(p))delete p[e];Object.assign(p,c);for(const e of u.keys())delete p[e];let e=[...u.values()];for(;e.length;){const n=e.filter(e=>{try{const n=t.calculate(l(e),p);if("number"==typeof n.value||"bigint"==typeof n.value||Array.isArray(n.value))return p[e.name]=n.exact?n.text:n.value,!1}catch{}return!0});if(n.length===e.length)break;e=n}const s={},i=m({});for(const e of u.keys()){const t=i(e);if(t)try{s[e]=n.toPostfix(ae(t,t=>t===e?null:i(t)).tree)}catch{}}p[te]=s})(),g=!1);const a=o?"mv-md-display":"mv-md-math",v=(e,t="")=>`<span class="${a}${t}" data-mv-md="${i}">${e}</span>`;try{const n={...s.math,display:o,blocks:s.blocks,scope:p},a=function(e){let t=e.trim();const n=t.startsWith("_");n&&(t=t.slice(1).trimStart());let s=t.indexOf(":="),i=2;s<0&&n&&(s=t.search(/(?<![<>!≤≥=])=(?!=)/),i=1);const r=n?{error:"a hidden $_…$ saves a variable: $_A := 2+2$"}:null;if(s<=0)return r;const o=t.slice(0,s).trim(),a=t.slice(s+i).trim();let u=null;try{u=/\{\{/.test(o)?null:se(K(o))}catch{}return null!==u&&a?{hidden:n,lhs:o,name:u,rhs:a,input:ce(a)}:r}(r);if(a&&a.error)throw new Error(a.error);if(a){const{name:t,input:s,hidden:r}=a,o=s?{name:t,text:s.default,input:s,key:`input:${JSON.stringify(s)}`}:{name:t,text:a.rhs,input:null,key:`expr:${a.rhs}`,start:e.start,end:e.end};let c="";if(s){const e=function(e,t){const{input:n,name:s}=e,i=`class="mv-md-input mv-md-${n.kind}" data-mv-var="${be(s)}" aria-label="${be(s)}"`;if("dropdown"===n.kind)return`<select ${i}>${n.options.map(e=>`<option value="${be(e)}"${e===t?" selected":""}>${be(e)}</option>`).join("")}</select>`;return"slider"===n.kind?`<input type="range" ${i} min="${n.min}" max="${n.max}" step="${n.step}" value="${be(t)}"><output class="mv-md-output" data-mv-out="${be(s)}">${be(t)}</output>`:`<input type="text" ${i} value="${be(t)}" size="${Math.max(4,t.length+1)}" spellcheck="false" autocomplete="off">`}(o,l(o));c=r?e:`${J(a.lhs,n)}<span class="mv-md-assign" aria-hidden="true">≔</span>${e}`,f.add(i)}else{const e=ae(K(a.rhs,n),m(n)).tree;if(!r){const t=V({type:"op",op:"=",args:[F(K(a.lhs)),void 0===e.id?e:F(e)]});d[i]=t,c=function(e,t="mv"){return e.replace(`<span class="${t}-rel">=</span>`,`<span class="${t}-rel ${t}-rel-def">≔</span>`).replace(/(aria-label="[^"]*?) equals /,"$1 is defined as ").replace("<mo>=</mo>","<mo>≔</mo>")}(J(t,n),n.prefix)}}return u.delete(t),u.set(t,o),h.set(t,o),g=!0,r&&!s?"":v(c,s?" mv-md-input-def":"")}const{tree:b,changed:y}=ae(K(r,n),m(n));y&&V(b),d[i]=b;const w=J(b,n);return!y&&!1!==s.define&&function(e,n,s){const i=ye.exec(e);if(!i||/\{\{/.test(i[2]))return!1;const r=i[1].replace(/[{}]/g,"");if(s.has(r))return!1;try{const e=t.calculate(i[2],n);if("number"==typeof e.value||"bigint"==typeof e.value||Array.isArray(e.value))return n[r]=e.exact?e.text:e.value,!0}catch{}return!1}(r,c,u)&&(g=!0),v(w)}catch(t){return`<span class="mv-md-error" data-mv-md="${i}" title="${be(t.message)}"><code>${be(e.raw)}</code></span>`}});return{text:o,math:a,drawn:v,defs:h,inputs:f,trees:d}}const xe=/^(https?:|mailto:|#|\/|\.{0,2}\/|[^:]*$)/i,ke=e=>xe.test(e.trim())?be(e.trim()):"#",qe=/\uE002(\d+)\uE003/g;function $e(e,t,n,s=[]){const i=e=>(s.push(e),`${s.length-1}`),r=e=>(e=>e.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&"))(n(e).replace(qe,(e,t)=>(s[Number(t)]??"").replace(/<[^>]*>/g,"")));let o=e;o=o.replace(/(`+)([\s\S]*?[^`])\1(?!`)/g,(e,t,s)=>i(`<code>${be(n(s.trim()))}</code>`)),o=o.replace(/\\([\\`*_{}[\]()#+\-.!|~$<>"'])/g,(e,t)=>i(be(t))),o=o.replace(/<((?:https?:\/\/|mailto:)[^\s>]+)>/g,(e,t)=>i(`<a href="${ke(t)}">${be(t)}</a>`)),t.html&&(o=o.replace(/<\/?[A-Za-z][^>]*>/g,e=>i(e))),o=o.replace(/!\[([^\[\]]*)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,t,n,s)=>i(`<img src="${ke(r(n))}" alt="${be(r(t))}"${s?` title="${be(r(s))}"`:""}>`)),o=o.replace(/\[([^\[\]]+)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,o,a,u)=>i(`<a href="${ke(r(a))}"${u?` title="${be(r(u))}"`:""}>${$e(o,t,n,s)}</a>`)),o=o.replace(/&(?!#\d{1,7};|#x[0-9a-f]{1,6};|[a-z][a-z0-9]{1,31};)/gi,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),o=o.replace(/(\*\*\*|___)(?=\S)([\s\S]*?\S)\1/g,"<strong><em>$2</em></strong>"),o=o.replace(/(\*\*\*|___)(?=\S)([^*_]*?\S)(\*\*|__)(?![*_])([\s\S]*?\S)(\*|_)(?![*_])/g,"<em><strong>$2</strong>$4</em>"),o=o.replace(/(\*\*\*|___)(?=\S)([^*_]*?\S)(\*|_)(?![*_])([\s\S]*?\S)(\*\*|__)(?![*_])/g,"<strong><em>$2</em>$4</strong>"),o=o.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g,"<strong>$2</strong>"),o=o.replace(/(^|[^*\w])\*(?=\S)([\s\S]*?\S)\*(?!\*)/g,"$1<em>$2</em>"),o=o.replace(/(^|[^_\w])_(?=\S)([\s\S]*?\S)_(?![_\w])/g,"$1<em>$2</em>"),o=o.replace(/~~(?=\S)([\s\S]*?\S)~~/g,"<del>$1</del>"),o=o.replace(/( {2,}|\\)\n/g,"<br>\n");for(let e=0;e<8&&/\uE002\d+\uE003/.test(o);e++)o=o.replace(qe,(e,t)=>s[Number(t)]??"");return o}const Se=/^( {0,3})(#{1,6}\s|>|```|~~~|([-*+]|\d{1,9}[.)])\s|(\*[ \t]*){3,}$|(-[ \t]*){3,}$|(_[ \t]*){3,}$)/,Me=/^( {0,3})([-*+]|\d{1,9}[.)])(\s+|$)/,Oe=/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/,Ae=e=>Se.test(e)&&!/^ {0,3}[-=]+\s*$/.test(e)&&!/^ {0,3}(?!1[.)])\d{1,9}[.)]\s/.test(e);function Ne(e){const t=e.trim();let n=t.length;for(;n>0&&"#"===t[n-1];)n--;return n===t.length?t:0===n?"":/[ \t]/.test(t[n-1])?t.slice(0,n).trimEnd():t}function Ee(e,t,n,s=0){const i=[];let r=0;const o=e=>$e(e,t,n);if(s>100)return`<p>${o(e.join("\n"))}</p>`;for(;r<e.length;){const a=e[r];if(!a.trim()){r++;continue}const u=/^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)/.exec(a);if(u){const t=[];for(r++;r<e.length&&!new RegExp(`^ {0,3}${"`"===u[1][0]?"`":"~"}{${u[1].length},}\\s*$`).test(e[r]);)t.push(e[r++]);r++;const s=u[2]?` class="language-${be(u[2])}"`:"";i.push(`<pre><code${s}>${be(n(t.join("\n")))}</code></pre>`);continue}const l=/^ {0,3}(#{1,6})[ \t]+/.exec(a);if(l){i.push(`<h${l[1].length}>${o(Ne(a.slice(l[0].length)))}</h${l[1].length}>`),r++;continue}if(/^ {0,3}((\*[ \t]*){3,}|(-[ \t]*){3,}|(_[ \t]*){3,})$/.test(a)){i.push("<hr>"),r++;continue}if(/^ {0,3}>/.test(a)){const o=[];for(;r<e.length&&e[r].trim()&&(/^ {0,3}>/.test(e[r])||o.length);)o.push(e[r].replace(/^ {0,3}> ?/,"")),r++;i.push(`<blockquote>\n${Ee(o,t,n,s+1)}\n</blockquote>`);continue}const c=Me.exec(a);if(c){const o=/\d/.test(c[2]),a=o?parseInt(c[2],10):1,u=[];let l=!1;for(;r<e.length;){const t=Me.exec(e[r]);if(!t||/\d/.test(t[2])!==o)break;const n=t[0].length,s=[e[r].slice(n)];for(r++;r<e.length;){const t=e[r];if(!t.trim()){const t=e[r+1];if(void 0!==t&&t.startsWith(" ".repeat(Math.min(n,4)))&&t.trim()){s.push(""),l=!0,r++;continue}void 0!==t&&Me.test(t)&&(l=!0);break}if(t.startsWith(" ".repeat(Math.min(n,4))))s.push(t.slice(Math.min(n,4)));else{if(Me.test(t)||Se.test(t))break;s.push(t)}r++}for(u.push(s);r<e.length&&!e[r].trim()&&void 0!==e[r+1]&&Me.test(e[r+1]);)r++}const p=o?"ol":"ul",h=u.map(e=>{let i=Ee(e,t,n,s+1);return l||(i=i.replace(/^<p>([\s\S]*?)<\/p>/,"$1").replace(/\n<p>([\s\S]*?)<\/p>/g,"\n$1")),`<li>${i}</li>`});i.push(`<${p}${o&&1!==a?` start="${a}"`:""}>\n${h.join("\n")}\n</${p}>`);continue}if(a.includes("|")&&void 0!==e[r+1]&&Oe.test(e[r+1])&&e[r+1].includes("-")){const t=e=>e.trim().replace(/^\|/,"").replace(/\|$/,"").split(/(?<!\\)\|/).map(e=>e.trim()),n=t(e[r+1]).map(e=>e.startsWith(":")&&e.endsWith(":")?"center":e.endsWith(":")?"right":e.startsWith(":")?"left":""),s=(e,t,s)=>`<${e}${n[s]?` style="text-align:${n[s]}"`:""}>${o(t)}</${e}>`,u=t(a);r+=2;const l=[];for(;r<e.length&&e[r].trim()&&e[r].includes("|");)l.push(t(e[r++]));i.push(`<table>\n<thead><tr>${u.map((e,t)=>s("th",e,t)).join("")}</tr></thead>\n<tbody>\n${l.map(e=>`<tr>${u.map((t,n)=>s("td",e[n]??"",n)).join("")}</tr>`).join("\n")}\n</tbody>\n</table>`);continue}if(/^( {4}|\t)/.test(a)){const t=[];for(;r<e.length&&(/^( {4}|\t)/.test(e[r])||!e[r].trim());)t.push(e[r++].replace(/^( {4}|\t)/,""));for(;t.length&&!t[t.length-1].trim();)t.pop();i.push(`<pre><code>${be(n(t.join("\n")))}</code></pre>`);continue}const p=[];for(;r<e.length&&e[r].trim()&&(!p.length||!Ae(e[r]));){if(p.length&&/^ {0,3}(=+|-+)\s*$/.test(e[r])){const t="="===e[r].trim()[0]?1:2;i.push(`<h${t}>${o(p.join("\n"))}</h${t}>`),p.length=0,r++;break}p.push(e[r].replace(/^ {0,3}/,"")),r++}p.length&&i.push(`<p>${o(p.join("\n"))}</p>`)}return i.join("\n")}function Ie(e,t={},n=e=>e){return Ee(String(e).replace(/\r\n?/g,"\n").replace(/[\uE002\uE003]/g,"�").split("\n"),t,n)}function Te({text:e,math:t,drawn:n},s){return(s.render?s.render(e):Ie(e,s,e=>e.replace(me,(e,n)=>t[Number(n)]?.raw??""))).replace(new RegExp("<p>\\s*(\\d+)\\s*</p>","g"),(e,s)=>t[Number(s)].display&&n[Number(s)]?`<div class="mv-md-block">${n[Number(s)]}</div>`:e).replace(me,(e,t)=>n[Number(t)]??"").replace(/<p>\s*<\/p>\n?/g,"")}const Le=new WeakMap,je=new Set;function ze(){for(const e of je)e.connected()&&!e.element.isConnected&&e.stop(!0)}const Ce=new Map,Ze=-1,Fe="\\:",Be=e=>"string"==typeof e&&e.startsWith(Fe)&&e.length>2;function De(e){if(!e||!e.symbol)throw new Error("operator needs a symbol");if(!Number.isInteger(e.arity)||e.arity<0&&e.arity!==Ze)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 t={symbol:e.symbol,arity:e.arity,commutative:!!e.commutative,fold:"function"==typeof e.fold?e.fold:null,label:e.label||e.symbol};return Ce.set(t.symbol,t),t}const Pe=Object.freeze({symbol:Fe,arity:Ze,commutative:!1,fold:null,label:"function"});function Re(e){const t=Ce.get(e);return t||(Be(e)?{...Pe,symbol:e,label:e.slice(2)}:null)}function _e(e){return Ce.has(e)||Be(e)}const Ve=e=>Number.isFinite(e)&&Number.isInteger(e)?e:null,We=e=>Number.isFinite(e)?e:null;!function(){De({symbol:"+",arity:2,commutative:!0,label:"add",fold:(e,t)=>We(e+t)}),De({symbol:"-",arity:2,label:"subtract",fold:(e,t)=>We(e-t)}),De({symbol:"*",arity:2,commutative:!0,label:"multiply",fold:(e,t)=>We(e*t)}),De({symbol:"/",arity:2,label:"divide",fold:(e,t)=>0===t?null:Ve(e/t)}),De({symbol:"^",arity:2,label:"power",fold:(e,t)=>Number.isInteger(t)&&Math.abs(t)<=64?We(e**t):null}),De({symbol:"neg",arity:1,label:"negate",fold:e=>We(-e)}),De({symbol:"pm",arity:1,label:"plus or minus"}),De({symbol:"±",arity:2,label:"plus or minus"}),De({symbol:"mod",arity:2,label:"modulo",fold:(e,t)=>0===t?null:Ve((e%t+t)%t)}),De({symbol:"!",arity:1,label:"factorial",fold:e=>Number.isInteger(e)&&e>=0&&e<=18?[...Array(e).keys()].reduce((e,t)=>e*(t+1),1):null}),De({symbol:"_",arity:2,label:"subscript"}),De({symbol:"der",arity:2,label:"derivative"}),De({symbol:"evaluated",arity:4,label:"evaluated from a to b"}),De({symbol:"setbuilder",arity:2,label:"the set of … such that"}),De({symbol:"int",arity:Ze,label:"integral"}),De({symbol:"lim",arity:Ze,label:"limit"}),De({symbol:"\\sumidx",arity:Ze,label:"sum over an index"}),De({symbol:"\\prodidx",arity:Ze,label:"product over an index"}),De({symbol:"abs",arity:1,label:"absolute value",fold:e=>We(Math.abs(e))}),De({symbol:"floor",arity:1,label:"floor",fold:e=>We(Math.floor(e))}),De({symbol:"ceil",arity:1,label:"ceiling",fold:e=>We(Math.ceil(e))}),De({symbol:"round",arity:2,label:"round",fold:(e,t)=>Number.isInteger(t)?We(Math.round(e*10**t)/10**t):null}),De({symbol:"fixed",arity:2,label:"fixed",fold:()=>null}),De({symbol:"sqrt",arity:1,label:"square root",fold:e=>Ve(Math.sqrt(e))}),De({symbol:"root",arity:2,label:"nth root",fold:(e,t)=>Ve(Math.round(t**(1/e))**e===t?Math.round(t**(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"])De({symbol:e,arity:1,label:e});De({symbol:"log",arity:2,label:"log to a base"}),De({symbol:"atan2",arity:2,label:"atan2"}),De({symbol:"perm",arity:2,label:"permutations"}),De({symbol:"comb",arity:2,label:"combinations"}),De({symbol:"random",arity:0,label:"random"});for(const e of["max","min","gcd","mean","sum","prod"])De({symbol:e,arity:Ze,label:e});for(const e of["()","[]","{}","(]","[)"])De({symbol:e,arity:Ze,label:"group"});for(const e of["pmatrix","bmatrix","vmatrix"])De({symbol:e,arity:Ze,label:"matrix"});De({symbol:"det",arity:1,label:"determinant"});for(const e of["=","===","≠","≠=","<",">","≤","≥","∈","∉","∪","∩","≈","≡","→","pmod","&","|","\\xor","\\nand","\\nor","\\implies","\\iff"])De({symbol:e,arity:2,label:e});De({symbol:"\\not",arity:1,label:"not"}),De({symbol:"?:",arity:3,label:"if then else"})}();const Ue="num",He="sym",Ke="op",Je=Object.freeze([]);class Qe extends Error{constructor(e){super(e),this.name="ExprError"}}function Ye(e){if("number"!=typeof e||!Number.isFinite(e))throw new Qe(`not a finite number: ${e}`);const t=(n=e,Object.is(n,-0)?"0":String(n));var n;return Object.freeze({type:Ue,token:t,value:e,args:Je,s:t})}function Ge(e){if("string"!=typeof e||""===e)throw new Qe("symbol needs a non-empty token");return Object.freeze({type:He,token:e,value:null,args:Je,s:e})}function Xe(e){const t=/^(-?)0*(\d+?)(?:\.(\d*?)0*)?$/.exec(String(e));if(!t)throw new Qe(`not an exact decimal: ${e}`);const[,n,s,i=""]=t,r=i?`${s}.${i}`:s,o=/^0(\.0*)?$/.test(r)?"0":n+r;return Object.freeze({type:Ue,token:o,value:Number(o),args:Je,s:o})}const et=/^-?\d+(\.\d+)?$/;function tt(e){const t=String(e);if(et.test(t))return Xe(t);if(""!==t&&!/\s/.test(t)){const e=Number(t);if(Number.isFinite(e))return Ye(e)}return Ge(t)}function nt(e,t){const n=Re(e);if(!n)throw new Qe(`unknown operator "${e}"`);if(n.arity!==Ze&&t.length!==n.arity)throw new Qe(`"${e}" takes ${n.arity} operand(s), got ${t.length}`);const s=Object.freeze(t.slice()),i=n.arity===Ze?` ${s.length}`:"",r=`${s.length?s.map(e=>e.s).join(" "):""}${s.length,""}${i} ${e}`.trimStart();return Object.freeze({type:Ke,op:e,token:e,value:null,args:s,s:r})}const st=e=>e.type===Ue,it=e=>e.type===Ke;function rt(e){return ot(function(e){const t=String(e).trim();return""===t?[]:t.split(/\s+/)}(e))}function ot(e){if(!Array.isArray(e))throw new Qe("fromPostfix needs an array of tokens");if(0===e.length)throw new Qe("empty expression");const t=[];for(let n=0;n<e.length;n++){const s=String(e[n]);if(_e(s)){let e=Re(s).arity;if(e===Ze){const i=t.pop();if(e=i&&i.type===Ue&&Number.isInteger(i.value)&&i.value>=0?i.value:-1,e<0)throw new Qe(`"${s}" at position ${n+1} takes any number of operands, so a count must come before it`)}if(t.length<e)throw new Qe(`"${s}" at position ${n+1} needs ${e} operand(s), only ${t.length} on the stack`);const i=t.splice(t.length-e,e);t.push(nt(s,i))}else t.push(tt(s))}if(1!==t.length){const n=[...new Set(e.filter(e=>!_e(e)))];throw new Qe(`expression leaves ${t.length} values on the stack; it should leave exactly 1. Read as operands: ${n.join(", ")} — is one of those meant to be an operator?`)}return t[0]}function at(e){if(e.type!==Ke)return 0;let t=0;for(const n of e.args)t=Math.max(t,at(n));return t+1}function ut(e){if(e.type!==Ke)return 1;let t=1;for(const n of e.args)t+=ut(n);return t}function lt(e,t=[]){if(e.type!==Ke)t.push(e.token);else for(const n of e.args)lt(n,t);return t}function ct(e){return e.type===Ue||e.type!==He&&e.args.every(ct)}function pt(e,t="pre",n=[],s=[]){"pre"===t&&s.push({node:e,path:n});for(let i=0;i<e.args.length;i++)pt(e.args[i],t,n.concat(i),s);return"post"===t&&s.push({node:e,path:n}),s}function ht(e,t,n){if(0===t.length)return n;const[s,...i]=t,r=e.args.slice();return r[s]=ht(r[s],i,n),nt(e.op,r)}class ft extends Error{constructor(e){super(e),this.name="CasError"}}const dt=1e5,mt=e=>e<0n?-e:e,gt=e=>0n===e?0:mt(e).toString(2).length;function vt(e,t){for(e=mt(e),t=mt(t);t;)[e,t]=[t,e%t];return e}class bt{constructor(e,t=1n){if(0n===t)throw new ft("division by zero");t<0n&&(e=-e,t=-t);const n=vt(e,t)||1n;if(this.n=e/n,this.d=t/n,gt(this.n)>dt||gt(this.d)>dt)throw new ft("a number too large to keep exactly")}static of(e){return new bt(BigInt(e))}add(e){return new bt(this.n*e.d+e.n*this.d,this.d*e.d)}sub(e){return new bt(this.n*e.d-e.n*this.d,this.d*e.d)}mul(e){return new bt(this.n*e.n,this.d*e.d)}div(e){if(0n===e.n)throw new ft("division by zero");return new bt(this.n*e.d,this.d*e.n)}neg(){return new bt(-this.n,this.d)}abs(){return this.n<0n?this.neg():this}inv(){return bt.ONE.div(this)}pow(e){if((e=BigInt(e))<0n)return this.inv().pow(-e);if((0n===this.n||1n===mt(this.n))&&1n===this.d)return 0n===e||-1n===this.n&&e%2n==0n?bt.ONE:this;if(BigInt(Math.max(gt(this.n),gt(this.d)))*e>BigInt(dt))throw new ft("a power too large to work out exactly");return new bt(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 t=this.n*e.d,n=e.n*this.d;return t<n?-1:t>n?1:0}floor(){const e=this.n/this.d;return new bt(this.n<0n&&e*this.d!==this.n?e-1n:e)}ceil(){return this.neg().floor().neg()}toNumber(){const e=Number(this.n),t=Number(this.d);if(Number.isFinite(e)&&Number.isFinite(t))return e/t;const n=BigInt(Math.max(gt(this.n),gt(this.d))-1e3);return Number(this.n>>n)/Number(this.d>>n)}toString(){return 1n===this.d?String(this.n):`${this.n}/${this.d}`}}function yt(e){const t=/^(-?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(String(e));if(!t||""===t[2]&&!t[3])return null;const[,n,s,i="",r="0"]=t;let o=new bt(BigInt((s||"0")+i),10n**BigInt(i.length));const a=Number(r);return a&&(o=o.mul(bt.of(10).pow(a))),n?o.neg():o}function wt(e,t){if(e<2n)return e;if(t>=gt(e))return 1n;const n=BigInt(t);let s=1n<<BigInt(Math.ceil(gt(e)/t));for(;;){const t=((n-1n)*s+e/s**(n-1n))/n;if(t>=s)break;s=t}for(;s**n>e;)s--;for(;(s+1n)**n<=e;)s++;return s}bt.ZERO=new bt(0n),bt.ONE=new bt(1n),bt.MINUS_ONE=new bt(-1n),bt.HALF=new bt(1n,2n);const xt=(()=>{const e=[],t=new Uint8Array(1e4);for(let n=2;n<t.length;n++)if(!t[n]){e.push(BigInt(n));for(let e=n*n;e<t.length;e+=n)t[e]=1}return e})();function kt(e,t){const n=BigInt(t);let s=1n,i=1n,r=e;for(const e of xt){if(e*e>r)break;if(r%e)continue;let t=0n;for(;r%e===0n;)r/=e,t++;s*=e**(t/n),i*=e**(t%n)}if(r>1n){const e=function(e,t){if(e<0n)return null;if(e<2n)return e;const n=wt(e,t);return n**BigInt(t)===e?n:null}(r,t);null!==e?s*=e:i*=r}return{outside:s,inside:i}}const qt=new Set(["pi","e","π"]),$t={complex:!1};function St(e,t){const n=$t.complex;$t.complex=Boolean(e);try{return t()}finally{$t.complex=n}}const Mt=e=>qt.has(e)||$t.complex&&"i"===e,Ot=e=>$t.complex&&"atom"===e.k&&"sym"===e.node.type&&"i"===e.node.token,At=e=>({k:"num",q:e}),Nt=At(bt.ONE),Et=At(bt.ZERO),It=At(bt.HALF),Tt=e=>"num"===e.k,Lt=e=>({k:"atom",node:e}),jt=new WeakMap;function zt(e){let t=jt.get(e);return void 0===t&&jt.set(e,t=dn(e).s),t}function Ct(e){if("num"===e.k)return 0;if("atom"===e.k)return"sym"===e.node.type&&Mt(e.node.token)?0:1;if("add"===e.k)return Math.max(...e.terms.map(e=>Ct(e.x)));let t=0;for(const n of e.fs){const e=Ct(n.b);e&&(t+=e*(Tt(n.e)?n.e.q.toNumber():1))}return t}function Zt(e,t){return"num"===e.k?t&&!Tt(t)?3:0:Ot(e)?1.5:"atom"===e.k&&"sym"===e.node.type?Mt(e.node.token)?t&&!Tt(t)?3:1:2:"atom"===e.k?3:4}const Ft=(e,t)=>e<t?-1:e>t?1:0;function Bt(e){const t=new Map,n=(e,n)=>{"atom"!==e.k||"sym"!==e.node.type||Mt(e.node.token)||t.set(e.node.token,(t.get(e.node.token)??0)+n)};if("mul"===e.k)for(const t of e.fs)n(t.b,Tt(t.e)?t.e.q.toNumber():1);else n(e,1);return t}function Dt(e,t){const n=Ct(t.x)-Ct(e.x);if(n)return n;const s=Bt(e.x),i=Bt(t.x);for(const e of[...new Set([...s.keys(),...i.keys()])].sort()){const t=(i.get(e)??0)-(s.get(e)??0);if(t)return t}return Ft(zt(e.x),zt(t.x))}function Pt(e,t){return e.isOne?t:e.isZero?Et:Wt([At(e),t])}function Rt(e){if("num"===e.k)return{coef:e.q,rest:null};if("mul"!==e.k||e.c.isOne)return{coef:bt.ONE,rest:e};const t=1===e.fs.length&&Tt(e.fs[0].e)&&e.fs[0].e.q.isOne?e.fs[0].b:{k:"mul",c:bt.ONE,fs:e.fs};return{coef:e.c,rest:t}}function _t(e){let t=bt.ZERO;const n=new Map,s=(e,t)=>{const s=zt(t),i=n.get(s);i?i.coef=i.coef.add(e):n.set(s,{coef:e,x:t})};for(const n of e)if("num"===n.k)t=t.add(n.q);else if("add"===n.k){t=t.add(n.c);for(const e of n.terms)s(e.coef,e.x)}else{const{coef:e,rest:t}=Rt(n);s(e,t)}const i=[...n.values()].filter(e=>!e.coef.isZero);return i.length?t.isZero&&1===i.length?Pt(i[0].coef,i[0].x):(i.sort(Dt),{k:"add",c:t,terms:i}):At(t)}function Vt(e,t){if(!Tt(t))return e.isOne?{coef:bt.ONE,fs:[]}:{coef:bt.ONE,fs:[{b:At(e),e:t}]};const n=t.q;if(n.isInteger)return{coef:e.pow(n.n),fs:[]};if(e.isZero){if(n.sign<0)throw new ft("division by zero");return{coef:bt.ZERO,fs:[]}}if(e.isOne)return{coef:bt.ONE,fs:[]};if(e.sign<0){if(n.d%2n==1n){const{coef:s,fs:i}=Vt(e.neg(),t);return{coef:n.n%2n==0n?s:s.neg(),fs:i}}if($t.complex&&2n===n.d){const{coef:s,fs:i}=Vt(e.neg(),t);return{coef:s,fs:[...i,{b:Kt,e:At(new bt(n.n))}]}}return{coef:bt.ONE,fs:[{b:At(e),e:t}]}}if(!e.isInteger){const s=Vt(new bt(e.n),t),i=Vt(new bt(e.d),At(n.neg()));return{coef:s.coef.mul(i.coef),fs:[...s.fs,...i.fs]}}const s=n.floor(),i=n.sub(s);if(BigInt(gt(e.n))*i.n>BigInt(dt)||i.d>1000n)return{coef:bt.ONE,fs:[{b:At(e),e:t}]};let r=s.isZero?bt.ONE:e.pow(s.n);const{outside:o,inside:a}=kt(e.n**i.n,Number(i.d));r=r.mul(new bt(o));return{coef:r,fs:a>1n?[{b:At(new bt(a)),e:At(new bt(1n,i.d))}]:[]}}function Wt(e){let t=bt.ONE;const n=new Map,s=(e,t)=>{const s=zt(e),i=n.get(s);i?i.e=_t([i.e,t]):n.set(s,{b:e,e:t})};for(const n of e)if("num"===n.k)t=t.mul(n.q);else if("mul"===n.k){t=t.mul(n.c);for(const e of n.fs)s(e.b,e.e)}else s(n,Nt);if(t.isZero)return Et;const i=[],r=new Map;for(const e of n.values())if(!Tt(e.e)||!e.e.q.isZero){if("num"===e.b.k){if(Tt(e.e)&&!e.e.q.isInteger&&e.b.q.sign>0&&e.b.q.isInteger){const t=e.e.q.toString(),n=r.get(t);n?n.n*=e.b.q.n:r.set(t,{n:e.b.q.n,e:e.e});continue}const n=Vt(e.b.q,e.e);t=t.mul(n.coef),i.push(...n.fs);continue}if("mul"===e.b.k&&Tt(e.e)&&e.e.q.isInteger){const n=Ut(e.b,e.e);"mul"===n.k?(t=t.mul(n.c),i.push(...n.fs)):"num"===n.k?t=t.mul(n.q):i.push({b:n,e:Nt});continue}i.push(e)}for(const{n:e,e:n}of r.values()){const s=Vt(new bt(e),n);t=t.mul(s.coef),i.push(...s.fs)}if(t.isZero)return Et;const o=new Map;for(const e of i){const t=zt(e.b),n=o.get(t);n?n.e=_t([n.e,e.e]):o.set(t,{...e})}let a=[...o.values()].filter(e=>!(Tt(e.e)&&e.e.q.isZero));if($t.complex){a=a.flatMap(e=>{if(!Ot(e.b)||!Tt(e.e)||!e.e.q.isInteger)return[e];const n=(e.e.q.n%4n+4n)%4n;return n>=2n&&(t=t.neg()),n%2n?[{b:e.b,e:Nt}]:[]});const e=a.filter(e=>"add"===e.b.k&&Tt(e.e)&&e.e.q.isInteger&&Qt(e.b)),n=a.some(e=>Ot(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||n||!e[0].e.q.isOne)){const s=a.filter(t=>!e.includes(t)&&!Ot(t.b));let i=n?[Kt]:[Nt];for(const t of e){const e=t.e.q.sign<0?Xt(t.b):t.b;for(let n=0n;n<(t.e.q.sign<0?-t.e.q.n:t.e.q.n);n++)i=Yt(i,bn(e))}return Wt([At(t),_t(i),...s.map(e=>Ht(e.b,e.e))])}}if(a.some(e=>"num"===e.b.k&&Tt(e.e)&&e.e.q.compare(bt.ONE)>=0))return Wt([At(t),...a.map(e=>"num"===e.b.k?Ut(e.b,e.e):{k:"mul",c:bt.ONE,fs:[e]})]);if(!a.length)return At(t);if(1===a.length&&!t.isOne&&"add"===a[0].b.k&&Tt(a[0].e)&&a[0].e.q.isOne){const e=a[0].b;return _t([At(t.mul(e.c)),...e.terms.map(e=>Pt(t.mul(e.coef),e.x))])}return t.isOne&&1===a.length&&Tt(a[0].e)&&a[0].e.q.isOne?a[0].b:(a=a.sort((e,t)=>Zt(e.b,e.e)-Zt(t.b,t.e)||Ft(zt(e.b),zt(t.b))),{k:"mul",c:t,fs:a})}function Ut(e,t){if($t.complex&&Tt(t)&&t.q.isInteger){if(Ot(e))return Wt([{k:"mul",c:bt.ONE,fs:[{b:e,e:t}]}]);if("add"===e.k&&Qt(e)&&!t.q.isOne)return Wt([{k:"mul",c:bt.ONE,fs:[{b:e,e:t}]}])}if(Tt(t)){if(t.q.isZero){if(Tt(e)&&e.q.isZero)throw new ft("0^0 is undefined");return Nt}if(t.q.isOne)return e}if(Tt(e)){const n=Vt(e.q,t);if(!n.fs.length)return At(n.coef);if(n.fs.some(e=>Ot(e.b)))return Wt([At(n.coef),...n.fs.map(e=>({k:"mul",c:bt.ONE,fs:[e]}))]);const s={k:"mul",c:n.coef,fs:n.fs};return n.coef.isOne&&1===n.fs.length&&Tt(n.fs[0].e)&&n.fs[0].e.q.isOne?n.fs[0].b:s}if($t.complex&&Tt(t)&&2n===t.q.d&&Qt(e)){const n=Gt(e);if(n&&Tt(n.im)&&!n.im.q.isZero){const e=e=>Ut(e,At(bt.of(2))),s=Ut(_t([e(n.re),e(n.im)]),It),i=Ut(Wt([_t([s,n.re]),At(bt.HALF)]),It),r=Ut(Wt([_t([s,nn(n.re)]),At(bt.HALF)]),It);return Ut(_t([i,Wt([At(bt.of(n.im.q.sign)),r,Kt])]),At(new bt(t.q.n)))}}if("mul"===e.k){if(Tt(t)&&t.q.isInteger)return Wt([At(e.c.pow(t.q.n)),...e.fs.map(e=>Ht(e.b,Wt([e.e,t])))]);if(!e.c.isOne&&e.c.sign>0)return Wt([Ut(At(e.c),t),Ut({k:"mul",c:bt.ONE,fs:e.fs},t)]);if(e.c.isOne&&1===e.fs.length){const[n]=e.fs;if(Tt(n.e)&&Tt(t)&&1n===n.e.q.n&&n.e.q.d%2n==1n)return Ht(n.b,Wt([n.e,t]))}}return{k:"mul",c:bt.ONE,fs:[{b:e,e:t}]}}function Ht(e,t){return Tt(t)&&t.q.isZero?Nt:Tt(e)?Ut(e,t):Tt(t)&&t.q.isOne?e:{k:"mul",c:bt.ONE,fs:[{b:e,e:t}]}}const Kt=Lt(Ge("i")),Jt=e=>$t.complex&&dn(e).s.split(" ").includes("i");function Qt(e){return $t.complex&&Jt(e)&&0===vn(dn(e)).size}function Yt(e,t){const n=[];for(const s of e)for(const e of t)n.push(Wt([s,e]));return bn(_t(n))}function Gt(e){const t=[],n=[];for(const s of bn(e)){const{coef:e,rest:i}=Rt(s),r=i?yn(i):[],o=r.filter(e=>Ot(e)),a=r.filter(e=>!Ot(e));if(a.some(e=>Jt(e)))return null;(o.length?n:t).push(Wt([At(e),...a]))}return{re:_t(t),im:_t(n)}}function Xt(e){const t=Gt(e);if(!t)return Ut(e,At(bt.MINUS_ONE));const n=_t([Ut(t.re,At(bt.of(2))),Ut(t.im,At(bt.of(2)))]);return Wt([_t([t.re,Wt([At(bt.MINUS_ONE),t.im,Kt])]),Ut(n,At(bt.MINUS_ONE))])}const en={re:([e])=>Gt(e)?.re??null,im:([e])=>Gt(e)?.im??null,conj:([e])=>{const t=Gt(e);return t?_t([t.re,Wt([At(bt.MINUS_ONE),t.im,Kt])]):null},arg:([e])=>{const t=Gt(e);return t?an("atan2",[t.im,t.re]):null},abs:([e])=>{const t=Gt(e);return!t||Tt(t.im)&&t.im.q.isZero?null:Ut(_t([Ut(t.re,At(bt.of(2))),Ut(t.im,At(bt.of(2)))]),It)}},tn={Re:"re",re:"re",Im:"im",im:"im",conj:"conj",overline:"conj",bar:"conj",arg:"arg"},nn=e=>Wt([At(bt.MINUS_ONE),e]),sn=(e,t)=>Wt([e,Ut(t,At(bt.MINUS_ONE))]),rn=3000n,on={abs:([e])=>Tt(e)?At(e.q.abs()):"mul"!==e.k||e.c.isOne?null:Wt([At(e.c.abs()),an("abs",[Rt(e).rest])]),floor:([e])=>Tt(e)?At(e.q.floor()):null,ceil:([e])=>Tt(e)?At(e.q.ceil()):null,"!":([e])=>{if(!Tt(e)||!e.q.isInteger||e.q.sign<0||e.q.n>rn)return null;let t=1n;for(let n=2n;n<=e.q.n;n++)t*=n;return At(new bt(t))},mod:([e,t])=>Tt(e)&&Tt(t)&&!t.q.isZero?At(e.q.sub(t.q.mul(e.q.div(t.q).floor()))):null,max:e=>e.every(Tt)&&e.length?e.reduce((e,t)=>t.q.compare(e.q)>0?t:e):null,min:e=>e.every(Tt)&&e.length?e.reduce((e,t)=>t.q.compare(e.q)<0?t:e):null,gcd:e=>e.length&&e.every(e=>Tt(e)&&e.q.isInteger)?At(new bt(e.reduce((e,t)=>vt(e,t.q.n),0n))):null,log:([e,t])=>{if(!Tt(e)||!Tt(t)||e.q.sign<=0||t.q.sign<=0||e.q.isOne)return null;if(t.q.isOne)return Et;const n=Math.log(t.q.toNumber())/Math.log(e.q.toNumber());if(!Number.isFinite(n))return null;for(let s=1;s<=12;s++){const i=Math.round(n*s);if(!(Math.abs(n*s-i)>1e-9||0===i)&&(Math.abs(i)<=256&&e.q.pow(BigInt(i)).equals(t.q.pow(BigInt(s)))))return At(new bt(BigInt(i),BigInt(s)))}return null},comb:([e,t])=>Tt(e)&&Tt(t)&&e.q.isInteger&&t.q.isInteger&&e.q.sign>=0&&t.q.sign>=0&&e.q.n<=rn?At(function(e,t){if(t>e)return bt.ZERO;t>e-t&&(t=e-t);let n=1n;for(let s=1n;s<=t;s++)n=n*(e-t+s)/s;return new bt(n)}(e.q.n,t.q.n)):null,perm:([e,t])=>{if(!(Tt(e)&&Tt(t)&&e.q.isInteger&&t.q.isInteger&&e.q.sign>=0&&t.q.sign>=0&&e.q.n<=rn))return null;if(t.q.n>e.q.n)return Et;let n=1n;for(let s=0n;s<t.q.n;s++)n*=e.q.n-s;return At(new bt(n))}};function an(e,t){if($t.complex&&en[e]){const n=en[e](t);if(n)return n}const n=on[e];if(n){const e=n(t);if(e)return e}return Lt(nt(e,t.map(dn)))}const un=new Map;function ln(e){const t=$t.complex?`ℂ ${e.s}`:e.s,n=un.get(t);if(n)return n;const s=function(e){if("num"===e.type){const t=yt(e.token);if(!t)throw new ft(`not an exact number: ${e.token}`);return At(t)}if("sym"===e.type)return"π"===e.token?Lt(Ge("pi")):Lt(e);const t=e.args.map(ln);switch(e.op){case"+":return _t(t);case"-":return((e,t)=>_t([e,nn(t)]))(t[0],t[1]);case"neg":return nn(t[0]);case"*":return Wt(t);case"/":return sn(t[0],t[1]);case"^":return Ut(t[0],t[1]);case"sqrt":return Ut(t[0],It);case"root":return Ut(t[1],Ut(t[0],At(bt.MINUS_ONE)));default:{const n=e.op.startsWith("\\:")?e.op.slice(2):null;return n&&$t.complex&&tn[n]&&1===t.length?an(tn[n],t):n&&_e(n)&&Re(n).arity===t.length?an(n,t):an(e.op,t)}}}(e);return un.size>2e4&&un.clear(),un.set(t,s),s}const cn=e=>dn(ln(e)),pn=e=>Xe(String(e));function hn(e){return e.isInteger?pn(e.n):nt("/",[pn(e.n),pn(e.d)])}const fn=new WeakMap;function dn(e){let t=fn.get(e);return t||fn.set(e,t=function(e){switch(e.k){case"num":return hn(e.q);case"atom":return e.node;case"mul":return function(e,t){const n=[],s=[];for(const e of t)Tt(e.e)&&e.e.q.sign<0?s.push(mn(e.b,At(e.e.q.neg()))):n.push(mn(e.b,e.e));let i=1n!==e.n&&-1n!==e.n||!n.length?gn([pn(e.n),...n]):gn(n);-1n===e.n&&n.length&&(i=nt("neg",[i]));1n!==e.d&&s.unshift(pn(e.d));return s.length?nt("/",[i,gn(s)]):i}(e.c,e.fs);case"add":return function(e){let t=null;const n=e=>$t.complex&&Jt(e.x)&&0===vn(dn(e.x)).size,s=[...e.terms.filter(e=>!n(e)),...e.terms.filter(n)],i=e.c,r=()=>{i.isZero||(t=t?i.sign<0?nt("-",[t,hn(i.neg())]):nt("+",[t,hn(i)]):hn(i))};let o=!1;for(const e of s)!o&&n(e)&&(r(),o=!0),t=t?e.coef.sign<0?nt("-",[t,dn(Pt(e.coef.neg(),e.x))]):nt("+",[t,dn(Pt(e.coef,e.x))]):dn(Pt(e.coef,e.x));o||r();return t}(e);default:throw new Error(`bad form ${e.k}`)}}(e)),t}function mn(e,t){const n=dn(e);if(Tt(t)){const e=t.q;if(e.isOne)return n;if(1n===e.n&&2n===e.d)return nt("sqrt",[n]);if(1n===e.n)return nt("root",[pn(e.d),n])}return nt("^",[n,dn(t)])}const gn=e=>e.reduce((e,t)=>e?nt("*",[e,t]):t,null);function vn(e,t=new Set){if("sym"===e.type)Mt(e.token)||t.add(e.token);else if(it(e))for(const n of e.args)vn(n,t);return t}function bn(e){if("add"!==e.k)return[e];const t=e.terms.map(e=>Pt(e.coef,e.x));return e.c.isZero||t.push(At(e.c)),t}function yn(e){if("num"===e.k)return[e];if("mul"!==e.k)return[e];const t=e.c.isOne?[]:[At(e.c)];for(const n of e.fs)t.push(Ht(n.b,n.e));return t}const wn="_",xn=new WeakMap;function kn(e,t){return[...t,...Re(e.op)?.arity===Ze?[String(e.args.length)]:[],e.op].join(" ")}function qn(e,t){let n=xn.get(e);n||xn.set(e,n=new Map);const s=n.get(t);if(s)return s;const i=function(e,t){const n={key:wn,slots:[e]};if(e.type!==Ke||t<=0)return[n];const s=e.args.map(e=>qn(e,t-1)),i=[n],r=new Array(s.length).fill(0);for(;;){const t=[],n=[];for(let e=0;e<s.length;e++){const i=s[e][r[e]];t.push(i.key);for(const e of i.slots)n.push(e)}if(i.push({key:kn(e,t),slots:n}),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,t);return n.set(t,i),i}function $n(e){return e.type!==Ke?wn:kn(e,e.args.map($n))}function Sn(e,t=[]){if(e.type!==Ke)t.push(e);else for(const n of e.args)Sn(n,t);return t}const Mn=new Map,On=new Map;class An extends Error{constructor(e){super(e),this.name="RequirementError"}}function Nn(e,t,n=""){Mn.set(e,{name:e,fn:t,doc:n,arity:Math.max(0,t.length-1)})}function En(e,t,n=""){On.set(e,{name:e,fn:t,doc:n})}function In(e){return Mn.get(e)||null}function Tn(e){return On.get(e)||null}const Ln=e=>e.type===Ue;function jn(e,t){return e.type===Ke&&(e.op===t||e.args.some(e=>jn(e,t)))}Nn("always",()=>!0,"matches anything"),Nn("never",()=>!1,"matches nothing"),Nn("isLeaf",e=>e.type!==Ke,"a bare operand, not an operation"),Nn("isCompound",e=>e.type===Ke,"an operation, not a bare operand"),Nn("isSymbol",e=>e.type===He,"a non-numeric operand such as x"),Nn("isOperation",(e,t)=>e.type===Ke&&e.op===t,"is this specific operation"),Nn("notOperation",(e,t)=>!(e.type===Ke&&e.op===t),"is anything except this operation"),Nn("isNumber",Ln,"a numeric literal"),Nn("isInteger",e=>Ln(e)&&Number.isInteger(e.value),"a whole number"),Nn("isPositive",e=>Ln(e)&&e.value>0,"greater than zero"),Nn("isNegative",e=>Ln(e)&&e.value<0,"less than zero"),Nn("isNonNegative",e=>Ln(e)&&e.value>=0,"zero or greater"),Nn("isZero",e=>Ln(e)&&0===e.value,"exactly 0"),Nn("isOne",e=>Ln(e)&&1===e.value,"exactly 1"),Nn("isNonZero",e=>Ln(e)&&0!==e.value,"a number that is provably not 0"),Nn("isNotZeroLiteral",e=>!(Ln(e)&&0===e.value),"anything except a literal 0"),Nn("isPositiveInteger",e=>Ln(e)&&Number.isInteger(e.value)&&e.value>0,"a whole number above 0"),Nn("isNegativeInteger",e=>Ln(e)&&Number.isInteger(e.value)&&e.value<0,"a whole number below 0"),Nn("isEven",e=>Ln(e)&&Number.isInteger(e.value)&&e.value%2==0,"a whole even number"),Nn("isOdd",e=>Ln(e)&&Number.isInteger(e.value)&&1===Math.abs(e.value%2),"a whole odd number"),Nn("greaterThan",(e,t)=>Ln(e)&&e.value>Number(t),"above a given value"),Nn("lessThan",(e,t)=>Ln(e)&&e.value<Number(t),"below a given value"),Nn("isValue",(e,t)=>Ln(e)&&e.value===Number(t),"equals a given number"),Nn("isNumeric",ct,"contains no symbols: a constant (it need not fold to a number: 1 sin)"),Nn("hasSymbol",e=>!ct(e),"mentions a symbol somewhere, so it is not just a number"),Nn("isVar",(e,t)=>e.type===He&&e.token===String(t),"is exactly this symbol"),Nn("contains",(e,t)=>lt(e).includes(String(t)),"mentions this operand somewhere"),Nn("isFree",(e,t)=>!lt(e).includes(String(t)),"never mentions this operand"),Nn("hasOperation",(e,t)=>jn(e,String(t)),"uses this operation somewhere inside"),Nn("equals",(e,t)=>e.s===String(t),"is exactly this postfix expression");const zn=e=>e.type===Ke?null:e.token;function Cn(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 An(`bad requirement: ${JSON.stringify(e)}`)}En("freeOf",(e,t)=>{const n=zn(t);return null!==n&&!lt(e).includes(n)},"the first operand never mentions the second"),En("dependsOn",(e,t)=>{const n=zn(t);return null!==n&&lt(e).includes(n)},"the first operand does mention the second"),En("sameAs",(...e)=>e.every(t=>t.s===e[0].s),"these operands are structurally identical"),En("differs",(...e)=>new Set(e.map(e=>e.s)).size===e.length,"these operands are all different"),En("sameValue",(...e)=>e.every(e=>Ln(e))&&e.every(t=>t.value===e[0].value),"these operands are the same number");const Zn="simplify";class Fn extends Error{constructor(e,t){super(t?`rule "${t}": ${e}`:e),this.name="RuleError",this.ruleId=t}}const Bn=/^[A-Za-z_][A-Za-z0-9_]*$/;function Dn(e,t){if(st(e))return{literal:e.value};const n=e.token;if(n.startsWith("=")){const e=n.slice(1);if(""===e)throw new Fn('"=" needs an operand after it',t);return{token:e}}if(!Bn.test(n))throw new Fn(`"${n}" is not a usable slot name; use letters, digits and _`,t);if(_e(n))throw new Fn(`slot name "${n}" collides with an operator`,t);return{name:n}}function Pn(e){if(!it(e))return[e];const t=e.args.map(Pn),n=Re(e.op),s=[];for(const i of function(e){let t=[[]];for(const n of e){const e=[];for(const s of t)for(const t of n)e.push(s.concat([t]));if(t=e,t.length>64)return t.slice(0,64)}return t}(t))if(s.push(nt(e.op,i)),n.commutative&&2===i.length&&i[0].s!==i[1].s&&s.push(nt(e.op,[i[1],i[0]])),s.length>=64)break;return s}function Rn(e,t=[]){return"op"===e.kind?e.args.forEach(e=>Rn(e,t)):"const"===e.kind&&e.free&&t.push(e.node.token),t}function _n(e){if(!e||"object"!=typeof e)throw new Fn("rule must be a mapping");const t=e.id||e.name;if(!t)throw new Fn("rule needs an id");if(!e.pattern)throw new Fn("rule needs a pattern",t);if(void 0===e.output||null===e.output)throw new Fn("rule needs an output",t);let n;try{n=rt(String(e.pattern))}catch(e){if(e instanceof Qe)throw new Fn(`bad pattern: ${e.message}`,t);throw e}const s=Sn(n).map(e=>Dn(e,t)),i=new Set(s.filter(e=>e.name).map(e=>e.name)),r=function(e,t,n){const s=[],i=e.when||{};if("object"!=typeof i||Array.isArray(i))throw new Fn('"when" must map slot names to lists of requirements',n);for(const[e,r]of Object.entries(i)){if(!t.has(e))throw new Fn(`"when" mentions "${e}", which is not a slot in the pattern`,n);const i=Array.isArray(r)?r:[r];for(const t of i){const{name:i,args:r}=Cn(t),o=In(i);if(!o)throw new Fn(`unknown requirement "${i}"`,n);s.push({slot:e,name:i,args:r,fn:o.fn})}}return s}(e,i,t),o=function(e,t,n){const s=[],i=e.require||[];if(!Array.isArray(i))throw new Fn('"require" must be a list of relations',n);for(const e of i){const{name:i,args:r}=Cn(e),o=Tn(i);if(!o)throw new Fn(`unknown relation "${i}"`,n);if(r.length<2)throw new Fn(`relation "${i}" needs at least two operands`,n);for(const e of r)if("string"==typeof e&&!t.has(e)&&Bn.test(e))throw new Fn(`relation "${i}" mentions "${e}", which is not a slot in the pattern`,n);s.push({name:i,args:r,fn:o.fn})}return s}(e,i,t),a=function(e,t,n){let s;try{s=rt(e)}catch(t){throw new Fn(`bad output "${e}": ${t.message}`,n)}const i=e=>it(e)?{kind:"op",op:e.op,args:e.args.map(i)}:st(e)?{kind:"const",node:e}:t.has(e.token)?{kind:"slot",name:e.token}:e.token.startsWith("=")?{kind:"const",node:Ge(e.token.slice(1))}:{kind:"const",node:e,free:!0};return i(s)}(String(e.output),i,t),u=e.commutative?Pn(n):[n],l=[],c=new Set;for(const e of u){const n=$n(e),s=Sn(e).map(e=>Dn(e,t)),i=n+"\0"+s.map(e=>e.name??(void 0!==e.literal?`#${e.literal}`:`=${e.token}`)).join(",");c.has(i)||(c.add(i),l.push({key:n,slots:s}))}const p={id:String(t),name:e.name?String(e.name):String(t),pattern:String(e.pattern),patternTree:n,output:String(e.output),outputTemplate:a,explain:e.explain?String(e.explain).trim():"",mode:e.mode?String(e.mode):Zn,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:at(n),bindings:l,freeSymbols:Rn(a),source:e};for(const e of l)e.rule=p;return p}function Vn(e){const t={};for(const n of e.when)(t[n.slot]||=[]).push(n.args.length?[n.name,...n.args]:n.name);const n={id:e.id};return e.name!==e.id&&(n.name=e.name),e.mode!==Zn&&(n.mode=e.mode),n.pattern=e.pattern,Object.keys(t).length&&(n.when=t),e.require.length&&(n.require=e.require.map(e=>[e.name,...e.args])),n.output=e.output,e.explain&&(n.explain=e.explain),e.fold&&(n.fold=!0),e.commutative&&(n.commutative=!0),e.priority&&(n.priority=e.priority),e.tags.length&&(n.tags=e.tags),e.enabled||(n.enabled=!1),n}class Wn extends Error{constructor(e,t){super(null==t?e:`${e} (line ${t+1})`),this.name="YamlError",this.line=t}}class Un{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 Hn=e=>"-"===e||e.startsWith("- ");function Kn(e){let t=null,n=0;for(let s=0;s<e.length;s++){const i=e[s];if(t)i===t?"'"===t&&"'"===e[s+1]?s++:t=null:'"'===t&&"\\"===i&&s++;else if('"'===i||"'"===i)t=i;else if("["===i||"{"===i)n++;else if("]"===i||"}"===i)n--;else if(":"===i&&0===n&&(s+1===e.length||" "===e[s+1])){const t=e.slice(0,s).trim();return""===t?null:{key:Jn(t),rest:e.slice(s+1).trim()}}}return null}function Jn(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 Qn(e){const t=new Un(function(e){return String(e).split(/\r?\n/).map((e,t)=>{const n=e.search(/\S/);if(-1===n)return{raw:e,n:t,indent:0,text:"",blank:!0};const s=function(e){let t=null;for(let n=0;n<e.length;n++){const s=e[n];if(t)s===t?"'"===t&&"'"===e[n+1]?n++:t=null:'"'===t&&"\\"===s&&n++;else if('"'===s||"'"===s)t=s;else if("#"===s&&(0===n||/\s/.test(e[n-1])))return e.slice(0,n)}return e}(e.slice(n)).trimEnd();return{raw:e,n:t,indent:n,text:s,blank:""===s}})}(e));let n=t.peek();if(n&&"---"===n.text&&(t.next(),n=t.peek()),!n)return null;const s=Gn(t,n.indent),i=t.peek();if(i&&"..."!==i.text&&"---"!==i.text)throw new Wn(`unexpected content "${i.text}"`,i.n);return s}const Yn=/^[|>][-+]?\d*$/;function Gn(e,t){const n=e.peek();return!n||n.indent<t?null:Hn(n.text)?Xn(e,n.indent):Kn(n.text)?function(e,t){const n={};for(;;){const s=e.peek();if(!s||s.indent!==t)break;const i=Kn(s.text);if(!i)break;e.next();const{key:r,rest:o}=i;if(""===o){const s=e.peek();s&&s.indent>t?n[r]=Gn(e,s.indent):s&&s.indent===t&&Hn(s.text)?n[r]=Xn(e,t):n[r]=null}else Yn.test(o)?n[r]=es(e,o,t):n[r]=ts(o,s.n)}return n}(e,n.indent):(e.next(),Yn.test(n.text)?es(e,n.text,n.indent-1):ts(n.text,n.n))}function Xn(e,t){const n=[];for(;;){const s=e.peek();if(!s||s.indent!==t||!Hn(s.text))break;if(e.next(),"-"===s.text){const s=e.peek();n.push(s&&s.indent>t?Gn(e,s.indent):null);continue}if(Yn.test(s.text.slice(2).trim())){n.push(es(e,s.text.slice(2).trim(),t));continue}const i=s.text.slice(2),r=t+2+(i.length-i.trimStart().length);e.push({raw:s.raw,n:s.n,indent:r,text:i.trim(),blank:!1}),n.push(Gn(e,r))}return n}function es(e,t,n){const s=t[0],i=(t.match(/[-+]/)||[""])[0],r=(t.match(/\d+/)||[null])[0];let o=r?n+Number(r):null;const a=[];for(;e.i<e.records.length;){const t=e.records[e.i];if(""===t.raw.trim()){a.push(""),e.i++;continue}const s=t.raw.search(/\S/);if(s<=n)break;if(null===o&&(o=s),s<o)break;a.push(t.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 t of a)""===t?e.push("\n"):e.length&&"\n"!==e[e.length-1]?e[e.length-1]+=" "+t:e.push(t);u=e.join("").replace(/\n(?!$)/g,"\n")}return"-"===i?u:"+"===i?u+"\n":""===u?"":u+"\n"}function ts(e,t){const n=e.trim();return""===n||"~"===n||"null"===n||"Null"===n||"NULL"===n?null:"true"===n||"True"===n||"TRUE"===n||"false"!==n&&"False"!==n&&"FALSE"!==n&&("["===n[0]||"{"===n[0]?function(e,t){const n={text:e,i:0,line:t},s=ss(n);if(ns(n),n.i<n.text.length)throw new Wn(`unexpected "${n.text.slice(n.i)}" in flow value`,t);return s}(n,t):'"'===n[0]||"'"===n[0]?Jn(n):/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(n)?Number(n):n)}const ns=e=>{for(;e.i<e.text.length&&/\s/.test(e.text[e.i]);)e.i++};function ss(e){ns(e);const t=e.text[e.i];return"["===t?function(e){e.i++;const t=[];for(;;){if(ns(e),e.i>=e.text.length)throw new Wn("unterminated [",e.line);if("]"===e.text[e.i])return e.i++,t;if(t.push(ss(e)),ns(e),","===e.text[e.i])e.i++;else if("]"!==e.text[e.i])throw new Wn(`expected , or ] near "${e.text.slice(e.i)}"`,e.line)}}(e):"{"===t?function(e){e.i++;const t={};for(;;){if(ns(e),e.i>=e.text.length)throw new Wn("unterminated {",e.line);if("}"===e.text[e.i])return e.i++,t;const n=String(ss(e));if(ns(e),":"!==e.text[e.i])throw new Wn(`expected : after "${n}"`,e.line);if(e.i++,t[n]=ss(e),ns(e),","===e.text[e.i])e.i++;else if("}"!==e.text[e.i])throw new Wn(`expected , or } near "${e.text.slice(e.i)}"`,e.line)}}(e):ts(function(e){const t=e.text[e.i];if('"'===t||"'"===t){const n=e.i;for(e.i++;e.i<e.text.length;)if("\\"===e.text[e.i]&&'"'===t)e.i+=2;else if(e.text[e.i]===t){if("'"!==t||"'"!==e.text[e.i+1])return e.i++,e.text.slice(n,e.i);e.i+=2}else e.i++;throw new Wn("unterminated quoted string",e.line)}const n=e.i;for(;e.i<e.text.length;){const t=e.text[e.i];if(","===t||"]"===t||"}"===t)break;if(":"===t){const t=e.text[e.i+1];if(void 0===t||/[\s,\]}]/.test(t))break}e.i++}return e.text.slice(n,e.i).trim()}(e),e.line)}const is=/^(true|false|null|yes|no|on|off|~)$/i;function rs(e){if(null==e)return"null";if("boolean"==typeof e)return e?"true":"false";if("number"==typeof e){if(!Number.isFinite(e))throw new Wn(`cannot serialize ${e}`);return String(e)}const t=String(e);return function(e){return!!(""===e||/^\s|\s$/.test(e)||/[\u0000-\u001f\u007f]/.test(e)||/^[-?:,[\]{}#&*!|>'"%@`]/.test(e)||/: |\s#/.test(e)||is.test(e)||/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(e))}(t)?JSON.stringify(t):t}const os=e=>null==e||"object"!=typeof e;function as(e){return Array.isArray(e)?`[${e.map(as).join(", ")}]`:e&&"object"==typeof e?`{${Object.entries(e).map(([e,t])=>`${rs(e)}: ${as(t)}`).join(", ")}}`:rs(e)}function us(e){return Array.isArray(e)?!!e.every(e=>os(e)||Array.isArray(e)&&e.every(os))&&as(e).length<=72:!(!e||"object"!=typeof e)&&(Object.values(e).every(e=>os(e)||Array.isArray(e)&&e.every(os))&&as(e).length<=72)}function ls(e){const t=[];return cs(e,0,t),t.length?t.join("\n")+"\n":""}function cs(e,t,n){const s=" ".repeat(t);if(Array.isArray(e)){if(0===e.length)return void n.push(s+"[]");for(const s of e)ps(s,t,n)}else{if(e&&"object"==typeof e){const i=Object.entries(e).filter(([,e])=>void 0!==e);if(0===i.length)return void n.push(s+"{}");for(const[e,s]of i)hs(e,s,t,n);return}!function(e,t,n){if("string"==typeof e&&e.includes("\n")){n.push(t+"|-");for(const s of e.replace(/\n+$/,"").split("\n"))n.push(t+" "+s);return}n.push(t+rs(e))}(e,s,n)}}function ps(e,t,n){const s=" ".repeat(t);if(null!==e&&"object"==typeof e&&!us(e)){const i=[];if(cs(e,t+2,i),0===i.length)return void n.push(s+"-");n.push(s+"- "+i[0].slice(t+2));for(let e=1;e<i.length;e++)n.push(i[e]);return}if(null===e||"object"!=typeof e)if("string"==typeof e&&e.includes("\n")){n.push(s+"- |-");for(const s of e.replace(/\n+$/,"").split("\n"))n.push(" ".repeat(t+4)+s)}else n.push(s+"- "+rs(e));else n.push(s+"- "+as(e))}function hs(e,t,n,s){const i=" ".repeat(n),r=rs(e);if("string"==typeof t&&t.includes("\n")){s.push(`${i}${r}: |-`);for(const e of t.replace(/\n+$/,"").split("\n"))s.push(" ".repeat(n+2)+e)}else{if(null!==t&&"object"==typeof t)return us(t)?void s.push(`${i}${r}: ${as(t)}`):(s.push(`${i}${r}:`),void cs(t,Array.isArray(t)?n:n+2,s));s.push(`${i}${r}: ${rs(t)}`)}}class fs{constructor(e=[]){this.index=new Map,this.rules=[],this.maxDepth=0,this.name="",this.views=new Map;for(const t of e)this.add(t)}add(e){const t=e&&e.bindings?e:_n(e);if(this.rules.some(e=>e.id===t.id))throw new Fn(`duplicate rule id "${t.id}"`);return this.rules.push(t),t.enabled&&this.link(t),t.depth>this.maxDepth&&(this.maxDepth=t.depth),this.views.clear(),t}view(e){if(!e)return this;let t=this.views.get(e);return t||(t=new fs(this.rules.filter(t=>t.mode===e)),t.name=this.name,this.views.set(e,t)),t}modes(){return[...new Set(this.rules.map(e=>e.mode))].sort((e,t)=>e===Zn?-1:t===Zn?1:e.localeCompare(t))}link(e){for(const t of e.bindings){let e=this.index.get(t.key);e||this.index.set(t.key,e=[]),e.push(t),e.sort((e,t)=>t.rule.priority-e.rule.priority||t.rule.depth-e.rule.depth)}}remove(e){const t=this.rules.findIndex(t=>t.id===e);return-1!==t&&(this.rules.splice(t,1),this.reindex(),!0)}setEnabled(e,t){const n=this.get(e);return!!n&&(n.enabled=!!t,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(t=>t.id===e)||null}candidates(e){return this.index.get(e)||null}get size(){return this.rules.length}static fromYaml(e,{strict:t=!0}={}){const n=Qn(e);return fs.fromSpecs(n,{strict:t})}static fromSpecs(e,{strict:t=!0}={}){let n=e,s="";if(e&&!Array.isArray(e)&&"object"==typeof e&&(n=e.rules,s=e.name?String(e.name):""),!Array.isArray(n))throw new Fn('expected a list of rules, or a mapping with a "rules" list');const i=new fs;i.name=s;const r=[];for(let e=0;e<n.length;e++)try{i.add(n[e])}catch(t){r.push(`#${e+1}: ${t.message}`)}if(r.length&&t)throw new Fn(`${r.length} rule(s) failed to compile:\n ${r.join("\n ")}`);return i.errors=r,i}toSpecs(){return this.rules.map(Vn)}toYaml(){const e=this.toSpecs();return this.name?ls({name:this.name,rules:e}):ls(e)}keyReport(){return[...this.index.entries()].map(([e,t])=>({key:e,rules:t.map(e=>e.rule.id)})).sort((e,t)=>e.key.localeCompare(t.key))}}function ds(e,t){const n=Object.create(null),s=e.slots;for(let e=0;e<s.length;e++){const i=s[e],r=t[e];if(void 0!==i.literal){if(!st(r)||r.value!==i.literal)return null;continue}if(void 0!==i.token){if(r.s!==i.token)return null;continue}const o=n[i.name];if(void 0!==o){if(o.s!==r.s)return null}else n[i.name]=r}return n}function ms(e,t){for(const n of e.when){const e=t[n.slot];if(void 0===e)return!1;if(!n.fn(e,...n.args))return!1}for(const n of e.require){const e=n.args.map(e=>void 0!==t[e]?t[e]:e);if(!n.fn(...e))return!1}return!0}function gs(e,t){return t.rule.priority-e.rule.priority||t.rule.depth-e.rule.depth}function vs(e,t){const n=[];if(0===t.maxDepth)return n;for(const{key:s,slots:i}of function(e,t){const n=qn(e,t),s=[];for(const e of n)e.key!==wn&&s.push(e);return s}(e,t.maxDepth)){const e=t.candidates(s);if(e)for(const t of e){const e=ds(t,i);e&&(ms(t.rule,e)&&n.push({rule:t.rule,binding:t,key:s,bound:e}))}}return n.sort(gs)}function bs(e,t){switch(e.kind){case"slot":{const n=t[e.name];if(!n)throw new Error(`output references unbound slot "${e.name}"`);return n}case"const":return e.node;case"op":return nt(e.op,e.args.map(e=>bs(e,t)));default:throw new Error(`bad output template: ${JSON.stringify(e)}`)}}const ys=4e5,ws=()=>new ft("a number too large to approximate"),xs=e=>e<0n?-e:e;class ks{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,t){return e*t/this.S}div(e,t){if(0n===t)throw new ft("division by zero");return e*this.S/t}sqrt(e){if(e<0n)throw new ft("the square root of a negative number is not real");return wt(e*this.S,2)}series(e,t){let n=0n,s=e;for(let e=1;0n!==s;e++)if(n+=s,s=t(s,e),e>1e5)throw new ft("a series did not converge");return n}atanhInv(e){const t=BigInt(e),n=t*t;let s=this.S/t,i=0n;for(let e=1n;0n!==s;e+=2n)i+=s/e,s/=n;return i}atanInv(e){const t=BigInt(e),n=t*t;let s=this.S/t,i=0n;for(let e=1n,t=1n;0n!==s;e+=2n,t=-t)i+=t*s/e,s/=n;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,t){return this.cache.has(e)||this.cache.set(e,t()),this.cache.get(e)}exp(e){const t=(e+(e>=0n?this.ln2/2n:-this.ln2/2n))/this.ln2;if(t>BigInt(ys))throw ws();if(t<-BigInt(ys))return 0n;const n=e-t*this.ln2,s=this.series(this.S,(e,t)=>e*n/this.S/BigInt(t));return t>=0n?s<<t:s>>-t}ln(e){if(e<=0n)throw new ft("the log of a number that is not positive is not real");let t=0n,n=e;for(;n>=this.S;)n>>=1n,t++;for(;n<this.S/2n;)n<<=1n,t--;const s=this.div(n-this.S,n+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+t*this.ln2}sin(e){const t=2n*this.pi;let n=e%t;n>this.pi&&(n-=t),n<-this.pi&&(n+=t);const s=this.mul(n,n);return this.series(n,(e,t)=>-e*s/this.S/BigInt(2*t*(2*t+1)))}cos(e){return this.sin(e+this.pi/2n)}atan(e){if(xs(e)>this.S){const t=this.pi/2n;return(e>0n?t:-t)-this.atan(this.div(this.S,e))}let t=e;for(let e=0;e<2;e++)t=this.div(t,this.S+this.sqrt(this.S+this.mul(t,t)));const n=this.mul(t,t);let s=t,i=0n;for(let e=1n,t=1n;0n!==s;e+=2n,t=-t)i+=t*s/e,s=this.mul(s,n);return 4n*i}asin(e){if(xs(e)>this.S)throw new ft("arcsin of a number beyond ±1 is not real");return xs(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 qs(e,t,n){if(n>0n)return e.atan(e.div(t,n));if(n<0n)return e.atan(e.div(t,n))+(t>=0n?e.pi:-e.pi);if(0n===t)throw new ft("the argument of 0 is undefined");return t>0n?e.pi/2n:-e.pi/2n}const $s={add:(e,t)=>[e[0]+t[0],e[1]+t[1]],sub:(e,t)=>[e[0]-t[0],e[1]-t[1]],mul:(e,t,n)=>[e.mul(t[0],n[0])-e.mul(t[1],n[1]),e.mul(t[0],n[1])+e.mul(t[1],n[0])],div(e,t,n){const s=e.mul(n[0],n[0])+e.mul(n[1],n[1]);if(0n===s)throw new ft("division by zero");return[e.div(e.mul(t[0],n[0])+e.mul(t[1],n[1]),s),e.div(e.mul(t[1],n[0])-e.mul(t[0],n[1]),s)]},abs:(e,t)=>e.sqrt(e.mul(t[0],t[0])+e.mul(t[1],t[1])),exp(e,t){const n=e.exp(t[0]);return[e.mul(n,e.cos(t[1])),e.mul(n,e.sin(t[1]))]},ln(e,t){const n=$s.abs(e,t);if(0n===n)throw new ft("the log of 0 is undefined");return[e.ln(n),qs(e,t[1],t[0])]},pow(e,t,n,s){if(0n===t[0]&&0n===t[1])return[0n,0n];if(s&&s.isInteger){let n=s.n<0n?-s.n:s.n,i=[e.S,0n],r=t;for(;n>0n;)1n&n&&(i=$s.mul(e,i,r)),r=$s.mul(e,r,r),n>>=1n;return s.n<0n?$s.div(e,[e.S,0n],i):i}return $s.exp(e,$s.mul(e,n,$s.ln(e,t)))},sinh:(e,t)=>(e.exp(t)-e.exp(-t))/2n,cosh:(e,t)=>(e.exp(t)+e.exp(-t))/2n},Ss={sin:(e,[t,n])=>[e.mul(e.sin(t),$s.cosh(e,n)),e.mul(e.cos(t),$s.sinh(e,n))],cos:(e,[t,n])=>[e.mul(e.cos(t),$s.cosh(e,n)),-e.mul(e.sin(t),$s.sinh(e,n))],tan:(e,t)=>$s.div(e,Ss.sin(e,t),Ss.cos(e,t)),ln:(e,t)=>$s.ln(e,t),sqrt:(e,t)=>$s.exp(e,$s.mul(e,[e.S/2n,0n],$s.ln(e,t))),sinh:(e,[t,n])=>[e.mul($s.sinh(e,t),e.cos(n)),e.mul($s.cosh(e,t),e.sin(n))],cosh:(e,[t,n])=>[e.mul($s.cosh(e,t),e.cos(n)),e.mul($s.sinh(e,t),e.sin(n))]},Ms=e=>({q:e}),Os=([e,t])=>0n===t?{f:e}:{z:[e,t]};function As(e,t,n){const s=e=>((e,t)=>t.z??[Ns(e,t),0n])(n,t[e]);switch(e.op){case"+":return Os($s.add(s(0),s(1)));case"-":return Os($s.sub(s(0),s(1)));case"neg":return Os([-s(0)[0],-s(0)[1]]);case"*":return Os($s.mul(n,s(0),s(1)));case"/":return Os($s.div(n,s(0),s(1)));case"^":return Os($s.pow(n,s(0),s(1),t[1].q));case"sqrt":return Os(Ss.sqrt(n,s(0)));case"root":return Os($s.pow(n,s(1),$s.div(n,[n.S,0n],s(0)),t[0].q?.inv()));case"abs":return{f:$s.abs(n,s(0))};case"arg":return{f:qs(n,s(0)[1],s(0)[0])};case"re":return{f:s(0)[0]};case"im":return{f:s(0)[1]};case"conj":return Os([s(0)[0],-s(0)[1]]);case"log":return Os($s.div(n,$s.ln(n,s(1)),$s.ln(n,s(0))));default:{const i=Ss[e.op];if(!i||1!==t.length)throw new ft(`no complex value for ${e.op}`);return Os(i(n,s(0)))}}}function Ns(e,t){return t.q?e.fromQ(t.q):t.f}const Es={sin:(e,t)=>e.sin(t),cos:(e,t)=>e.cos(t),tan:(e,t)=>e.div(e.sin(t),e.cos(t)),sec:(e,t)=>e.div(e.S,e.cos(t)),csc:(e,t)=>e.div(e.S,e.sin(t)),cot:(e,t)=>e.div(e.cos(t),e.sin(t)),arcsin:(e,t)=>e.asin(t),arccos:(e,t)=>e.pi/2n-e.asin(t),arctan:(e,t)=>e.atan(t),arcsec:(e,t)=>{if(xs(t)<e.S)throw new ft("arcsec of a number between -1 and 1 is not real");return e.pi/2n-e.asin(e.div(e.S,t))},arccsc:(e,t)=>{if(xs(t)<e.S)throw new ft("arccsc of a number between -1 and 1 is not real");return e.asin(e.div(e.S,t))},arccot:(e,t)=>e.pi/2n-e.atan(t),sinh:(e,t)=>(e.exp(t)-e.exp(-t))/2n,cosh:(e,t)=>(e.exp(t)+e.exp(-t))/2n,tanh:(e,t)=>{const n=e.exp(t),s=e.exp(-t);return e.div(n-s,n+s)},arcsinh:(e,t)=>e.ln(t+e.sqrt(e.mul(t,t)+e.S)),arccosh:(e,t)=>{if(t<e.S)throw new ft("arccosh of a number below 1 is not real");return e.ln(t+e.sqrt(e.mul(t,t)-e.S))},arctanh:(e,t)=>{if(xs(t)>=e.S)throw new ft("arctanh of a number beyond ±1 is not real");return e.ln(e.div(e.S+t,e.S-t))/2n},ln:(e,t)=>e.ln(t),loglog:(e,t)=>e.ln(e.ln(t)),logloglog:(e,t)=>e.ln(e.ln(e.ln(t))),expm1:(e,t)=>e.exp(t)-e.S};function Is(e,t,n){if("num"===e.type)return Ms(yt(e.token));if("sym"===e.type){if("pi"===e.token||"π"===e.token)return{f:t.pi};if("e"===e.token)return{f:t.e};if("i"===e.token&&$t.complex)return{z:[0n,t.S]};if(n&&e.token in n){const t=n[e.token],s="number"==typeof t||"string"==typeof t||"bigint"==typeof t?yt(String(t)):null;if(!s)throw new ft(`the value of ${e.token} is not a number`);return Ms(s)}throw new ft(`${e.token} has no value`)}$t.complex&&e.op.startsWith("\\:")&&tn[e.op.slice(2)]&&(e=nt(tn[e.op.slice(2)],e.args));const s=e.args.map(e=>Is(e,t,n));if(s.some(e=>e.z)||["re","im","conj","arg"].includes(e.op)||function(e,t){if(!$t.complex)return!1;const n=e=>e.q?e.q.sign<0:void 0!==e.f&&e.f<0n;return"sqrt"===e.op||"ln"===e.op||"log"===e.op?n(t["log"===e.op?1:0])||"log"===e.op&&n(t[0]):"^"===e.op?n(t[0])&&!(t[1].q&&t[1].q.d%2n==1n):"root"===e.op&&n(t[1])&&!(t[0].q&&t[0].q.isInteger&&t[0].q.n%2n==1n)}(e,s))return As(e,s,t);const i=s.every(e=>e.q),r=e=>Ns(t,s[e]);switch(e.op){case"+":return i?Ms(s[0].q.add(s[1].q)):{f:r(0)+r(1)};case"-":return i?Ms(s[0].q.sub(s[1].q)):{f:r(0)-r(1)};case"neg":return s[0].q?Ms(s[0].q.neg()):{f:-s[0].f};case"*":return i?Ms(s[0].q.mul(s[1].q)):{f:t.mul(r(0),r(1))};case"/":return i?Ms(s[0].q.div(s[1].q)):{f:t.div(r(0),r(1))};case"^":return Ls(t,s[0],s[1]);case"sqrt":return Ls(t,s[0],Ms(bt.HALF));case"root":return Ls(t,s[1],s[0].q?Ms(s[0].q.inv()):{f:t.div(t.S,s[0].f)});case"abs":return s[0].q?Ms(s[0].q.abs()):{f:xs(s[0].f)};case"floor":return Ms(s[0].q?s[0].q.floor():new bt(Ts(s[0].f,t.S)));case"ceil":return Ms(s[0].q?s[0].q.ceil():new bt(-Ts(-s[0].f,t.S)));case"log":return{f:t.div(t.ln(r(1)),t.ln(r(0)))};case"atan2":return{f:qs(t,r(0),r(1))};case"max":case"min":if(!s.length)throw new ft(`${e.op} of nothing`);return i?Ms(s.map(e=>e.q).reduce((t,n)=>("max"===e.op?n.sub(t).sign>0:n.sub(t).sign<0)?n:t)):{f:s.map((e,t)=>r(t)).reduce((t,n)=>"max"===e.op?n>t?n:t:n<t?n:t)};case"sum":return i?Ms(s.reduce((e,t)=>e.add(t.q),bt.ZERO)):{f:s.reduce((e,t,n)=>e+r(n),0n)};case"prod":return i?Ms(s.reduce((e,t)=>e.mul(t.q),bt.ONE)):{f:s.reduce((e,n,s)=>t.mul(e,r(s)),t.S)};case"mean":if(!s.length)throw new ft("mean of nothing");return i?Ms(s.reduce((e,t)=>e.add(t.q),bt.ZERO).div(new bt(BigInt(s.length)))):{f:s.reduce((e,t,n)=>e+r(n),0n)/BigInt(s.length)};case"mod":{if(i){if(s[1].q.isZero)throw new ft("mod 0 is undefined");return Ms(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 ft("mod 0 is undefined");return{f:r(0)-t.mul(e,Ts(t.div(r(0),e),t.S)*t.S)}}case"round":{if(!s[1].q?.isInteger)throw new ft("round needs a whole number of places");const e=10n**xs(s[1].q.n),n=s[0].q??new bt(r(0),t.S),i=s[1].q.sign>=0,o=(i?n.mul(new bt(e)):n.div(new bt(e))).add(bt.HALF).floor();return Ms(i?o.div(new bt(e)):o.mul(new bt(e)))}case"!":{if(!s[0].q?.isInteger||s[0].q.sign<0)throw new ft("factorial is only worked out for whole numbers");let e=1n;for(let t=2n;t<=s[0].q.n;t++)if(e*=t,0n==(255n&t)&&gt(e)>ys)throw ws();return Ms(new bt(e))}default:{const n=Es[e.op];if(!n||1!==s.length)throw new ft(`no numeric value for ${e.op}`);return{f:n(t,r(0))}}}}const Ts=(e,t)=>{const n=e/t;return e<0n&&n*t!==e?n-1n:n};function Ls(e,t,n){if(n.q&&n.q.isInteger){if(t.q)return Ms(t.q.pow(n.q.n));let s=n.q.n;const i=s<0n;i&&(s=-s);let r=e.S,o=t.f;for(;s>0n;){if(1n&s&&(r=e.mul(r,o)),o=e.mul(o,o),gt(r)>ys+4*e.P||gt(o)>8e5){if(i)return{f:0n};throw ws()}s>>=1n}return{f:i?e.div(e.S,r):r}}const s=Ns(e,t);if(0n===s){if(n.q?n.q.sign>0:n.f>0n)return Ms(bt.ZERO);throw new ft("0 to a power that is not positive is undefined")}if(s<0n){if(n.q&&n.q.d%2n==1n){const t=Ls(e,{f:-s},n).f;return{f:n.q.n%2n==0n?t:-t}}throw new ft("a negative number to a fractional power is not real")}if(n.q&&1n===xs(n.q.n)&&n.q.d<=64n){const t=wt(s*e.S**(n.q.d-1n),Number(n.q.d));return{f:n.q.n<0n?e.div(e.S,t):t}}return{f:e.exp(e.mul(Ns(e,n),e.ln(s)))}}function js(e,t,n){const s=e<0n?"-":"",i=xs(e);if(0n===i)return{sign:"",digits:"0",point:1};const r=i.toString(),o=r.length-t.P;let a=r.slice(0,n);r.length>n&&r[n]>="5"&&(a=(BigInt(a)+1n).toString());let u=o;return a.length>n&&(a=a.slice(0,n),u++),{sign:s,digits:a.replace(/0+$/,"")||"0",point:u}}function zs({sign:e,digits:t,point:n}){if("0"===t)return"0";if(n>21||n<-6){return`${e}${t.length>1?`${t[0]}.${t.slice(1)}`:t}e${n-1}`}return n<=0?`${e}0.${"0".repeat(-n)}${t}`:n>=t.length?`${e}${t}${"0".repeat(n-t.length)}`:`${e}${t.slice(0,n)}.${t.slice(n)}`}function Cs(e){let t=0n,n=0n,s=e.d;for(;s%2n==0n;)s/=2n,t++;for(;s%5n==0n;)s/=5n,n++;const i=t>n?t:n;let r=xs(e.n)*10n**i/e.d;if(0n===r)return 1;for(;r%10n==0n;)r/=10n;return r.toString().length}function Zs(e){let t=e.d;for(;t%2n==0n;)t/=2n;for(;t%5n==0n;)t/=5n;return 1n===t}function Fs(e){const t=/^(-?[\d.]+)e(-?\d+)$/.exec(e);return t?nt("*",[Xe(t[1]),nt("^",[Xe("10"),Xe(t[2])])]):Xe(e)}function Bs(e,{digits:t=15,scope:n}={}){if(!Number.isInteger(t)||t<1||t>1e5)throw new ft("digits must be a whole number from 1 to 100000");let s=t+25,i=null;for(let r=0;r<4;r++){const o=new ks(s),a=Is(e,o,n);if(a.z){const e=Ps(a.z,o,t);if(e.retry&&r<3){s+=e.retry;continue}return void 0===e.real?e:Ds(e.real,o,t,null)}if(a.q&&a.q.isInteger&&xs(a.q.n).toString().length<=t)return{text:a.q.n.toString(),node:Xe(a.q.n.toString()),number:Number(a.q.n),re:Number(a.q.n),im:0,exact:!0};const u=Ns(o,a);if(0n===u&&(!a.q||!a.q.isZero)&&r<3){i=null,s*=4;continue}const l=js(u,o,t);if(i&&l.point<-10&&i.point-l.point>=(s-i.P)/2)return{text:"0",node:Xe("0"),number:0,re:0,im:0,exact:!1};if(!(l.point<-10&&r<3)||i&&i.point===l.point)return Ds(u,o,t,a.q);i={point:l.point,P:s},s+=10-l.point}throw new ft("could not approximate")}function Ds(e,t,n,s){const i=zs(js(e,t,n));return{text:i,node:Fs(i),number:Number(i),re:Number(i),im:0,exact:Boolean(s)&&Zs(s)&&Cs(s)<=n}}function Ps([e,t],n,s){const i=10n**BigInt(Math.max(0,n.P-s-12)),r=e=>xs(e)>i;if(!r(t))return{real:e};const o=js(t,n,s);if(o.point<-10&&r(t))return{retry:10-o.point};const a=zs(o),u="1"===a?"i":"-1"===a?"-i":`${a}i`,l="1"===a?Ge("i"):nt("*",[Fs(a.replace(/^-/,"")),Ge("i")]);if(!r(e))return{text:u,node:a.startsWith("-")?nt("neg",[l]):l,number:NaN,re:0,im:Number(a),exact:!1};const c=zs(js(e,n,s)),p=a.startsWith("-"),h="1"===a.replace(/^-/,"")?Ge("i"):nt("*",[Fs(a.replace(/^-/,"")),Ge("i")]);return{text:`${c} ${p?"-":"+"} ${u.replace(/^-/,"")}`,node:nt(p?"-":"+",[Fs(c),h]),number:NaN,re:Number(c),im:Number(a),exact:!1}}function Rs(e,t={}){const n=e=>(e=>0===vn(e).size)(e)?"num"===e.type&&/^-?\d+$/.test(e.token)?e:Bs(e,t).node:it(e)?nt(e.op,e.args.map(n)):e;return n(e)}const _s={variable:null},Vs=(e,t)=>null!==t&&vn(e).has(t);function Ws(e){if("num"===e.type)return yt(e.token);if(it(e)&&"/"===e.op&&e.args.every(e=>"num"===e.type)){const t=yt(e.args[0].token),n=yt(e.args[1].token);return t&&n&&!n.isZero?t.div(n):null}return null}const Us=e=>0===vn(e).size;function Hs(e,t,n){const s=function(e){const t=ln(e);return"num"===t.k?t.q.isZero?t.q:null:"atom"===t.k&&"sym"===t.node.type&&"pi"===t.node.token?yt("1"):"mul"===t.k&&1===t.fs.length&&"atom"===t.fs[0].b.k&&"pi"===t.fs[0].b.node.token&&"num"===t.fs[0].e.k&&t.fs[0].e.q.isOne?t.c:null}(e);if(!s)return!1;const[i,r="1"]=String(t).split("/");return n(s.compare(yt(i).div(yt(r))))}function Ks(e){if(!Us(e))return NaN;try{const{number:t}=Bs(e,{digits:30});return Math.sign(t)}catch{return NaN}}function Js(){In("hasVariable")||(Nn("hasVariable",e=>Vs(e,_s.variable),"mentions the variable being solved for"),Nn("freeOfVariable",e=>null!==_s.variable&&!Vs(e,_s.variable),"does not mention the variable being solved for"),Nn("isRational",e=>null!==Ws(e),"an exact number: 3, -2, 1/2"),Nn("isWhole",e=>Ws(e)?.isInteger??!1,"a whole number (any size)"),Nn("isEvenWhole",e=>{const t=Ws(e);return Boolean(t?.isInteger&&t.n%2n==0n)},"an even whole number"),Nn("isOddWhole",e=>{const t=Ws(e);return Boolean(t?.isInteger&&t.n%2n!=0n)},"an odd whole number"),Nn("isPositiveRational",e=>(Ws(e)?.sign??0)>0,"an exact number above 0"),Nn("isNegativeRational",e=>(Ws(e)?.sign??0)<0,"an exact number below 0"),Nn("isConstant",Us,"has no unknowns (numbers, π and e only)"),Nn("notOne",e=>{const t=Ws(e);return!t||!t.isOne},"anything except the number 1"),Nn("notMinusOne",e=>{const t=Ws(e);return!t||!t.equals(yt("-1"))},"anything except the number -1"),Nn("hasMinusSign",e=>function(e){const t=ln(e);return"num"===t.k?t.q.sign<0:"mul"===t.k&&t.c.sign<0}(e),"written with a leading minus: -x, -2x, -π/6"),Nn("piMultipleAtLeast",(e,t)=>Hs(e,t,e=>e>=0),"a multiple of π, at least k·π"),Nn("piMultipleAbove",(e,t)=>Hs(e,t,e=>e>0),"a multiple of π, above k·π"),Nn("piMultipleBelow",(e,t)=>Hs(e,t,e=>e<0),"a multiple of π, below k·π"),Nn("piMultipleAtMost",(e,t)=>Hs(e,t,e=>e<=0),"a multiple of π, at most k·π"),Nn("isPositiveConstant",e=>Ks(e)>0,"no unknowns, and above 0 (e, π, √2, 3)"),Nn("isNegativeConstant",e=>Ks(e)<0,"no unknowns, and below 0"),Nn("hasImaginaryPart",e=>{if(!$t.complex)return!1;const t=Gt(ln(e));return Boolean(t)&&!("num"===t.im.k&&t.im.q.isZero)},"complex mode: has a nonzero imaginary part (unknowns count as real)"),Nn("isSymbolNode",e=>"sym"===e.type&&!qt.has(e.token),"a single unknown such as x"))}function Qs(e){const t=new Map;for(const n of e){const e=n.id??n.name;if(!e)throw new Error(`a rule needs an id (pattern ${n.pattern})`);t.set(String(e),{...t.get(String(e))??{},...n})}const n=[...t.values()].map(e=>{const t={...e};try{void 0!==t.pattern&&(t.pattern=function(e){const t=rt(e),n=e=>"num"===e.type||("sym"===e.type?e.token.startsWith("="):e.args.every(n)),s=e=>"sym"===e.type?Ge(e.token.slice(1)):"num"===e.type?e:nt(e.op,e.args.map(s)),i=e=>"sym"===e.type?Ge(`=${e.token}`):"num"===e.type?e:nt(e.op,e.args.map(i)),r=e=>"op"!==e.type?e:n(e)?i(cn(s(e))):nt(e.op,e.args.map(r));return r(t).s}(String(t.pattern)))}catch(e){throw new Error(`rule "${t.id}": bad pattern "${t.pattern}": ${e.message}`)}return"hidden"===t.step&&(t.tags=[...t.tags??[],"hidden"]),t});return fs.fromSpecs(n,{strict:!0})}function Ys(e,t,n,s){return e.explain?e.explain.replace(/\{(\w+)\}/g,(e,i)=>"result"===i?n?s(n):e:t[i]?s(t[i]):e).trim():""}const Gs=e=>it(e)&&("+"===e.op||"-"===e.op),Xs=e=>it(e)&&("*"===e.op||"/"===e.op);function*ei(e,t,{order:n="pre"}={}){for(const s of function(e,t,{order:n="post"}={}){const s=[];for(const{node:i,path:r}of pt(e,n))for(const e of vs(i,t))s.push({...e,node:i,path:r});return s}(e,t,{order:n})){const t=bs(s.rule.outputTemplate,s.bound);yield{rule:s.rule,bound:s.bound,path:s.path,before:s.node,after:t,next:()=>cn(ht(e,s.path,t))}}for(const{node:s,path:i}of pt(e,n)){const n=Gs(s);if(!n&&!Xs(s))continue;const r=n?bn(ln(s)):yn(ln(s));if(r.length<3)continue;const o=n?_t:Wt;for(let n=0;n<r.length;n++)for(let s=n+1;s<r.length;s++){const a=dn(o([r[n],r[s]]));for(const u of vs(a,t)){const t=bs(u.rule.outputTemplate,u.bound),l=r.filter((e,t)=>t!==n&&t!==s);yield{rule:u.rule,bound:u.bound,path:i,before:a,after:t,next:()=>cn(ht(e,i,dn(o([ln(t),...l]))))}}}}}function ti(e,t,{format:n,order:s="pre",maxSteps:i=200,variable:r=null}={}){const o=_s.variable;_s.variable=r;try{let r=cn(e);const o=new Set([r.s]),a=[];for(let e=0;e<i;e++){let e=null;for(const n of ei(r,t,{order:s})){const t=n.next();if(t.s!==r.s&&!o.has(t.s)){e={c:n,next:t};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:Ys(i.rule,i.bound,cn(i.after),n)}),r=u,o.add(r.s)}return{node:r,steps:a}}finally{_s.variable=o}}const ni={full:[],normal:["hidden"],brief:["hidden","tidy","identity","value","split","base","arithmetic"]},si=(e,t)=>"all"===t||"*"===t||Array.isArray(t)&&t.some(t=>t===e.id||e.tags?.includes(t));function ii(e){if(!1===e)return null;if(void 0===e||!0===e)return{show:"all",hide:ni.normal,explain:!0};if("string"==typeof e){if(!ni[e])throw new Error(`steps: "${e}" is not one of ${Object.keys(ni).join(", ")}`);return{show:"all",hide:ni[e],explain:!0}}const t=e.detail??"normal";if(!ni[t])throw new Error(`steps.detail: "${t}" is not one of ${Object.keys(ni).join(", ")}`);return{show:e.show??"all",hide:[...ni[t],...e.hide??[]],explain:e.explain??!0}}function ri(e,t){if(!t)return[];const n=[];let s=null;for(const i of e){if(!(si(i,t.show)&&!si(i,t.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===t.explain||!1!==t.explain&&si(i,t.explain)||delete e.explanation,n.push(e)}if(s&&n.length){const t=n[n.length-1];t.to=e[e.length-1].to,t.also=[...t.also??[],...s.ids]}return n}const oi=At(bt.ONE),ai=(e,t)=>"atom"===e.k&&"sym"===e.node.type&&e.node.token===t;function ui(e){switch(e.k){case"num":default:return e;case"atom":return"op"===e.node.type?an(e.node.op,e.node.args.map(e=>ui(ln(e)))):e;case"add":return _t(bn(e).map(ui));case"mul":{let t=[At(e.c)];for(const n of e.fs){const e=ui(n.b);if("add"===e.k&&Tt(n.e)&&n.e.q.isInteger&&n.e.q.sign>0&&n.e.q.n<=BigInt(60))for(let s=0n;s<n.e.q.n;s++)t=li(t,bn(e));else t=li(t,[Ht(e,n.e)])}return _t(t)}}}function li(e,t){const n=[];for(const s of e)for(const e of t)n.push(Wt([s,e]));return bn(_t(n))}function ci(e,t){const n=new Map;for(const s of bn(ui(e))){const{coef:e,rest:i}=Rt(s);let r=0;const o=[At(e)];for(const e of i?yn(i):[]){const{b:n,e:s}="mul"===e.k&&1===e.fs.length&&e.c.isOne?e.fs[0]:{b:e,e:oi};if(ai(n,t)){if(!Tt(s)||!s.q.isInteger||s.q.sign<0)return null;r+=Number(s.q.n)}else{if(pi(n,t)||pi(s,t))return null;o.push(e)}}n.set(r,_t([n.get(r)??At(bt.ZERO),Wt(o)]))}for(const[e,t]of n)Tt(t)&&t.q.isZero&&n.delete(e);return n}const pi=(e,t)=>vn(dn(e)).has(t);function hi(e){if(!e)return null;const t=Math.max(0,...e.keys());if(t>256)return null;const n=[];for(let s=0;s<=t;s++){const t=e.get(s)??At(bt.ZERO);if(!Tt(t))return null;n.push(t.q)}return n}function fi(e,t){const n=ln(Ge(t));return _t(e.map((e,t)=>Wt([At(e),Ut(n,At(bt.of(t)))])))}const di=e=>{const t=e.slice();for(;t.length>1&&t[t.length-1].isZero;)t.pop();return t},mi=(e,t)=>e.reduceRight((e,n)=>e.mul(t).add(n),bt.ZERO);function gi(e,t){const n=e.length-1,s=new Array(n);let i=bt.ZERO;for(let r=n;r>=1;r--)i=e[r].add(i.mul(t)),s[r-1]=i;return s}function vi(e){if(0n===(e=(e=>e<0n?-e:e)(e)))return null;if(e>10n**14n)return null;const t=[];let n=e;for(let e=2n;e*e<=n;e+=2n===e?1n:2n){if(n%e)continue;let s=0;for(;n%e===0n;)n/=e,s++;t.push([e,s])}n>1n&&t.push([n,1]);let s=[1n];for(const[e,n]of t){const t=[];for(const i of s)for(let s=0,r=1n;s<=n;s++,r*=e)t.push(i*r);if(s=t,s.length>2e4)return null}return s.sort((e,t)=>e<t?-1:e>t?1:0)}function bi(e){let t=di(e);const n=[];for(;t.length>1&&t[0].isZero;)n.push(bt.ZERO),t=t.slice(1);if(t.length<=1)return{roots:n,rest:t};const s=t.reduce((e,t)=>e*t.d/vt(e,t.d),1n),i=t.map(e=>e.n*s/e.d),r=vi(i[0]),o=vi(i[i.length-1]);if(!r||!o)return{roots:n,rest:t};const a=new Map;for(const e of r)for(const t of o)for(const n of[1n,-1n]){const s=new bt(n*e,t);a.set(s.toString(),s)}const u=[...a.values()].sort((e,t)=>e.compare(t));for(const e of u)for(;t.length>1&&mi(t,e).isZero;)n.push(e),t=gi(t,e);return{roots:n.sort((e,t)=>e.compare(t)),rest:t}}function yi(e,t){const n=di(t);let s=di(e);const i=n[n.length-1];if(i.isZero)throw new ft("division by the zero polynomial");const r=new Array(Math.max(1,s.length-n.length+1)).fill(bt.ZERO);for(;s.length>=n.length&&(1!==s.length||!s[0].isZero);){const e=s.length-n.length,t=s[s.length-1].div(i);if(r[e]=t,s=di(s.map((s,i)=>i>=e&&i-e<n.length?s.sub(t.mul(n[i-e])):s)),s.length-1<e+n.length-1&&s[s.length-1].isZero)break;if(s.length<n.length)break}return{q:di(r),r:s}}function wi(e){if("num"===e.k)return{coef:e.q,factors:[],notes:[]};if("atom"===e.k)return{coef:bt.ONE,factors:[{base:e,exp:oi}],notes:[]};if("mul"===e.k){let t=e.c;const n=[],s=[];for(const i of e.fs)if("add"===i.b.k&&Tt(i.e)&&i.e.q.isInteger){const e=wi(i.b);t=t.mul(e.coef.pow(i.e.q.n));for(const t of e.factors)n.push({base:t.base,exp:Wt([t.exp,i.e])});s.push(...e.notes)}else n.push({base:i.b,exp:i.e});return xi(t,n,s)}return function(e){const t=bn(e),n=[],s=t.map(e=>{const{coef:t,rest:n}=Rt(e);return{coef:t,fs:n?yn(n).map(qi):[]}}),i=s.reduce((e,t)=>({n:vt(e.n,t.coef.n),d:e.d*t.coef.d/vt(e.d,t.coef.d)}),{n:0n,d:1n});let r=new bt(i.n||1n,i.d);ki(e)<0&&(r=r.neg());const o=[];for(const e of s[0].fs){if(!Tt(e.e)||e.e.q.sign<=0)continue;let t=e.e.q;const n=zt(e.b);let i=!0;for(const e of s.slice(1)){const s=e.fs.find(e=>zt(e.b)===n&&Tt(e.e)&&e.e.q.sign>0);if(!s){i=!1;break}s.e.q.compare(t)<0&&(t=s.e.q)}i&&o.push({base:e.b,exp:At(t)})}let a=e;if(!r.isOne||o.length){const e=Wt([At(r),...o.map(e=>Ht(e.base,e.exp))]);a=_t(t.map(t=>Wt([t,Ut(e,At(bt.MINUS_ONE))]))),n.push({id:"factor.common",values:{common:e}})}const u="add"===a.k?function(e,t){const n=[...$i(e)];for(const s of n){const i=hi(ci(e,s));if(!i||i.length<3)continue;if(1!==n.length)break;const{roots:r,rest:o}=bi(i);if(!r.length)break;const a=[];let u=o[o.length-1]??bt.ONE;const l=o.map(e=>e.div(u)),c=[...r].sort((e,t)=>e.abs().compare(t.abs())||t.sign-e.sign);for(const e of c){const n=fi([new bt(-e.n),new bt(e.d)],s);a.push({base:n,exp:oi}),u=u.div(new bt(e.d)),t.push({id:"factor.root",values:{root:At(e),factor:n}})}if(l.length>1){const e=l.reduce((e,t)=>e*t.d/vt(e,t.d),1n),t=l.map(t=>t.mul(new bt(e))),n=t.reduce((e,t)=>vt(e,t.n),0n)||1n;u=u.mul(new bt(n,e)),a.push({base:fi(t.map(e=>e.div(new bt(n))),s),exp:oi})}return xi(u,a,[])}const s=bn(e);if(2===s.length){const[e,n]=s;for(const s of[2,3]){const i=Si(e,s),r=Si(nn(n),s),o=3===s?Si(n,s):null;if(i&&r&&2===s){t.push({id:"factor.squares",values:{a:i,b:r}});const e=wi(_t([i,nn(r)])),n=wi(_t([i,r]));return xi(e.coef.mul(n.coef),[...e.factors,...n.factors],[...e.notes,...n.notes])}if(3===s&&i&&(r||o)){const e=r??o,n=r?-1:1;t.push({id:n<0?"factor.cubes-difference":"factor.cubes-sum",values:{a:i,b:e}});const s=_t(n<0?[i,nn(e)]:[i,e]),a=_t([Ut(i,At(bt.of(2))),n<0?Wt([i,e]):nn(Wt([i,e])),Ut(e,At(bt.of(2)))]),u=wi(s);return xi(u.coef,[...u.factors,{base:a,exp:oi}],u.notes)}}}return{coef:bt.ONE,factors:[{base:e,exp:oi}],notes:[]}}(a,n):wi(a);return xi(r.mul(u.coef),[...o,...u.factors],[...n,...u.notes.filter(e=>!n.includes(e))])}(e)}function xi(e,t,n){const s=new Map;for(const e of t){const t=zt(e.base),n=s.get(t);n?n.exp=_t([n.exp,e.exp]):s.set(t,{...e})}return{coef:e,factors:[...s.values()].filter(e=>!(Tt(e.exp)&&e.exp.q.isZero)),notes:n}}const ki=e=>Rt(bn(e)[0]).coef.sign;const qi=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length?{b:e.fs[0].b,e:e.fs[0].e}:{b:e,e:oi},$i=e=>vn(dn(e));function Si(e,t){const{coef:n,rest:s}=Rt(e);if(n.sign<0)return null;const i=function(e,t){const n=e=>{if(e<0n)return null;let n=0n,s=1n;for(;s**BigInt(t)<=e;)s*=2n;for(;n<s-1n;){const i=(n+s)/2n;i**BigInt(t)<=e?n=i:s=i}return n**BigInt(t)===e?n:null},s=n(e.n),i=n(e.d);return null!==s&&null!==i?new bt(s,i):null}(n,t);if(!i)return null;const r=[At(i)];for(const e of s?yn(s).map(qi):[]){if(!Tt(e.e))return null;const n=e.e.q.div(bt.of(t));if(!n.isInteger)return null;r.push(Ht(e.b,At(n)))}return Wt(r)}function Mi({coef:e,factors:t}){const n=[],s=[];for(const e of t){const t=Tt(e.exp)&&e.exp.q.sign<0,i=t?At(e.exp.q.neg()):e.exp,r=dn(Ht(e.base,i));(t?s:n).push(r)}const i=e=>e.reduce((e,t)=>e?nt("*",[e,t]):t,null),r=e.n<0n?-e.n:e.n;let o=n.length?i(1n===r?n:[dn(At(new bt(r))),...n]):dn(At(new bt(r)));return e.n<0n&&(o=nt("neg",[o])),1n!==e.d&&s.unshift(dn(At(new bt(e.d)))),s.length?nt("/",[o,i(s)]):o}function Oi(e){if("mul"!==e.k)return{num:e,den:oi};const t=[At(new bt(e.c.n))],n=[At(new bt(e.c.d))];for(const s of e.fs)Tt(s.e)&&s.e.q.sign<0?n.push(Ht(s.b,At(s.e.q.neg()))):t.push(Ht(s.b,s.e));return{num:Wt(t),den:Wt(n)}}function Ai(e){if("add"!==e.k)return Oi(e);const t=bn(e).map(Oi),n=new Map;let s=1n;for(const e of t){const{coef:t,rest:i}=Rt(e.den);s=s*t.n/vt(s,t.n);for(const e of i?yn(i).map(qi):[]){const t=zt(e.b),s=n.get(t);(!s||Tt(e.e)&&Tt(s.e)&&e.e.q.compare(s.e.q)>0)&&n.set(t,e)}}const i=Wt([At(new bt(s)),...[...n.values()].map(e=>Ht(e.b,e.e))]);if(Tt(i)&&i.q.isOne)return{num:e,den:oi};return{num:ui(_t(t.map(e=>Wt([e.num,i,Ut(e.den,At(bt.MINUS_ONE))])))),den:i}}function Ni(e){const{num:t,den:n}=Ai(e);if(Tt(n)&&n.q.isOne)return null;const s=wi(t),i=wi(n),r=new Set(s.factors.map(e=>zt(e.base))),o=i.factors.filter(e=>r.has(zt(e.base))),a=[...s.factors,...i.factors.map(e=>({base:e.base,exp:nn(e.exp)}))];return{...xi(s.coef.div(i.coef),a,[...s.notes,...i.notes]),canceled:o.map(e=>e.base)}}const Ei=(e,t)=>nt("=",[e,t]),Ii=cn(nt("+",[Ge("x"),nt("neg",[Ge("x")])])),Ti=e=>it(e)&&"="===e.op;function Li(e,t,n,s={}){const i=[],r=(t,n,s,r,o,a={})=>i.push(e.step(t,n,s,r,o,a));r.raw=e=>i.push(e);const o=Ti(t)?t:Ei(t,Ii),a=Ei(cn(o.args[0]),cn(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,Bi(e,a,n,s,r,u,l,0);const p=[],h=new Set;for(const t of u.map(t=>c.has(t)?t:(t=>ti(t,e.set.view("simplify"),{format:e.format}).node)(t))){const e=t.s;if(h.has(e))continue;h.add(e);const s=c.has(t)?null:Ci(o,n,t);s?r("solve.reject","Check the answer",["check"],Ei(Ge(n),t),Ei(Ge(n),t),{value:t,reason:s}):p.push(t)}return p.sort(ji),{solutions:p,unsolved:l,steps:i,always:l.some(e=>e.always)}}function ji(e,t){const n=zi(e),s=zi(t);return null===n||null===s?e.s<t.s?-1:1:(Math.abs(n.im)>0)-(Math.abs(s.im)>0)||n.re-s.re||n.im-s.im}function zi(e){if(vn(e).size)return null;try{const{re:t,im:n}=Bs(e,{digits:20});return{re:t,im:n}}catch{return null}}function Ci(e,t,n){const[s,i]=e.args,r=new Set([...vn(s),...vn(i),...vn(n)]);if(r.delete(t),r.size)return null;const o=e=>Zi(e,t,n);try{const e=Bs(o(s),{digits:40}),t=Bs(o(i),{digits:40}),n=Math.max(1,Math.hypot(e.re,e.im),Math.hypot(t.re,t.im));return Math.hypot(e.re-t.re,e.im-t.im)>1e-12*n?"it does not make the two sides equal":null}catch(e){return`the original equation has no value there (${e.message})`}}function Zi(e,t,n){return"sym"===e.type?e.token===t?n:e:it(e)?nt(e.op,e.args.map(e=>Zi(e,t,n))):e}const Fi=24;function Bi(e,t,n,s,i,r,o,a){if(a>Fi)return Ui(e,t,n,s,i,r,o);const u=function(e){const t=[],n=e=>{if(it(e)&&"|"===e.op)return void e.args.forEach(n);if(!Ti(e))return void t.push(e);const s=e.args[1],i=pt(s,"pre").find(({node:e})=>it(e)&&"pm"===e.op);if(!i)return void t.push(e);const r=i.node.args[0],o=cn(ht(s,i.path,r)),a=cn(ht(s,i.path,nt("neg",[r])));n(Ei(e.args[0],o)),a.s!==o.s&&n(Ei(e.args[0],a))};return n(e),t}(t);if(u.length>1){i("solve.split","Two cases",["split"],t,u.reduce((e,t)=>e?nt("|",[e,t]):t,null));for(const t of u)Bi(e,t,n,s,i,r,o,a+1);return}if(1===u.length&&u[0].s!==t.s)return Bi(e,u[0],n,s,i,r,o,a+1);const[l,c]=t.args;if("sym"===l.type&&l.token===n&&!pi(ln(c),n))return void r.push(c);const p=_t([ln(l),nn(ln(c))]);if(!pi(p,n))return Tt(p)&&p.q.isZero?(i("solve.always","Always true",["check"],t,t,{v:n}),void o.push(Object.assign(Object.create(t),{always:!0}))):void i("solve.never","No solution",["check"],t,t,{v:n});const h=bn(p).filter(e=>pi(e,n)),f=bn(p).filter(e=>!pi(e,n)),d=_t(h),m=nn(_t(f));if($t.complex){const u=ci(p,n);if(u&&[...u.values()].every(e=>!pi(e,n))&&Math.max(...u.keys())>=2){const l=Ei(dn(p),Ii);return l.s!==t.s&&i("solve.one-side","Everything on one side",["move"],t,l,{v:n}),Vi(e,p,u,n,s,i,r,o,a,l)}}if(1===h.length)return Di(e,t,d,m,n,s,i,r,o,a);const g=Ei(dn(p),Ii),v=ci(p,n);if(v&&[...v.values()].every(e=>!pi(e,n))&&Math.max(...v.keys())>=2)return g.s!==t.s&&i("solve.one-side","Everything on one side",["move"],t,g,{v:n}),Vi(e,p,v,n,s,i,r,o,a,g);const b=wi(p),y=b.factors.filter(e=>pi(e.base,n)&&!(Tt(e.exp)&&e.exp.q.sign<0));if(y.length>=2||1===y.length&&b.factors.length>1){const u=Ei(Mi(b),Ii);g.s!==t.s&&i("solve.one-side","Everything on one side",["move"],t,g,{v:n}),u.s!==g.s&&i("solve.factor","Factor",["factor"],g,u,{});const l=y.map(e=>Ei(dn(e.base),Ii));l.length>1&&i("solve.zero-product","A product is zero when a factor is",["split"],u,l.reduce((e,t)=>e?nt("|",[e,t]):t,null),{});for(const t of l)Bi(e,t,n,s,i,r,o,a+1);return}const w=Ai(p);if(pi(w.den,n)){const u=Ei(dn(w.num),Ii);return i("solve.clear-denominator","Clear the denominator",["move"],t,u,{den:dn(w.den)}),Bi(e,u,n,s,i,r,o,a+1)}const x=h.filter(e=>!_i(e,n));if(1===x.length&&/\b(sqrt|root|abs)\b/.test(dn(x[0]).s))return Di(e,t,x[0],nn(_t(bn(p).filter(e=>e!==x[0]))),n,s,i,r,o,a);const k=function(e,t){const n=dn(e),s=new Map;for(const{node:e}of pt(n,"pre"))if(it(e)&&vn(e).has(t))if("^"!==e.op||vn(e.args[0]).has(t))["sin","cos","tan","ln","sqrt","abs"].includes(e.op)&&e.args[0].s===t&&s.set(e.s,e);else{const n=ln(e.args[1]),{coef:i,rest:r}=Rt(n);if(r&&i.isInteger&&dn(r).s===t){const n=dn(Ut(ln(e.args[0]),ln(Ge(t))));s.set(n.s,n)}}const i="u"===t?"w":"u";for(const e of s.values()){const s=Wi(n,e,t,i);if(!s||vn(s).has(t))continue;const r=ln(s),o=ci(r,i);if(o&&Math.max(...o.keys())>=1)return{kernel:ln(e),poly:r,symbol:i}}return null}(p,n);if(k){const t=k.symbol;i("solve.substitute","Substitute",["substitute"],g,Ei(dn(k.poly),Ii),{u:Ge(t),kernel:dn(k.kernel)});const u=[];Bi(e,Ei(dn(k.poly),Ii),t,s,i,u,o,a+1);for(const t of u)Bi(e,Ei(dn(k.kernel),t),n,s,i,r,o,a+1);return}return Ui(e,g,n,s,i,r,o)}function Di(e,t,n,s,i,r,o,a,u,l){let c=Ei(dn(n),dn(s));c.s!==t.s&&o("solve.move","Move the terms",["move"],t,c,{v:i});const{coef:p,rest:h}=Rt(n),f=h?yn(h):[],d=Wt([At(p),...f.filter(e=>!pi(e,i))]);if(!Tt(d)||!d.q.isOne){const e=Wt(f.filter(e=>pi(e,i))),t=Ei(dn(e),dn(sn(s,d))),n=Tt(d)&&!d.q.isInteger&&(1n===d.q.n||-1n===d.q.n);o(n?"solve.multiply":"solve.divide",n?"Multiply both sides":"Divide both sides",["move"],c,t,{by:dn(n?At(d.q.inv()):d),v:i}),c=t}if("sym"===c.args[0].type&&c.args[0].token===i)return void a.push(c.args[1]);const m=ln(c.args[1]);if(Tt(m)&&m.q.isZero){const t=ln(c.args[0]),n=yn(t).filter(e=>pi(e,i)&&!Pi(e));if(!n.length&&yn(t).some(e=>pi(e,i)))return void o("solve.never","No solution",["check"],c,c,{});if(n.length>1||n.length<yn(t).filter(e=>pi(e,i)).length){const t=n.map(e=>Ei(dn(Ri(e)),Ii));o("solve.zero-product","A product is zero when a factor is",["split"],c,t.reduce((e,t)=>e?nt("|",[e,t]):t,null),{});for(const n of t)Bi(e,n,i,r,o,a,u,l+1);return}}const g=ti(c,e.set.view("isolate"),{format:e.format,maxSteps:1,variable:i});return g.steps.length?(function(e,t){for(const n of t)e.raw(n)}(o,g.steps),Bi(e,g.node,i,r,o,a,u,l+1)):Ui(e,c,i,r,o,a,u)}const Pi=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&Tt(e.fs[0].e)&&e.fs[0].e.q.sign<0,Ri=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&Tt(e.fs[0].e)&&e.fs[0].e.q.sign>0?e.fs[0].b:e,_i=(e,t)=>{const n=ci(e,t);return Boolean(n)&&[...n.values()].every(e=>!pi(e,t))};function Vi(e,t,n,s,i,r,o,a,u,l){const c=Math.max(...n.keys()),p=hi(n);if($t.complex&&c>=3&&c<=64&&p&&p.every((e,t)=>0===t||t===c||e.isZero)&&!p[0].isZero){const t=p[0].neg().div(p[c]),n=Ut(At(t.abs()),At(new bt(1n,BigInt(c)))),i=[];for(let s=0;s<c;s++){const r=Wt([At(new bt(BigInt((t.sign<0?1:0)+2*s),BigInt(c))),ln(Ge("pi"))]),o=nt("*",[dn(n),nt("+",[nt("cos",[dn(r)]),nt("*",[Ge("i"),nt("sin",[dn(r)])])])]);i.push(ti(o,e.set.view("simplify"),{format:e.format}).node)}return r("solve.roots","All n roots",["complex"],l,i.map(e=>Ei(Ge(s),e)).reduce((e,t)=>e?nt("|",[e,t]):t),{v:s,n:String(c),last:String(c-1),r:dn(At(t))}),void o.push(...i)}if(p){const{roots:n}=bi(p);if(n.length){const n=wi(t),c=Ei(Mi(n),Ii);if(n.factors.length>1||n.factors.some(e=>!(Tt(e.exp)&&e.exp.q.isOne))){r("solve.factor","Factor",["factor"],l,c,{});const t=n.factors.filter(e=>pi(e.base,s)).map(e=>Ei(dn(e.base),Ii));t.length>1&&r("solve.zero-product","A product is zero when a factor is",["split"],c,t.reduce((e,t)=>e?nt("|",[e,t]):t,null),{});for(const n of t)Bi(e,n,s,i,r,o,a,u+1);return}}}if(2===c){const e=n.get(2),t=n.get(1)??At(bt.ZERO),i=n.get(0)??At(bt.ZERO),a=_t([Ut(t,At(bt.of(2))),Wt([At(bt.of(-4)),e,i])]);if(Tt(a)&&a.q.sign<0&&!$t.complex)return void r("solve.no-real","No real solutions",["quadratic"],l,l,{D:dn(a)});const u=Wt([At(bt.of(2)),e]),c=Ut(a,At(bt.HALF)),p=dn(sn(_t([nn(t),c]),u)),h=dn(sn(_t([nn(t),nn(c)]),u)),f=p.s===h.s?Ei(Ge(s),p):nt("|",[Ei(Ge(s),p),Ei(Ge(s),h)]);return r($t.complex&&Tt(a)&&a.q.sign<0?"solve.quadratic-complex":"solve.quadratic","The quadratic formula",["quadratic"],l,f,{a:dn(e),b:dn(t),c:dn(i),D:dn(a),root:dn(c),v:s}),o.push(p),void(h.s!==p.s&&o.push(h))}return Ui(e,l,s,i,r,o,a)}function Wi(e,t,n,s){if(e.s===t.s)return Ge(s);if(!it(e))return e;if("^"===e.op&&"^"===t.op&&e.args[0].s===t.args[0].s){const t=ln(e.args[1]),{coef:i,rest:r}=Rt(t);if(r&&dn(r).s===n&&i.isInteger)return nt("^",[Ge(s),dn(At(i))])}return nt(e.op,e.args.map(e=>Wi(e,t,n,s)))}function Ui(e,t,n,s,i,r,o){if(s.approximate){const e="number"==typeof s.approximate?s.approximate:15,o=ln(nt("-",[t.args[0],t.args[1]])),a=$t.complex?hi(ci(o,n)):null,u=a&&a.length>2?function(e,t){const n=e.length-1,s=e[n],i=e.map(e=>e/s),r=(e,t)=>{let s=1,r=0;for(let o=n-1;o>=0;o--)[s,r]=[s*e-r*t+i[o],s*t+r*e];return[s,r]};let o=Array.from({length:n},(e,t)=>[1.3*Math.cos(2*Math.PI*t/n+.4),1.3*Math.sin(2*Math.PI*t/n+.4)]);for(let e=0;e<500;e++){let e=0;if(o=o.map(([t,s],i)=>{let[a,u]=r(t,s);for(let e=0;e<n;e++){if(e===i)continue;const n=t-o[e][0],r=s-o[e][1],l=n*n+r*r;[a,u]=[(a*n+u*r)/l,(u*n-a*r)/l]}return e=Math.max(e,Math.hypot(a,u)),[t-a,s-u]}),e<1e-15)break}const a=e=>Math.abs(e)<1e-12?0:Number(e.toPrecision(t));return o.map(([e,t])=>[a(e),a(t)]).sort((e,t)=>(0!==e[1])-(0!==t[1])||e[0]-t[0]||e[1]-t[1]).map(([e,t])=>{const n=Hi(e);if(0===t)return n;const s=nt("*",[Hi(Math.abs(t)),Ge("i")]);return 0===e?t<0?nt("neg",[s]):s:nt(t<0?"-":"+",[n,s])})}(a.map(e=>e.toNumber()),Math.min(e,14)):function(e,t,n){const s=ln(nt("-",[e.args[0],e.args[1]])),i=dn(s),r=e=>{try{return Bs(Zi(i,t,Ki(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 t=a[e],s=a[e+1],i=r(t);const u=r(s);if(Number.isNaN(i)||Number.isNaN(u))continue;if(0===i){o.push(Ki(t));continue}if(i*u>0)continue;for(let e=0;e<200&&s-t>1e-16*Math.abs(t);e++){const e=(t+s)/2,n=r(e);if(Number.isNaN(n))break;i*n<=0?s=e:(t=e,i=n)}const l=(t+s)/2;Math.abs(r(l))<1e-6&&o.push(Ki(Number(l.toPrecision(Math.min(n,15)))))}return o}(t,n,e);for(const e of u)r.numeric?.add(e);return i("solve.numeric","Numeric solutions",["numeric"],t,u.length?u.map(e=>Ei(Ge(n),e)).reduce((e,t)=>e?nt("|",[e,t]):t):t,{v:n,count:String(u.length)}),void r.push(...u)}i("solve.unsolved","No exact method",["unsolved"],t,t,{v:n}),o.push(t)}const Hi=e=>Xe(String(e).includes("e")?e.toFixed(20):String(e)),Ki=e=>Xe(Number.isInteger(e)?String(e):e.toFixed(17));const Ji=()=>Xe("1"),Qi={"<":e=>e<0,">":e=>e>0,"≤":e=>e<=0,"≥":e=>e>=0},Yi=new Set(["sin","cos","tan","csc","sec","cot"]);function Gi(e,t,n){const s=[],i=[],r=[];let o=t;for(;it(o.args[0])&&Qi[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,t)=>i.push({h:cn(nt("-",[a[t],a[t+1]])),op:e}));const u=new Set(i.flatMap(e=>[...vn(e.h)]));if(u.delete(n),u.size)throw new ft(`an inequality in ${n} with other unknowns (${[...u].join(", ")}) can't be charted`);if(i.some(e=>pt(e.h,"pre").some(({node:e})=>it(e)&&Yi.has(e.op)&&vn(e).has(n))))return{pieces:null,steps:s,unsolved:!0};const l=[];for(const{h:e}of i){l.push(e);for(const{node:t}of pt(e,"pre"))it(t)&&vn(t).has(n)&&("/"===t.op&&l.push(t.args[1]),"sqrt"!==t.op&&"ln"!==t.op||l.push(t.args[0]),"root"===t.op&&l.push(t.args[1]),"log"===t.op&&l.push(t.args[1],t.args[0],nt("-",[t.args[0],Ji()])),["arcsin","arccos","arctanh","arcsec","arccsc"].includes(t.op)&&l.push(nt("-",[t.args[0],Ji()]),nt("+",[t.args[0],Ji()])),"arccosh"===t.op&&l.push(nt("-",[t.args[0],Ji()])),"^"===t.op&&Tt(ln(t.args[1]))&&ln(t.args[1]).q.sign<0&&l.push(t.args[0]),"^"===t.op&&Tt(ln(t.args[1]))&&!ln(t.args[1]).q.isInteger&&l.push(t.args[0]))}const c=new Map;for(const t of l){const i=Li(e,Ei(t,Ii),n,{});if(i.unsolved.length&&!i.always)return{pieces:null,steps:s,unsolved:!0};if(!i.always)for(const e of i.solutions){const t=zi(e);!t||Math.abs(t.im)>1e-12||c.set(e.s,{node:e,x:t.re})}}const p=[...c.values()].sort((e,t)=>e.x-t.x).filter((e,t,n)=>0===t||Math.abs(e.x-n[t-1].x)>1e-12),h=p.map(e=>e.x),f=[];if(h.length){f.push(h[0]-Math.max(1,Math.abs(h[0])));for(let e=0;e+1<h.length;e++)f.push((h[e]+h[e+1])/2);f.push(h[h.length-1]+Math.max(1,Math.abs(h[h.length-1])))}else f.push(0);const d=f.map(e=>i.every(({h:t,op:s})=>{try{const i=Bs(Zi(t,n,Xe(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)&&Qi[s](Math.abs(i.re)<1e-30?0:i.re)}catch{return!1}})),m=p.map(e=>i.every(({h:t,op:s})=>{try{const i=Bs(cn(Zi(t,n,e.node)),{digits:30});return!(!Number.isFinite(i.re)||Math.abs(i.im)>1e-12)&&Qi[s](Math.abs(i.re)<1e-15?0:i.re)}catch{return!1}})),g=[];let v=null;const b=(e,t)=>{g.push({...v,hi:e,hiClosed:t}),v=null};for(let e=0;e<=p.length;e++){const t=0===e?null:p[e-1].node;if(d[e]?v??={lo:t,loClosed:!1}:v&&b(t,e>0&&m[e-1]),e===p.length)break;const n=p[e];if(m[e]){if(v)continue;d[e+1]?v={lo:n.node,loClosed:!0}:g.push({lo:n.node,hi:n.node,loClosed:!0,hiClosed:!0})}else v&&b(n.node,!1)}v&&b(null,!1);const y=p.length?p.map(t=>e.format(t.node)).join(", "):"none";return s.push(e.step("solve.sign-chart","A sign chart",["inequality"],t,t,{points:Ge(y),v:n})),{pieces:g,steps:s}}const Xi={tan:"cos",sec:"cos",csc:"sin",cot:"sin"};class er extends Error{}const tr=e=>({fin:e}),nr={bnd:!0},sr=e=>({inf:e}),ir=Ge("∞");function rr(e){try{const t=Bs(e,{digits:15});return Math.abs(t.im??0)>1e-12?NaN:t.re??t.number}catch{return NaN}}function or(e){if(!$t.complex)return Number.isFinite(rr(e));try{const t=Bs(e,{digits:15});return Number.isFinite(t.re??t.number)&&Number.isFinite(t.im??0)}catch{return!1}}function ar(e,t,n){if(!Number.isFinite(n))return!1;try{const s=Bs(Zi(e,t,Xe(lr(n))),{digits:15});return Math.abs(s.im??0)>1e-12}catch(e){return/not real/.test(e.message)}}function ur(e,t,n){return Number.isFinite(n)?rr(Zi(e,t,Xe(lr(n)))):NaN}function lr(e){const t=Math.min(40,Math.max(0,16-Math.floor(Math.log10(Math.abs(e)||1))));return e.toFixed(t)}function cr(e,t,n,s){const i=pr(n,s).map(n=>ur(e,t,n)).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 pr(e,t){if(e.inf)return[100,1e3,1e4,1e5,1e6].map(t=>t*e.inf);const n=rr(e.fin);return[.001,1e-4,1e-5,1e-6,1e-7].map(e=>n+t*e*Math.max(1,Math.abs(n)))}function hr(e,t,n,s,i=0){const r=[];if(!i&&!s.inf){const[e,i]=[cr(t,n,s,-1),cr(t,n,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 er(`from the left it goes to ${+e.toPrecision(6)}, from the right to ${+i.toPrecision(6)}`)}if(!s.inf&&!$t.complex)for(const e of i?[i]:[-1,1])if(pr(s,e).every(e=>ar(t,n,e)))throw new er(`it has no real values ${e<0?"to the left":"to the right"} of ${+rr(s.fin).toPrecision(6)}`);const o=new fr(e,n,s,i,r);let a;try{if(a=o.of(cn(t),0),a.bnd)throw new er("it keeps swinging between bounds")}catch(e){if(e instanceof er){const e=(s.inf?[s.inf]:i?[i]:[-1,1]).map(e=>cr(t,n,s,e));if(e.every(Number.isFinite)&&e.every(t=>Math.abs(t-e[0])<1e-6*Math.max(1,Math.abs(t))))throw new ft(`numbers near the point settle on ${+e[0].toPrecision(6)}: not answered`)}throw e}return function(e,t,n,s,i){const r=s?[s]:n.inf?[-1]:[-1,1];for(const s of r){const r=pr(n,s).map(n=>ur(e,t,n)).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 ft(`numbers near the point don't go to ${i.inf>0?"∞":"-∞"}: not answered`)}else{const e=rr(i.fin);if(!Number.isFinite(e))continue;const t=r.map(t=>Math.abs(t-e)),n=Math.abs(r[r.length-1]-r[r.length-2]),s=t.every((e,n)=>0===n||e<t[n-1])&&t[t.length-1]<.5*t[0]&&t[t.length-1]<10*n;if(t[t.length-1]>.01*Math.max(1,Math.abs(e))&&!s)throw new ft(`numbers near the point go to ${o.toPrecision(6)}, not ${e.toPrecision(6)}: not answered`)}}}(t,n,s,i,a),{value:a,steps:r}}class fr{constructor(e,t,n,s,i){Object.assign(this,{cas:e,v:t,a:n,side:s,steps:i}),this.point=n.inf?n.inf>0?ir:Ge("-∞"):n.fin}step(e,t,n,s,i={}){this.steps.push(this.cas.step(e,t,["limit"],n,s,{v:Ge(this.v),a:this.point,...i}))}of(e,t){if(t>8)throw new ft("this limit went too deep");const{v:n,a:s}=this;if(!vn(e).has(n))return tr(e);if("sym"===e.type)return s.inf?sr(s.inf):tr(s.fin);if(s.inf){const i=hi(ci(ln(e),n));if(i&&i.length>1){const r=i.length-1,o=i[r].sign*(r%2&&s.inf<0?-1:1);return 0===t&&this.step("limit.leading","The leading term",e,cn(nt("*",[dn(At(i[r])),nt("^",[Ge(n),Xe(String(r))])])),{f:e,lead:cn(nt("*",[dn(At(i[r])),nt("^",[Ge(n),Xe(String(r))])]))}),sr(o)}}if(!s.inf&&0===t){const t=Zi(e,n,s.fin);let i=null;if(or(t)&&!this.pole(t)&&!dr(t))try{i=cn(t)}catch{}if(i&&or(i)){const t=this.cas.simplify(i,{steps:!1}).result;return this.step("limit.substitute","Put the point in",e,t,{f:e}),tr(t)}}if(!it(e))return tr(e);switch(e.op){case"+":case"-":return this.sum(e,t);case"neg":return gr(this.of(e.args[0],t+1));case"*":return this.product(e,t);case"/":return this.quotient(e,e.args[0],e.args[1],t);case"^":return this.power(e,t);default:return this.func(e,t)}}signOf(e){const t=Math.sign(rr(e));if(!t)throw new ft(`the sign of ${this.cas.format(e)} is not known`);return t}pole(e){return mr(e).some(e=>it(e)&&Xi[e.op]&&this.isExactZero(nt(Xi[e.op],[e.args[0]])))}isExactZero(e){try{const t=this.cas.simplify(cn(e),{steps:!1}).result;return st(t)&&0===Number(t.value)}catch{return!1}}sum(e,t){const[n,s]=e.args;let i,r;try{i=this.of(n,t+1),r=this.of(s,t+1)}catch(n){if(!(n instanceof er))throw n;const s=Ai(ln(e)),i=cn(nt("/",[dn(s.num),dn(s.den)]));if(i.s===e.s)throw n;return this.step("limit.combine","One fraction",e,i,{f:e}),this.of(i,t+1)}const o="-"===e.op?gr(r):r;if(i.bnd||o.bnd)return i.inf||o.inf?i.inf?i:o:nr;if(i.fin&&o.fin)return tr(cn(nt("+",[i.fin,o.fin])));if(i.inf&&o.inf&&i.inf!==o.inf){const i="-"===e.op?s:nt("neg",[s]);if([n,s].some(e=>it(e)&&"sqrt"===e.op)||it(s)&&"neg"===s.op&&it(s.args[0])&&"sqrt"===s.args[0].op){const s=cn(nt("/",[nt("-",[nt("^",[n,Xe("2")]),nt("^",[i,Xe("2")])]),nt("+",[n,i])]));return this.step("limit.conjugate","∞ − ∞: the conjugate",e,s,{f:e}),this.of(s,t+1)}const r=Ai(ln(e)),o=cn(nt("/",[dn(r.num),dn(r.den)]));if(o.s===e.s)throw new ft("∞ − ∞ that does not become one fraction");return this.step("limit.combine","∞ − ∞: one fraction",e,o,{f:e}),this.of(o,t+1)}return i.inf?i:o}product(e,t){const[n,s]=e.args,i=this.of(n,t+1),r=this.of(s,t+1),o=e=>e.fin&&Math.abs(rr(e.fin))<1e-300;if(i.bnd||r.bnd){const t=i.bnd?r:i;if(o(t))return this.step("limit.squeeze","The squeeze theorem",e,Xe("0"),{f:e,bounded:i.bnd?n:s}),tr(Xe("0"));if(t.inf)throw new er("a growing factor times one that keeps swinging");return nr}if(i.fin&&r.fin)return tr(cn(nt("*",[i.fin,r.fin])));if(o(i)&&r.inf||i.inf&&o(r)){const[r,a]=o(i)?[n,s]:[s,n],u=e=>e.s.split(" ").length,[l,c]=[cn(nt("/",[Xe("1"),r])),cn(nt("/",[Xe("1"),a]))],p=u(l)<=u(c)?nt("/",[a,l]):nt("/",[r,c]);return this.step("limit.zero-times-infinity","0·∞: a quotient",e,p,{f:e}),this.quotient(p,p.args[0],p.args[1],t+1)}const a=e=>e.inf?e.inf:this.signOf(e.fin);return sr(a(i)*a(r))}quotient(e,t,n,s){const{v:i,a:r}=this;if(r.inf){const t=this.rational(e,s);if(t)return t}const o=this.of(t,s+1),a=this.of(n,s+1),u=e=>e.fin&&Math.abs(rr(e.fin))<1e-300;if(o.bnd&&a.inf)return this.step("limit.squeeze","The squeeze theorem",e,Xe("0"),{f:e,bounded:t}),tr(Xe("0"));if(o.bnd&&a.fin&&!u(a))return nr;if(a.bnd)throw new ft("a quotient over something that keeps swinging is not worked out here");if(o.inf&&a.inf&&r.inf){const i=this.dividePower(e,t,n,s);if(i)return i}if(a.fin&&!u(a))return o.fin?tr(this.cas.simplify(cn(nt("/",[o.fin,a.fin])),{steps:!1}).result):sr(o.inf*this.signOf(a.fin));if(a.inf&&o.fin)return tr(Xe("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 p=cn(this.cas.differentiate(t,i)),h=cn(this.cas.differentiate(n,i)),f=cn(nt("/",[p,h]));return this.step("limit.lhopital","L'Hôpital's rule",e,f,{f:e,form:Ge(l)}),this.of(f,s+1)}dividePower(e,t,n,s){const{v:i,a:r}=this;if(!mr(e).some(e=>it(e)&&(["sqrt","root","sin","cos"].includes(e.op)||"^"===e.op&&!vn(e.args[1]).size&&!Number.isInteger(rr(e.args[1]))))||this.divided?.has(e.s))return null;const[o,a]=[1e4*r.inf,1e6*r.inf],u=Math.log(Math.abs(ur(n,i,a)/ur(n,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=nt("^",[Ge(i),Xe(String(l))]),p=e=>{if(it(e)&&("+"===e.op||"-"===e.op))return nt(e.op,e.args.map(p));if(it(e)&&"neg"===e.op)return nt("neg",[p(e.args[0])]);if(it(e)&&"sqrt"===e.op){const t=nt("sqrt",[cn(nt("/",[e.args[0],nt("^",[Ge(i),Xe(String(2*l))])]))]);return r.inf<0&&l%2?nt("neg",[t]):t}return cn(nt("/",[e,c]))},h=nt("/",[cn(p(t)),cn(p(n))]);return(this.divided??=new Set).add(e.s),this.step("limit.divide-power","Divide by the highest power",e,h,{f:e,power:c}),this.quotient(h,h.args[0],h.args[1],s+1)}rational(e,t){const{v:n,a:s}=this,{num:i,den:r}=Ai(ln(e)),o=hi(ci(i,n)),a=hi(ci(r,n));if(!o||!a||a.length<2)return null;if(s.inf){const[t,i]=[o.length-1,a.length-1],r=cn(nt("/",[nt("*",[dn(At(o[t])),nt("^",[Ge(n),Xe(String(t))])]),nt("*",[dn(At(a[i])),nt("^",[Ge(n),Xe(String(i))])])]));if(r.s!==e.s&&this.step("limit.leading","The leading terms",e,r,{f:e,lead:r}),t<i)return tr(Xe("0"));if(t===i)return tr(dn(At(o[t].div(a[i]))));const u=o[t].div(a[i]).sign*((t-i)%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=Zi(u,n,s.fin);return Number.isFinite(rr(l))?tr(this.cas.simplify(cn(l),{steps:!1}).result):this.blowUp(u)}blowUp(e){const{v:t,a:n,side:s}=this,i=(s?[s]:[-1,1]).map(s=>function(e,t,n,s){const i=pr(n,s).map(n=>ur(e,t,n)).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,t,n,s));if(i.includes(0))throw new ft("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?ir:Ge("-∞"),right:i[1]>0?ir:Ge("-∞")}),new er(`from the left it goes to ${i[0]>0?"∞":"-∞"}, from the right to ${i[1]>0?"∞":"-∞"}`);return sr(i[0])}power(e,t){const{v:n}=this,[s,i]=e.args,r=this.of(s,t+1);let o;const a=this.steps.length;try{o=this.of(i,t+1)}catch(n){if(!(n instanceof er)||!r.fin||Math.abs(rr(r.fin)-1)>1e-12)throw n;return this.steps.length=a,this.expLog(e,s,i,"1^∞",t)}if(r.bnd||o.bnd)throw new ft("a power of something that keeps swinging is not worked out here");const u=e=>e.fin?rr(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 tr(this.cas.simplify(cn(nt("^",[r.fin,o.fin])),{steps:!1}).result)}const p=!vn(s).has(n),h=!vn(i).has(n),f=r.fin&&Math.abs(l)<1e-300,d=r.fin&&Math.abs(l-1)<1e-12;if(r.fin&&o.inf&&(!d||p)){if(d)return tr(Xe("1"));if(f){if(o.inf<0){if(p)throw new er("0 to a negative power has no value");return sr(1)}return tr(Xe("0"))}if(l>1)return o.inf>0?sr(1):tr(Xe("0"));if(l>0)return o.inf>0?tr(Xe("0")):sr(1);throw new er("a negative number to a growing power swings between signs")}if(r.inf<0&&!h)throw new ft("a power of something going to -∞ is not worked out here");if(r.inf&&(h||o.fin&&Math.abs(c)>1e-300||o.inf)){if(c>0)return sr(r.inf>0?1:h&&Number.isInteger(c)&&c%2?-1:1);if(c<0)return tr(Xe("0"))}if(h&&f&&c>0)return tr(Xe("0"));const m=d?"1^∞":f?"0^0":r.inf&&o.fin?"∞^0":null;if(!m)throw new ft("a power of this shape is not worked out here");return this.expLog(e,s,i,m,t)}expLog(e,t,n,s,i){const r=cn(nt("*",[n,nt("ln",[t])]));this.step("limit.exp-log","Take logs",e,nt("^",[Ge("e"),r]),{f:e,form:Ge(s)});const o=this.of(r,i+1);if(o.bnd)throw new ft("a power of something that keeps swinging is not worked out here");return o.inf?o.inf>0?sr(1):tr(Xe("0")):tr(this.cas.simplify(cn(nt("^",[Ge("e"),o.fin])),{steps:!1}).result)}func(e,t){const n=e.op,s=e.args;if(1!==s.length){if("log"===n&&!vn(s[0]).has(this.v)){const e=this.of(s[1],t+1);if(e.fin){const t=cn(nt("log",[s[0],e.fin]));if(Number.isFinite(rr(t)))return tr(this.cas.simplify(t,{steps:!1}).result)}return this.of(cn(nt("/",[nt("ln",[s[1]]),nt("ln",[s[0]])])),t+1)}throw new ft(`a limit of ${n} is not worked out here`)}let i;try{i=this.of(s[0],t+1)}catch(e){if(e instanceof er&&("sin"===n||"cos"===n))return nr;throw e}if(i.bnd){if("sin"===n||"cos"===n||"arctan"===n||"abs"===n)return nr;throw new ft(`${n} of something that keeps swinging is not worked out here`)}if(i.fin){if(Xi[n]&&this.isExactZero(nt(Xi[n],[i.fin])))return this.blowUp(e);const t=cn(nt(n,[i.fin]));if(or(t))return tr(this.cas.simplify(t,{steps:!1}).result);if("ln"===n&&Math.abs(rr(i.fin))<1e-300)return sr(-1);if(["tan","sec","csc","cot"].includes(n))return this.blowUp(e);throw new ft(`${n} has no value at the limit of its argument`)}const r=i.inf;switch(n){case"sqrt":case"ln":case"cosh":if(r<0&&"cosh"!==n)throw new er(`${n} has no value as its argument goes to -∞`);return sr(1);case"abs":return sr(1);case"sinh":return sr(r);case"tanh":return tr(Xe(String(r)));case"arctan":return tr(cn(nt("/",[r>0?Ge("pi"):nt("neg",[Ge("pi")]),Xe("2")])));case"arccot":return tr(r>0?Xe("0"):Ge("pi"));case"arcsec":case"arccsc":return tr("arcsec"===n?cn(nt("/",[Ge("pi"),Xe("2")])):Xe("0"));case"sin":case"cos":return nr;case"tan":case"sec":case"csc":case"cot":throw new er(`${n} keeps swinging as its argument grows`);default:throw new ft(`a limit of ${n} at ∞ is not worked out here`)}}}const dr=e=>mr(e).some(e=>it(e)&&("/"===e.op&&Math.abs(rr(e.args[1]))<1e-300||"^"===e.op&&rr(e.args[1])<0&&Math.abs(rr(e.args[0]))<1e-300)),mr=(e,t=[])=>(t.push(e),it(e)&&e.args.forEach(e=>mr(e,t)),t),gr=e=>e.bnd?e:e.inf?sr(-e.inf):tr(cn(nt("neg",[e.fin])));function vr(e){if(!it(e)||"lim"!==e.op)return null;const[t,n,s,i]=e.args;if(it(n)&&"→"===n.op)return{f:t,v:n.args[0].token,to:n.args[1],side:0};if("sym"===n?.type&&s){const e="r"===i?.token?1:"l"===i?.token?-1:0;return{f:t,v:n.token,to:s,side:e}}return null}function br(e){return"sym"!==e.type||"∞"!==e.token&&"oo"!==e.token&&"infinity"!==e.token?"sym"===e.type&&"-∞"===e.token||it(e)&&"neg"===e.op&&"sym"===e.args[0].type&&"∞"===e.args[0].token?sr(-1):tr(cn(e)):sr(1)}const yr=new Set(["sin","cos","tan","sec","csc","cot"]),wr=()=>Xe("2");function xr(e,t){if(!kr(t))return[];let n,s;try{const e=qr(t);n=new Map;s=Ai(ln($r(e,n)))}catch{return[]}const i=[];for(const t of["sin","cos","none"])try{const r="none"===t?ui(s.num):Sr(s.num,n,t),o="none"===t?ui(s.den):Sr(s.den,n,t);if(!r||!o)continue;const a=[Ar(r,o)],u=[Mr(r,n),Mr(o,n)];u[0]&&u[1]&&a.push(Ar(u[0],u[1]));for(const t of a)i.push(Er(e,Nr(t,n)))}catch{}return i}const kr=e=>it(e)&&(yr.has(e.op)||e.args.some(kr));function qr(e){if(!it(e))return e;const t=e.args.map(qr),[n]=t,s=e=>nt("sin",[e]),i=e=>nt("cos",[e]),r=e=>it(e)&&"*"===e.op&&st(e.args[0])&&2===Number(e.args[0].value)?2===e.args.length?e.args[1]:nt("*",e.args.slice(1)):null;switch(e.op){case"tan":return nt("/",[s(n),i(n)]);case"sec":return nt("/",[Xe("1"),i(n)]);case"csc":return nt("/",[Xe("1"),s(n)]);case"cot":return nt("/",[i(n),s(n)]);case"sin":{const e=r(n);return e?nt("*",[nt("*",[wr(),s(e)]),i(e)]):s(n)}case"cos":{const e=r(n);return e?nt("-",[nt("^",[i(e),wr()]),nt("^",[s(e),wr()])]):i(n)}default:return nt(e.op,t)}}function $r(e,t){if(!it(e))return e;if(("sin"===e.op||"cos"===e.op)&&!kr(e.args[0])){const n=e.args[0];t.has(n.s)||t.set(n.s,{u:n,s:`$s${t.size}`,c:`$c${t.size}`});const s=t.get(n.s);return Ge("sin"===e.op?s.s:s.c)}return nt(e.op,e.args.map(e=>$r(e,t)))}function Sr(e,t,n){let s=ui(e);for(const{s:e,c:i}of t.values()){const[t,r]="sin"===n?[e,i]:[i,e],o=ci(s,t);if(!o)return null;const a=[];for(const[e,n]of o){const s=Math.floor(e/2),i=[n];e%2&&i.push(ln(Ge(t))),s&&i.push(ln(nt("^",[nt("-",[Xe("1"),nt("^",[Ge(r),wr()])]),Xe(String(s))]))),a.push(Wt(i))}if(s=ui(_t(a)),bn(s).length>200)return null}return s}function Mr(e,t){let n=ui(e);for(const{u:e,s:s,c:i}of t.values()){const t=nt("sin",[nt("*",[wr(),e])]),r=nt("cos",[nt("*",[wr(),e])]),o=[];for(const e of bn(n)){const n=dn(e),a=Or(n,s),u=Or(n,i);if(a+u===0){o.push(e);continue}if(a+u!==2)return null;const l=Zi(Zi(n,s,Xe("1")),i,Xe("1")),c=nt("/",1===a?[t,wr()]:2===a?[nt("-",[Xe("1"),r]),wr()]:[nt("+",[Xe("1"),r]),wr()]);o.push(ln(nt("*",[l,c])))}n=ui(_t(o))}return n}function Or(e,t){const n=ci(ln(e),t);return n?Math.max(0,...n.keys()):0}function Ar(e,t){const n=ln(nt("/",[dn(e),dn(t)])),s=Ni(n);return s?Mi(s):dn(n)}function Nr(e,t){let n=e;for(const{u:e,s:s,c:i}of t.values())n=Zi(Zi(n,s,nt("sin",[e])),i,nt("cos",[e]));return cn(n)}function Er(e,t){const n=e=>{if(!it(e))return e;const t=e.args.map(n);if("/"===e.op&&st(t[0])){const e=t[1],[n,s]=it(e)&&"^"===e.op&&st(e.args[1])?[e.args[0],e.args[1]]:[e,null],i=it(n)&&{cos:"sec",sin:"csc"}[n.op];if(i){const e=nt(i,n.args),r=s?nt("^",[e,s]):e;return 1===Number(t[0].value)?r:nt("*",[t[0],r])}}return nt(e.op,t)},s=ti(cn(n(t)),e.set.view("simplify"),{format:e.format}).node;try{const{num:e,den:t}=Ai(ln(s)),n=cn(nt("/",[dn(e),dn(t)]));return n.s.split(" ").length<s.s.split(" ").length?n:s}catch{return s}}const Ir=(e,t)=>nt("int",[e,"string"==typeof t?Ge(t):t]);function Tr(e,t,n,s=0){if(s>6)throw new ft("integration went too deep");const i=[],r=e.set.view("integrate"),o=ti(t,e.set.view("simplify"),{format:e.format});i.push(...o.steps);let a=cn(Ir(o.node,n));for(let t=0;t<40;t++){const t=ti(a,r,{format:e.format});i.push(...t.steps),a=t.node;const n=pt(a,"pre").find(({node:e})=>{return it(t=e)&&"int"===t.op&&2===t.args.length;var t});if(!n)return{node:a,steps:i};const o=Lr(e,n.node,s);if(!o)throw new ft(`no rule for ∫ ${e.format(n.node.args[0])} d${n.node.args[1].token}`);i.push(...o.steps),a=cn(ht(a,n.path,o.node))}throw new ft("integration did not finish")}function Lr(e,t,n){const[s,i]=t.args,r=i.token,o=ln(s),a=function(e,t){const{num:n,den:s}=Ai(e),i=wi(n),r=wi(s),o=i.coef.div(r.coef);if(o.isOne||!pi(e,t))return null;const a=Wt([...i.factors.map(e=>Ht(e.base,e.exp)),...r.factors.map(e=>Ht(e.base,nn(e.exp)))]);return{c:o,rest:a}}(o,r);if(a){const n=nt("*",[dn(At(a.c)),Ir(dn(a.rest),i)]);return{node:n,steps:[e.step("integrate.constant","Take the number out",["split"],t,n,{c:dn(At(a.c))})]}}const u=ui(o);if(dn(u).s!==s.s&&"add"===u.k){const n=Ir(dn(u),i);return{node:n,steps:[e.step("integrate.expand","Multiply out",["expand"],t,n,{})]}}const l=function(e,t){const n=new Map;for(const{node:s}of pt(e,"pre")){if(!it(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||!vn(s).has(t))continue;const e=ci(ln(s),t);if(!e||1!==Math.max(...e.keys()))continue;const i=e.get(1);pi(i,t)||Tt(i)&&i.q.isZero||n.set(s.s,{node:s,a:i})}}for(const s of n.values()){if(!vn(Rr(e,s.node,Ge("§"))).has(t))return s}return null}(s,r);if(l){const i="u"===r?"t":"u",o=Rr(s,l.node,Ge(i));if(!vn(o).has(r)){const s=Tr(e,cn(o),i,n+1),a=cn(Zi(s.node,i,l.node)),u=dn(sn(ln(a),l.a));return{node:u,steps:[e.step("integrate.substitute","Substitute",["substitute"],t,cn(Ir(o,i)),{u:Ge(i),inside:l.node,a:dn(l.a),v:r}),...s.steps,e.step("integrate.back","Substitute back",["substitute"],s.node,u,{u:Ge(i),inside:l.node})]}}}const c=function(e,t,n,s){const{num:i,den:r}=Ai(n);if(!pi(r,s))return null;const o=hi(ci(i,s)),a=hi(ci(r,s));if(!o||!a||a.length<2)return null;const u=ln(Ge(s)),l=e=>fi(e,s);if(o.length>=a.length){const{q:n,r:i}=yi(o,a),r=Ir(dn(_t([l(n),sn(l(i),l(a))])),Ge(s));return{node:r,steps:[e.step("integrate.divide","Divide the polynomials",["divide"],t,r,{})]}}const{roots:c,rest:p}=bi(a),h=new Set(c.map(String)).size===c.length,f=3===p.length&&p[1].mul(p[1]).sub(bt.of(4).mul(p[0]).mul(p[2])).sign<0;if(!h||1!==p.length&&!f||!c.length&&!f)return null;const d=(e=>e.length<=1?[bt.ZERO]:e.slice(1).map((e,t)=>e.mul(bt.of(t+1))))(a),m=c.map(e=>mi(o,e).div(mi(d,e))),g=c.map((e,t)=>sn(At(m[t]),_t([u,At(e.neg())])));if(!f){const n=Ir(dn(_t(g)),Ge(s));return{node:n,steps:[e.step("integrate.partial-fractions","Partial fractions",["partial-fractions"],t,n,{})]}}let v=o;c.forEach((e,t)=>{v=Pr(v,Dr(yi(a,[e.neg(),bt.of(1)]).q,m[t]))});const b=c.reduce((e,t)=>Br(e,[t.neg(),bt.of(1)]),[bt.of(1)]),{q:y}=yi(v,b),[w,x]=[y[0]??bt.ZERO,y[1]??bt.ZERO],[k,q,$]=yi(a,b).q,S=bt.of(4).mul($).mul(k).sub(q.mul(q)),M=fi([k,q,$],s),O=x.div(bt.of(2).mul($)),A=w.sub(x.mul(q).div(bt.of(2).mul($))),N=nt("sqrt",[jr(S)]),E=nt("*",[jr(O),nt("ln",[nt("abs",[dn(M)])])]),I=nt("*",[nt("/",[nt("*",[zr(2),jr(A)]),N]),nt("arctan",[nt("/",[dn(fi([q,$.mul(bt.of(2))],s)),N])])]),T=g.length?Ir(dn(_t(g)),Ge(s)):zr(0),L=cn(nt("+",[nt("+",[T,E]),I]));return{node:L,steps:[e.step("integrate.complete-square","Complete the square",["partial-fractions"],t,L,{Q:dn(M)})]}}(e,t,o,r);if(c)return c;const p=Fr(e,t,r);if(p)return p;const h=function(e,t,n,s){if(s>=3)return null;const[i,r]=t.args,o="u"===n?"t":"u",a=new Set;for(const{node:r}of pt(i,"pre")){if(r===i||!it(r)||r.s===i.s||a.has(r.s)||!vn(r).has(n)||["der","int"].includes(r.op))continue;let u,l,c;a.add(r.s);try{u=cn(e.differentiate(r,n))}catch{continue}if(st(u)&&0===Number(u.value))continue;try{l=Rr(cn(nt("/",[i,u])),r,Ge(o))}catch{continue}if(vn(l).has(n))continue;try{c=Tr(e,cn(l),o,s+1)}catch{continue}const p=cn(Zi(c.node,o,r));return{node:p,steps:[e.step("integrate.u-substitution","Substitute",["substitute"],t,cn(Ir(l,o)),{u:Ge(o),inside:r,du:u,v:n}),...c.steps,e.step("integrate.back","Substitute back",["substitute"],c.node,p,{u:Ge(o),inside:r})]}}return null}(e,t,r,n);return h||function(e,t,n,s,i){if(i>=6)return null;const r=yn(n),o=r.filter(e=>_r(e,s)||!pi(e,s)),a=r.filter(e=>!o.includes(e));if(1!==a.length)return null;const u=Wt(o),l=a[0],c=dn(l),p=it(c)?c.op:"",h=["ln","arctan","arcsin","arccos","arcsec","arccsc","arccot"];if(!pi(u,s)&&!h.includes(p))return null;let f,d,m;h.includes(p)?(f=l,d=u):(f=u,d=l);try{m=Tr(e,dn(d),s,i+1)}catch{return null}const g=ln(e.differentiate(dn(f),s)),v=Wt([f,ln(m.node)]),b=Ir(dn(Wt([g,ln(m.node)])),Ge(s)),y=cn(nt("-",[dn(v),b]));return{node:y,steps:[e.step("integrate.parts","Integration by parts",["parts"],t,y,{u:dn(f),dv:dn(d),V:m.node,du:dn(g),v:s})]}}(e,t,o,r,n)}const jr=e=>dn(At(e)),zr=e=>Xe(String(e));function Cr(e,t){if(!e||!vn(e).has(t))return null;const n=ci(ln(e),t);if(!n||1!==Math.max(...n.keys()))return null;const s=n.get(1);return!Tt(s)||s.q.isZero?null:{a:s.q,node:e}}function Zr(e){return it(e)&&"^"===e.op&&st(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 Fr(e,t,n){const[s,i]=t.args,r=yn(ln(s)).map(dn).map(Zr),o=(e,...t)=>it(e.base)&&t.includes(e.base.op),a=(s,i,r,o={})=>({node:r,steps:[e.step(s,i,["rewrite"],t,r,{v:n,...o})]});if(2===r.length&&r.every(e=>1===e.n)){const e=r.find(e=>it(e.base)&&"^"===e.base.op&&"sym"===e.base.args[0].type&&"e"===e.base.args[0].token),t=r.find(e=>o(e,"sin","cos")),s=e&&Cr(e.base.args[1],n),i=t&&Cr(t.base.args[0],n);if(s&&i){const[n,r]=[s.a,i.a],o=n.mul(n).add(r.mul(r)),[u,l]=[nt("sin",[i.node]),nt("cos",[i.node])],c="sin"===t.base.op?nt("-",[nt("*",[jr(n),u]),nt("*",[jr(r),l])]):nt("+",[nt("*",[jr(n),l]),nt("*",[jr(r),u])]);return a("integrate.parts-twice","By parts twice",cn(nt("/",[nt("*",[e.base,c]),jr(o)])),{e:e.base,t:t.base})}}if(2===r.length&&r.every(e=>1===e.n&&o(e,"sin","cos")&&Cr(e.base.args[0],n))&&r[0].base.args[0].s!==r[1].base.args[0].s){const[e,t]="sin"===r[0].base.op?r:[r[1],r[0]],[n,s]=[e.base.args[0],t.base.args[0]],o=(e,t)=>nt(e,[nt(t,[n,s])]);let u;u="sin"===e.base.op&&"cos"===t.base.op?nt("+",[o("sin","+"),o("sin","-")]):"cos"===e.base.op?nt("+",[o("cos","-"),o("cos","+")]):nt("-",[o("cos","-"),o("cos","+")]);return a("integrate.product-to-sum","Product to sum",cn(Ir(nt("/",[u,zr(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[t,s]of[[l,"sin"],[u,"cos"]]){if(!t||t.n<3||t.n%2==0)continue;const o=t.base.args[0],u=(t.n-1)/2,l=r.filter(e=>e!==t).map(e=>nt("^",[e.base,zr(e.n)])),c=[...l,nt("^",[nt("-",[zr(1),nt("^",[nt(s,[o]),zr(2)])]),zr(u)]),nt(t.base.op,[o])].reduce((e,t)=>nt("*",[e,t])),p=cn(Ir(c,i)),h=a("integrate.odd-power","An odd power",p,{f:t.base,other:nt(s,[o])});if("sym"!==o.type||o.token!==n)return h;const f="u"===n?"t":"u",d=l.length?r.find(e=>e!==t).n:0;if(2*u+d>100)throw new ft(`a power this high (${t.n+d}) is not integrated here`);const m="sin"===t.base.op?-1:1,g=nt(s,[o]),v=nt("*",[nt("^",[nt("-",[zr(1),nt("^",[Ge(f),zr(2)])]),zr(u)]),nt("^",[Ge(f),zr(d)])]),b=cn(Ir(m<0?nt("neg",[v]):v,Ge(f))),y=ci(ui(ln(v)),f);if(!y)return h;const w=[...y].map(([e,t])=>nt("*",[dn(t),nt("/",[nt("^",[g,zr(e+1)]),zr(e+1)])])).reduce((e,t)=>nt("+",[e,t])),x=cn(m<0?nt("neg",[w]):w);return{node:x,steps:[...h.steps,e.step("integrate.u-substitution","Substitute",["substitute"],p,b,{u:Ge(f),inside:g,du:m<0?nt("neg",[t.base]):t.base,v:n}),e.step("integrate.back","Back to "+n,["substitute"],b,x,{u:Ge(f),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===n){const{base:e,n:t}=r[0],n=e.args[0],s="sec"===e.op?nt("tan",[n]):nt("cot",[n]),o=nt("/",[nt("*",[nt("^",[e,zr(t-2)]),s]),zr(t-1)]),u=nt("*",[nt("/",[zr(t-2),zr(t-1)]),Ir(nt("^",[e,zr(t-2)]),i)]);return a("integrate.reduction","Reduction formula",cn(nt("+",["sec"===e.op?o:nt("neg",[o]),u])),{f:e,n:zr(t)})}const p=e=>{if(!it(e)||"sqrt"!==e.op)return null;const t=ci(ln(e.args[0]),n);if(!t||2!==t.size||!t.has(2)||!t.has(0))return null;const[s,i]=[t.get(2),t.get(0)];return!Tt(s)||!Tt(i)||s.q.sign>=0||i.q.sign<=0?null:{k:s.q.neg(),c:i.q,root:e}},h=Ge(n),f=e=>nt("sqrt",[jr(e)]),d=p(s),m=it(s)&&"/"===s.op&&st(s.args[0])&&1===s.args[0].value?p(s.args[1]):null;if(d||m){const{k:e,c:t,root:n}=d??m,s=nt("arcsin",[nt("*",[h,f(e.div(t))])]);return a("integrate.trig-substitution","A trig substitution",cn(d?nt("+",[nt("/",[nt("*",[h,n]),zr(2)]),nt("*",[nt("/",[jr(t),nt("*",[zr(2),f(e)])]),s])]):nt("/",[s,f(e)])),{x:h,a:cn(f(t.div(e)))})}return null}const Br=(e,t)=>{const n=Array.from({length:e.length+t.length-1},()=>bt.ZERO);return e.forEach((e,s)=>t.forEach((t,i)=>{n[s+i]=n[s+i].add(e.mul(t))})),n},Dr=(e,t)=>e.map(e=>e.mul(t)),Pr=(e,t)=>Array.from({length:Math.max(e.length,t.length)},(n,s)=>(e[s]??bt.ZERO).sub(t[s]??bt.ZERO));function Rr(e,t,n){return e.s===t.s?n:it(e)?nt(e.op,e.args.map(e=>Rr(e,t,n))):e}const _r=(e,t)=>{const n=ci(e,t);return Boolean(n)&&[...n.values()].every(e=>!pi(e,t))&&Math.max(...n.keys())>=1};function Vr(e,t,n,s,i,r){if([s,i].some(e=>br(e).inf))return function(e,t,n,s,i,r){const o=[s,i].map(e=>br(e)),a=e=>e.inf?e.inf*(1/0):Bs(e.fin,{digits:20}).number,[u,l]=o.map(a).sort((e,t)=>e-t);for(const t of r?Wr(r,n):[]){let s=[];try{s=e.solve(nt("=",[t,Xe("0")]),n,{steps:!1}).solutions}catch{continue}for(const t of s){const s=Bs(t,{digits:20});if(Number.isFinite(s.number)&&!s.im&&s.number>u&&s.number<l)throw new ft(`the integrand has no value at ${n} = ${e.format(t)}, between the limits: split the integral there`)}}const c=(s,i,r)=>{if(!i.inf)try{const e=cn(Zi(t,n,s));if(Number.isFinite(Bs(e,{digits:15}).number))return e}catch{}const o=e.limit(t,n,s,{steps:!1,side:i.inf?void 0:r});if(!o.exists)throw new ft(`the integral diverges: as ${n} → ${e.format(s)}, ${e.format(t)} has no limit (${o.reason})`);if(o.infinite)throw new ft(`the integral diverges: as ${n} → ${e.format(s)}, ${e.format(t)} goes to ${o.text}`);return o.result},p=a(o[0])<a(o[1]),[h,f]=[c(s,o[0],p?"right":"left"),c(i,o[1],p?"left":"right")],d=cn(nt("-",[f,h])),m=nt("-",[f,h]);return{value:d,step:e.step("integrate.improper","Limits at the ends",["evaluate"],t,m,{a:s,b:i,F:t,v:n})}}(e,t,n,s,i,r);if(r&&!vn(s).size&&!vn(i).size){const o=Bs(s,{digits:20}).number,a=Bs(i,{digits:20}).number,u=[...vn(r)].filter(e=>e!==n);if(!u.length){const[s,i]=o<=a?[o,a]:[a,o];for(const o of Wr(r,n)){let r=[];try{r=e.solve(nt("=",[o,Xe("0")]),n,{steps:!1}).solutions}catch{continue}for(const o of r){const r=Bs(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 ft(`the integrand has no value at ${n} = ${e.format(o)}, between the limits, so F(b) - F(a) would be wrong`);let a=NaN;try{a=Bs(cn(Zi(t,n,o)),{digits:15}).number}catch{}if(!Number.isFinite(a))throw new ft(`the integral diverges at ${n} = ${e.format(o)}: F has no value at that limit`)}}}for(let e=0;!u.length&&e<=64;e++){const t=o+(a-o)*(e+.5)/65;try{const e=Bs(Zi(r,n,Xe(t.toFixed(15))),{digits:15}).number;if(!Number.isFinite(e))throw new ft("not finite")}catch(e){throw new ft(`the integrand has no value at ${n} = ${t.toPrecision(6)}, between the limits, so F(b) - F(a) would be wrong`)}}}const o=e=>cn(Zi(t,n,e)),a=cn(nt("-",[o(i),o(s)])),u=nt("-",[o(i),o(s)]);return{value:a,step:e.step("integrate.evaluate","Between the limits",["evaluate"],t,u,{a:s,b:i,F:t,v:n})}}function Wr(e,t){const n=[],s={tan:"cos",sec:"cos",csc:"sin",cot:"sin"};return pt(e,"pre").forEach(({node:e})=>{if(!it(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&&it(e.args[1])&&"neg"===e.args[1].op?i=e.args[0]:s[e.op]&&(i=nt(s[e.op],[e.args[0]])),i&&vn(i).has(t)&&!n.some(e=>e.s===i.s)&&n.push(i)}),n}const Ur={"=":1,"≠":1,"<":1,">":1,"≤":1,"≥":1,"+":2,"-":2,"±":2,"*":3,"/":3,neg:4,pm:4,"^":5},Hr={pi:"π","≤":"≤","≥":"≥"};function Kr(e){return Xr(e).text}function Jr(e,t,n=!1){return e.prec<t||n&&e.prec===t?`(${e.text})`:e.text}const Qr=e=>"op"===e.type?e.op:null,Yr=e=>e.text.startsWith("-"),Gr={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]};function Xr(e){if("num"===e.type)return{text:e.token,prec:e.token.startsWith("-")?4:9};if("sym"===e.type)return{text:Hr[e.token]??e.token,prec:9};const t=e.args.map(Xr),n=Ur[e.op];switch(e.op){case"+":case"-":case"±":{const s="+"===e.op&&["+","-"].includes(Qr(e.args[1])),i=Yr(t[1])?`(${t[1].text})`:s?t[1].text:Jr(t[1],n,!0);return{text:`${Jr(t[0],n)} ${"±"===e.op?"±":e.op} ${i}`,prec:n}}case"*":{const s=Jr(t[0],n),i=Yr(t[1])?`(${t[1].text})`:"*"===Qr(e.args[1])?t[1].text:Jr(t[1],n,!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:n}}case"/":return{text:`${Jr(t[0],n)}/${Jr(t[1],n,!0)}`,prec:n};case"^":return{text:`${Jr(t[0],n+1)}^${Jr(t[1],n)}`,prec:n};case"neg":return{text:`-${Jr(t[0],3)}`,prec:4};case"pm":return{text:`±${Jr(t[0],4)}`,prec:4};case"!":return{text:`${Jr(t[0],9)}!`,prec:6};case"abs":return{text:`|${t[0].text}|`,prec:9};case"root":return{text:`root(${t[0].text}, ${t[1].text})`,prec:9};case"der":return"op"===e.args[1].type&&"="===e.args[1].op?{text:`d/d${t[1].text.split(" = ")[0]} (${t[0].text}) at ${t[1].text}`,prec:1}:{text:`d/d${t[1].text} (${t[0].text})`,prec:6};case"int":return{text:4===t.length?`∫ from ${t[2].text} to ${t[3].text} of ${t[0].text} d${t[1].text}`:`∫ ${t[0].text} d${t[1].text}`,prec:1};case"|":return{text:`${t[0].text} or ${t[1].text}`,prec:0};case"_":return{text:`${Jr(t[0],9)}_${t[1].prec>=9&&!/\s/.test(t[1].text)?t[1].text:`(${t[1].text})`}`,prec:9};case"()":case"[]":case"{}":case"(]":case"[)":return{text:`${Gr[e.op][0]}${t.map(e=>e.text).join(", ")}${Gr[e.op][1]}`,prec:9};case"&":return{text:`${t[0].text} and ${t[1].text}`,prec:0};default:return void 0!==n?{text:`${Jr(t[0],n)} ${e.op} ${Jr(t[1],n,!0)}`,prec:n}:{text:`${e.op.replace(/^\\:?/,"")}(${t.map(e=>e.text).join(", ")})`,prec:9}}}const eo=['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'],to=['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'],no=new Set(["<",">","≤","≥"]),so=new Set(["sin","cos","tan","sec","csc","cot"]),io=new Set(["arcsin","arccos","arctan","arcsec","arccsc","arccot"]),ro={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."},oo=["normal","rewrite","simplify","expand","factor","cancel","diff","differentiate","integrate","solve","solveSystem","substitute","approximate","equivalent","limit"];class ao{constructor(e,t,n,s,i){this.set=e,this.messages=t,this.format=n,this.read=s,this.complex=i;for(const e of oo){const t=ao.prototype[e];this[e]=(...e)=>St(i,()=>t.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 ot(e);if("string"!=typeof e)throw new ft("expected an expression");if(this.read){const t=this.read(e);return Array.isArray(t)?ot(t):"string"==typeof t?rt(t):t}return rt(e)}atPoints(e){if(!e||!it(e)||!e.s.includes("= der"))return e;const t=e.args.map(e=>this.atPoints(e)),[n,s]=t;if("der"===e.op&&it(s)&&"="===s.op&&"sym"===s.args[0].type){const e=s.args[0].token;return this.substitute(this.diff(n,e).result,{[e]:s.args[1].s}).result}return nt(e.op,t)}step(e,t,n,s,i,r={}){return function(e,t,n,s,i,r,o,a,u=[]){const l=(r??"").replace(/\{(\w+)\}/g,(e,t)=>{const n=o?.[t];return void 0===n?e:"string"==typeof n?n:a(n)});return{id:e,name:t,tags:n,from:s.s,to:i.s,path:u,before:s.s,after:i.s,explanation:l}}(e,t,n,s,i,this.messages[e]??"",r,this.format)}result(e,t,n,s={}){let i=e;if(n.approximate&&i){i=Rs(i,{digits:"number"==typeof n.approximate?n.approximate:15})}return{result:i,text:i?this.format(i):"",steps:ri(t,ii(n.steps)),...s}}variable(e,t){if(t&&!/^\\?[A-Za-z\u0370-\u03FF][A-Za-z0-9_\u0370-\u03FF′]*$/.test(t))throw new ft(`"${t}" is not a variable name; for a derivative at a point write der(f, x = a)`);if(t)return t;const n=[...vn(e)];return 1===n.length?n[0]:n.includes("x")?"x":n[0]??"x"}tidyStep(e,t){return e.s===t.s?[]:[this.step("normal","Work out and collect",["tidy","arithmetic"],e,t)]}normal(e){return cn(this.node(e))}rewrite(e,t,n={}){const s=this.node(e),i=this.set.view(t);if(!i.size)throw new ft(`no rules in mode "${t}" (modes: ${this.set.modes().join(", ")})`);const r=ti(s,i,{format:this.format,order:n.order,variable:n.variable});return this.result(r.node,[...this.tidyStep(s,cn(s)),...r.steps],n)}simplify(e,t={}){const n=this.node(e),s=[...this.tidyStep(n,cn(n))],i=ti(n,this.set.view("simplify"),{format:this.format});s.push(...i.steps);let r=i.node,o=null;const a=ln(r),u=[],l=0===vn(r).size,c=l?null:Ni(a);c&&u.push({node:Mi(c),id:"simplify.cancel",name:"Cancel"});const p=ti(dn(ui(a)),this.set.view("simplify"),{format:this.format});u.push({node:p.node,id:"simplify.expand",name:"Multiply out"}),"add"!==a.k||l||u.push({node:Mi(wi(a)),id:"simplify.factor",name:"Factor"});const h=e=>pt(e,"pre").some(({node:e})=>it(e)&&so.has(e.op)&&pt(e.args[0],"pre").some(({node:e})=>it(e)&&io.has(e.op)));for(const e of xr(this,r))u.push({node:e,id:"simplify.trig",name:"Trigonometric identities",prefer:h(r)&&!h(e)});let f=!1;for(const e of u)f&&"simplify.trig"===e.id&&!e.prefer||(e.prefer&&(f=!0),(ut(e.node)<ut(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,t)}expand(e,t={}){const n=this.node(e),s=dn(ui(ln(n)));return this.result(s,n.s===s.s?[]:[this.step("expand","Multiply out",["expand"],n,s)],t)}factor(e,t={}){const n=this.node(e),s=wi(ln(n)),i=Mi(s),r=[],o=s.notes.find(e=>"factor.common"===e.id);return i.s!==cn(n).s&&r.push(this.step(o?"factor.common":"factor","Factor",["factor"],n,i,o?{common:dn(o.values.common)}:{})),this.result(i,r,t)}cancel(e,t={}){const n=this.node(e),s=ln(n),i=Ni(s);if(!i)return this.result(cn(n),this.tidyStep(n,cn(n)),t);const r=Mi(i),o=Ai(s),a=nt("/",[dn(o.num),dn(o.den)]),u=[];return"/"===n.op&&a.s===cn(n).s||u.push(this.step("together","One fraction",["together"],n,a)),r.s!==a.s&&u.push(this.step("cancel","Cancel",["cancel"],a,r,{canceled:i.canceled.length?i.canceled.map(e=>this.format(dn(e))).join(", "):"numbers"})),this.result(r,u,t)}diff(e,t,n={}){const s=this.node(e),i=this.variable(s,t);let r=s;const o=[];for(let e=0;e<(n.order??1);e++){const e=ti(nt("der",[r,Ge(i)]),this.set.view("differentiate"),{format:this.format,order:"pre"}),t=ti(e.node,this.set.view("simplify"),{format:this.format});o.push(...e.steps,...t.steps),r=t.node}return this.result(r,o,n,{variable:i})}differentiate(e,t){const n=ti(nt("der",[e,Ge(t)]),this.set.view("differentiate"),{format:this.format,order:"pre"});return ti(n.node,this.set.view("simplify"),{format:this.format}).node}integrate(e,t,n={}){let s=this.node(e);const i=e=>void 0===e?null:this.node("number"==typeof e?String(e):e);let r=i(n.from),o=i(n.to);if(it(s)&&"int"===s.op){const[e,n,i,a]=s.args;t=n.token,i&&a&&(r=i,o=a),s=e}const a=this.variable(s,t),u=Tr(this,s,a),l=ti(u.node,this.set.view("simplify"),{format:this.format}),c=[...u.steps,...l.steps];if(r&&o){const e=Vr(this,l.node,a,r,o,s);c.push(e.step);const t=ti(e.value,this.set.view("simplify"),{format:this.format});return c.push(...t.steps),this.result(t.node,c,n,{antiderivative:l.node,variable:a})}let p=l.node;return n.constant&&(p=nt("+",[p,Ge(String(n.constant))])),this.result(p,c,n,{variable:a})}solve(e,t,n={}){const s=this.node(e),i=this.variable(s,t);if(it(s)&&no.has(s.op))return this.inequality(s,i,n);const r=Li(this,s,i,n);let o=r.solutions;if(n.approximate){const e="number"==typeof n.approximate?n.approximate:15;o=o.map(t=>Rs(t,{digits:e}))}const a=o.map(e=>nt("=",[Ge(i),e])),u=a.length?a.reduce((e,t)=>e?nt("|",[e,t]):t,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:ri(r.steps,ii(n.steps))}}inequality(e,t,n){const s=Gi(this,e,t),i={solutions:[],variable:t,unsolved:[],always:!1,steps:ri(s.steps,ii(n.steps))};if(!s.pieces)return{...i,pieces:null,intervals:"",result:null,unsolved:[e],text:`no exact solution found for ${t}`};const r=Ge(t),o=1===s.pieces.length&&!s.pieces[0].lo&&!s.pieces[0].hi,a=s.pieces.map(({lo:e,hi:t,loClosed:n,hiClosed:s})=>e&&t&&e.s===t.s?nt("=",[r,e]):e||t?e?t?nt(s?"≤":"<",[nt(n?"≤":"<",[e,r]),t]):nt(n?"≥":">",[r,e]):nt(s?"≤":"<",[r,t]):null).filter(Boolean).reduce((e,t)=>e?nt("|",[e,t]):t,null),u=s.pieces.length?s.pieces.map(({lo:e,hi:t,loClosed:n,hiClosed:s})=>e&&t&&e.s===t.s?`{${this.format(e)}}`:`${n?"[":"("}${e?this.format(e):"-∞"}, ${t?this.format(t):"∞"}${s?"]":")"}`).join(" ∪ "):"∅",l=o?`true for every ${t}`:a?this.format(a):"no solution";return{...i,pieces:s.pieces,intervals:u,result:a,always:o,text:l}}limit(e,t,n,s={}){null==n||"object"!=typeof n||Array.isArray(n)||n.type||(s=n,n=void 0);const i=this.node(e),r=vr(i);if(!r&&pt(i,"pre").some(({node:e})=>vr(e))){let e=i;for(const{node:t,path:n}of pt(i,"post").filter(({node:e})=>vr(e)).reverse()){const s=this.limit(t,void 0,void 0,{steps:!1});if(!s.exists)return s;if(s.infinite)throw new ft("a limit inside an expression that is infinite is not worked out here");e=ht(e,n,s.result)}return{...this.simplify(e,s),exists:!0,infinite:!1}}const o=r?r.f:i,a=r?r.v:this.variable(i,t),u=r?r.to:"number"==typeof n?Xe(String(n)):this.node(n??"0"),l="right"===s.side||"+"===s.side?1:"left"===s.side||"-"===s.side?-1:r?r.side:0;try{const{value:e,steps:t}=hr(this,o,a,br(u),l);return{...this.result((c=e,c.inf?c.inf>0?ir:Ge("-∞"):c.fin),t,s),exists:!0,infinite:Boolean(e.inf)}}catch(e){if(!(e instanceof er))throw e;return{result:null,text:"does not exist",exists:!1,reason:e.message,steps:[]}}var c}solveSystem(e,t,n={}){const s=e.map(e=>this.node(e)),i=t??[...new Set(s.flatMap(e=>[...vn(e)]))].sort(),r=function(e,t,n){const s=[],i=t.map(t=>{const s=Ti(t)?_t([ln(t.args[0]),nn(ln(t.args[1]))]):ln(t),i=n.map(t=>{const n=ci(s,t);if(!n||Math.max(0,...n.keys())>1)throw new ft(`not linear in ${t}`);const i=n.get(1)??At(bt.ZERO);if(!Tt(i))throw new ft(`the coefficient of ${t} must be a number (it is ${e.format(dn(i))})`);return i.q});let r=s;for(let e=0;e<n.length;e++)r=_t([r,Wt([At(i[e].neg()),ln(Ge(n[e]))])]);for(const e of n)if(pi(r,e))throw new ft(`not linear in ${e}`);return{coeffs:i,rhs:nn(r)}}),r=()=>i.map(e=>Ei(dn(_t(e.coeffs.map((e,t)=>Wt([At(e),ln(Ge(n[t]))])))),dn(e.rhs))).reduce((e,t)=>e?nt("&",[e,t]):t,null);let o=0;const a=[];for(let t=0;t<n.length&&o<i.length;t++){const u=i.findIndex((e,n)=>n>=o&&!e.coeffs[t].isZero);if(u<0)continue;[i[o],i[u]]=[i[u],i[o]];const l=r(),c=i[o],p=c.coeffs[t];c.coeffs=c.coeffs.map(e=>e.div(p)),c.rhs=Wt([At(p.inv()),c.rhs]);for(let e=0;e<i.length;e++){if(e===o||i[e].coeffs[t].isZero)continue;const n=i[e].coeffs[t];i[e].coeffs=i[e].coeffs.map((e,t)=>e.sub(n.mul(c.coeffs[t]))),i[e].rhs=_t([i[e].rhs,Wt([At(n.neg()),c.rhs])])}s.push(e.step("system.eliminate","Eliminate",["eliminate"],l,r(),{v:Ge(n[t])})),a.push(t),o++}for(const e of i.slice(o))if(!Tt(e.rhs)||!e.rhs.q.isZero)return{solution:null,steps:s,status:"none"};if(a.length<n.length)return{solution:null,steps:s,status:"many"};const u=new Map;return a.forEach((e,t)=>u.set(n[e],dn(i[t].rhs))),{solution:u,steps:s,status:"one"}}(this,s,i),o=r.solution?Object.fromEntries([...r.solution].map(([e,t])=>[e,t])):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:ri(r.steps,ii(n.steps))}}substitute(e,t,n={}){const s=this.node(e);let i=s;for(const[e,n]of Object.entries(t))i=Zi(i,e,"number"==typeof n?this.node(String(n)):this.node(n));const r=this.simplify(i,n),o=[this.step("substitute","Substitute",["substitute"],s,i)];return{...r,steps:[...ri(o,ii(n.steps)),...r.steps]}}defined(e){const t=this.set.view("define");return t.size?ti(e,t,{format:this.format}).node:e}approximate(e,t={}){const n=this.defined(this.node(e));if(vn(n).size&&!t.scope){const e=Rs(cn(n),t);return{result:e,text:this.format(e),number:null,exact:!1}}const s=Bs(n,t);return{result:s.node,text:s.text,number:s.number,re:s.re,im:s.im,exact:s.exact}}equivalent(e,t){const n=this.node(e),s=this.node(t),i=this.defined(nt("-",[n,s])),r=this.simplify(i,{steps:!1}).result;if("num"===r.type&&"0"===r.token)return{equal:!0,how:"exact"};const o=[...vn(i)];if(!o.length)try{return{equal:Math.abs(Bs(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 t=Object.fromEntries(o.map((t,n)=>[t,String(a[(e+n)%a.length]+n/7)]));let n;try{n=Bs(i,{digits:30,scope:t}).number}catch{continue}if(u++,Math.abs(n)>1e-20)return{equal:!1,how:"numeric"}}return{equal:u>0,how:"numeric"}}modes(){return this.set.modes()}}function uo(e={}){const t=!1===e.defaults?[]:[...eo,...e.complex?to:[]],{specs:n,messages:s}=function(e){Js();const t=[],n={};for(const s of e){const e="string"==typeof s?Qn(s):s,i=Array.isArray(e)?e:e?.rules??[];for(const t of(Array.isArray(e)?[]:e?.operators)??[]){if(!t?.symbol)throw new Error("an operator needs a symbol");_e(t.symbol)||De({symbol:String(t.symbol),arity:"any"===t.arity?Ze:Number(t.arity),label:t.label})}Object.assign(n,(Array.isArray(e)?null:e?.messages)??{});for(const e of i)t.push(e)}return{specs:t,messages:n}}([...t,...e.rules??[]]),i=St(e.complex,()=>Qs(n));return new ao(i,{...ro,...s},e.format??Kr,e.read??null,Boolean(e.complex))}const lo=Symbol.for("inlinemath.expressions"),co=new Map,po={re:"Re",im:"Im",conj:"overline"},ho=["Re","Im","re","im","conj","arg"];function fo(e){const t=[],s=e=>{"op"===e.type?(e.args.forEach(s),n.operator(e.op)?(-1===n.operator(e.op).arity&&t.push(String(e.args.length)),t.push(e.op)):t.push(String(e.args.length),`\\:${po[e.op]??e.op}`)):t.push(e.token)};return s(e),t}function mo(e,t){if(!t)return e;const s=new Map;for(const[e,i]of Object.entries(t))if("number"==typeof i?Number.isFinite(i):"bigint"==typeof i||"string"==typeof i)try{s.set(e,n.parse(String(i)))}catch{}if(!s.size)return e;const i=function(e){let t;try{t=n.fromPostfix(e)}catch{return new Set}const s=e=>"symbol"===e?.type?e.value:"op"===e?.type&&["=","→"].includes(e.op)&&"symbol"===e.args[0].type?e.args[0].value:null,i=new Set;return n.walk(t,e=>{if("op"!==e.type||e.args.length<2)return;const t=e.op.startsWith("\\:")?e.op.slice(2):e.op;["der","int","lim","diff","derivative","differentiate","integrate","integral","solve","limit"].includes(t)&&s(e.args[1])&&i.add(s(e.args[1]))}),i}(e);return e.flatMap(e=>s.has(e)&&!i.has(e)?s.get(e):[e])}const go={right:"right",r:"right","+":"right",left:"left",l:"left","-":"left"},vo=new Set(["simplify","expand","factor","cancel","diff","integrate","solve","approx","limit"]),bo={integral:"integrate",differentiate:"diff",approximate:"approx",simp:"simplify"};function yo(e={}){const t=e.rules||e.names?null:e.complex?"complex":"default";if(t&&co.has(t))return co.get(t);const s=[...e.names??[],...e.complex?ho:[],...vo,...Object.keys(bo)],i=uo({...e,read:e=>n.parse(e,{names:s}),format:Kr});return t&&co.set(t,i),i}const wo=e=>String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");var xo='/*\n * Inline Math stylesheet. Everything is under .mv; colors are left to the page.\n *\n * The numbers marked "metric" must match the constants at the top of\n * src/layout.js (line-height 1, bar 0.06em, gap 0.1em); everything else can\n * be changed freely.\n *\n * Handy hooks:\n * .mv-n[data-node="4"] one node (ids from MathZetta)\n * .mv-var .mv-num .mv-word variables, numbers, function names\n * .mv-op-frac .mv-op-pow … a kind of operation\n * .mv-hl the class highlight() adds\n * --mv-hl highlight color\n */\n\n.mv {\n display: inline-block;\n font-family: "Inline Math Roman", "Latin Modern Roman", "STIX Two Text", "Cambria", "Times New Roman", serif;\n font-size: 1.2em;\n font-style: normal;\n font-weight: normal;\n line-height: 1; /* metric */\n white-space: nowrap;\n text-indent: 0;\n text-align: left;\n letter-spacing: 0;\n}\n.mv-display { display: block; text-align: center; margin: 0.6em 0; }\n.mv span, .mv svg { line-height: 1; }\n.mv-n { display: inline-block; border-radius: 0.12em; }\n\n/* ---- letters and signs -------------------------------------------------- */\n.mv-var { font-style: italic; padding-right: 0.03em; }\n.mv-num, .mv-word, .mv-name, .mv-ord, .mv-text, .mv-d, .mv-conj { font-style: normal; }\n.mv-prime { margin-left: 0.04em; }\n.mv-bin { margin: 0 0.22em; }\n.mv-rel { margin: 0 0.28em; }\n.mv-conj { margin: 0 0.6em; } /* x = 2 or x = 3 */\n.mv-punct { margin-right: 0.17em; }\n.mv-sign { margin-right: 0.04em; }\n.mv-times { display: inline-block; width: 0.06em; }\n.mv-callgap { display: inline-block; width: 0.05em; }\n.mv-fnspace { display: inline-block; width: 0.17em; }\n.mv-space { display: inline-block; width: 0.33em; }\n.mv-dx { display: inline-block; margin-left: 0.17em; }\n.mv-text { margin: 0 0.25em; }\n/* Tighter spacing in limits and exponents: n=1, x→0. */\n.mv-script .mv-rel, .mv-sup .mv-rel, .mv-sub .mv-rel { margin: 0 0.12em; }\n.mv-script .mv-bin, .mv-sup .mv-bin, .mv-sub .mv-bin { margin: 0 0.1em; }\n\n/* ---- fractions (metric: padding and border) ------------------------------ */\n.mv-frac { display: inline-flex; flex-direction: column; align-items: stretch; margin: 0 0.12em; }\n.mv-numer, .mv-denom { display: block; text-align: center; padding: 0 0.1em; }\n.mv-numer { padding-bottom: 0.1em; }\n.mv-denom { padding-top: 0.1em; border-top: 0.06em solid currentColor; }\n.mv-frac-nobar > .mv-denom { border-top: 0; }\n.mv-scaled { display: inline-block; }\n\n/* ---- scripts ----------------------------------------------------------------- */\n.mv-sup, .mv-sub { display: inline-block; margin-left: 0.04em; }\n.mv-subsup, .mv-limits { display: inline-flex; flex-direction: column; justify-content: space-between; align-items: flex-start; margin-left: 0.04em; }\n.mv-limits { margin-left: 0.02em; margin-right: 0.12em; }\n.mv-limits > .mv-lower { margin-left: -0.3em; }\n.mv-script { display: block; }\n.mv-under { display: inline-flex; flex-direction: column; align-items: center; margin-right: 0.15em; }\n.mv-under > .mv-script { margin-top: 0.05em; }\n.mv-bigop { display: inline-flex; flex-direction: column; align-items: center; margin: 0 0.12em; }\n.mv-bigop > .mv-script { display: block; margin: 0.08em 0; }\n.mv-bigop > svg { display: block; }\n\n/* ---- radicals (metric: border and padding-top) ----------------------------- */\n.mv-sqrt { display: inline-block; white-space: nowrap; }\n.mv-radicand { display: inline-block; position: relative; border-top: 0.06em solid currentColor; padding: 0.1em 0.1em 0 0.06em; }\n/* the hook, in the radicand\'s left margin (layout.js sets its width and that margin): from the bar\'s center\n (just below the middle of the 0.06em border above the box) to the bottom of what it holds, so the tip always meets the bar */\n.mv-hook { position: absolute; top: -0.02em; height: calc(100% + 0.02em); overflow: visible; } /* a hair below the center: never above the bar */\n.mv-rootindex { display: inline-block; margin: 0 -0.32em 0 0.12em; }\n\n/* ---- delimiters: drawn at the full height of what they enclose -------------- */\n.mv-fence { display: inline-block; position: relative; }\n.mv-delim { position: absolute; top: 0; bottom: 0; height: 100%; }\n.mv-delim-l { left: 0.03em; }\n.mv-delim-r { right: 0.03em; }\nspan.mv-delim { width: 0.16em; border: 0 solid currentColor; box-sizing: border-box; }\n.mv-delim.mv-lbrack { border-width: 0.06em 0 0.06em 0.06em; left: 0.06em; }\n.mv-delim.mv-rbrack { border-width: 0.06em 0.06em 0.06em 0; right: 0.06em; }\n.mv-delim.mv-vert { border-left-width: 0.06em; width: 0; left: 0.07em; }\n.mv-delim.mv-vert.mv-delim-r { left: auto; right: 0.07em; }\n.mv-delim.mv-lfloor { border-width: 0 0 0.06em 0.06em; }\n.mv-delim.mv-rfloor { border-width: 0 0.06em 0.06em 0; }\n.mv-delim.mv-lceil { border-width: 0.06em 0 0 0.06em; }\n.mv-delim.mv-rceil { border-width: 0.06em 0.06em 0 0; }\n\n/* ---- shapes ----------------------------------------------------------------- */\n.mv svg { overflow: visible; }\n.mv svg path[stroke] { stroke-width: 0.065em; stroke-linecap: round; stroke-linejoin: round; }\n.mv-intsign path[stroke] { stroke-width: 0.075em; }\n.mv-bigsign { display: inline-block; margin: 0 0.06em; }\n.mv-intsign { margin-right: 0.12em; }\n\n/* ---- piecewise ------------------------------------------------------------- */\n.mv-cases { display: inline-grid; grid-template-columns: auto auto; column-gap: 1em; row-gap: 0.25em; align-items: baseline; text-align: left; margin: 0 0.1em; }\n.mv-case-value, .mv-case-cond { display: block; }\n.mv-matrix { display: inline-grid; column-gap: 0.8em; row-gap: 0.3em; align-items: baseline; justify-items: center; margin: 0 0.15em; }\n.mv-matrix-row { display: contents; }\n.mv-matrix-cell { display: block; }\n\n/* ---- decorations: \\boxed \\cancel \\overline \\vec … --------------------------- */\n.mv-boxed { display: inline-block; border: 0.06em solid currentColor; padding: 0.16em 0.2em; }\n.mv-over { display: inline-block; position: relative; padding-top: 0.14em; }\n.mv-over::before { content: \'\'; position: absolute; left: 0; right: 0; top: 0.21em; border-top: 0.06em solid currentColor; } /* metric */\n.mv-over-low::before { top: 0.48em; }\n.mv-underline { display: inline-block; border-bottom: 0.06em solid currentColor; padding-bottom: 0.06em; }\n.mv-cancel { display: inline-block; position: relative; }\n.mv-cancel-line { position: absolute; left: 0; top: 0; width: 100%; height: 100%; overflow: visible; pointer-events: none; }\n.mv-accent { display: inline-block; position: relative; padding-top: 0.3em; }\n.mv-accent-mark { position: absolute; top: -0.27em; left: 0; right: 0; text-align: center; font-size: 0.7em; line-height: 0.6; } /* metric: measured over F, h, A */\n/* ˆ ˜ ˙ ¨ are spacing marks that sit high in their em: full size, pulled down onto the letter */\n.mv-accent-hat, .mv-accent-widehat, .mv-accent-tilde, .mv-accent-dot, .mv-accent-ddot { font-size: 1em; line-height: 1; top: 0.02em; }\n/* over an italic letter the mark leans with it, right of the box\'s center */\n.mv-accent:has(> .mv-var) > .mv-accent-mark { transform: translateX(0.1em); }\n/* a letter with no ascender (x, u, α; layout.js adds -low): the mark comes down to its top */\n.mv-accent-low > .mv-accent-mark { top: 0.08em; }\n.mv-accent-low > .mv-accent-hat, .mv-accent-low > .mv-accent-widehat, .mv-accent-low > .mv-accent-tilde, .mv-accent-low > .mv-accent-dot, .mv-accent-low > .mv-accent-ddot { top: 0.31em; }\n\n/* ---- interaction -------------------------------------------------------------- */\n.mv-hl { background: var(--mv-hl, rgba(255, 200, 0, 0.35)); box-shadow: 0 0 0 0.08em var(--mv-hl, rgba(255, 200, 0, 0.35)); }\n/* Windows high contrast (and other forced colors) drops backgrounds and shadows: outline a highlight instead */\n@media (forced-colors: active) {\n .mv-hl { outline: 0.08em solid Highlight; outline-offset: 0.04em; }\n}\n.mv-clickable .mv-n { cursor: pointer; }\n.mv-editable .mv-n:hover { outline: 1px dashed rgba(0, 0, 0, 0.25); }\n/* the box editing a part in place (view.editable, or a Markdown textbox variable) */\n.mv-edit { transform: translateY(-50%); z-index: 1000; box-sizing: content-box; padding: 0.1em 0.35em; font-family: inherit;\n border: 1px solid #1a5fb4; border-radius: 0.25em; background: #fff; color: #111; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.18); }\n.mv-edit[aria-invalid="true"] { border-color: #c33; outline: 2px solid #c33; }\n/* the live region a view announces steps through ({ announce: true }): read, never seen */\n.mv-sr-only, .mv-sr-math { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }\n.mv-clickable .mv-n:hover { outline: 1px dashed rgba(0, 0, 0, 0.25); }\n/* the keyboard: the expression is one tab stop, and the part the arrow keys are on is ringed */\n.mv[tabindex]:focus-visible { outline: 0.1em solid #1a5fb4; outline-offset: 0.12em; }\n.mv[tabindex]:focus .mv-focus { outline: 0.1em solid #1a5fb4; outline-offset: 0.06em; border-radius: 0.1em; }\n/* while a part is ringed, the whole expression\'s ring steps back so the part is the one that stands out */\n.mv[tabindex]:focus-visible:has(.mv-focus) { outline: 1px dashed #1a5fb4; }\n@media (forced-colors: active) {\n .mv[tabindex]:focus-visible, .mv[tabindex]:focus .mv-focus { outline-color: Highlight; }\n}\n\n/* ---- steps (stepsHTML from \'@mathzetta/inlinemath/cas\') ---------------------------------------- */\n.mv-steps { margin: 0; padding-left: 1.6em; }\n.mv-step { margin: 0.5em 0 0.9em; }\n.mv-step-name { display: block; font-size: 0.85em; font-weight: 600; color: #555; }\n.mv-step-maths { display: flex; flex-wrap: wrap; align-items: center; gap: 0.4em 0.8em; margin: 0.15em 0; }\n.mv-step-arrow { color: #888; }\n.mv-step-why { margin: 0.1em 0 0; font-size: 0.9em; color: #444; }\n\n/* ---- Markdown with math (markdownToHTML from \'@mathzetta/inlinemath/markdown\') ------------------- */\n.mv-md-math { display: inline-block; vertical-align: middle; }\n.mv-md-display { display: block; text-align: center; margin: 0.6em 0; overflow-x: auto; }\n.mv-md-block { margin: 0.8em 0; }\n.mv-md-error code { background: rgba(200, 60, 0, 0.08); color: #a33; border-bottom: 1px dotted #a33; }\n/* saved variables: $A := 2+2$ draws A ≔ 2 + 2; $A := [[…]]$ an input that sets A */\n.mv-md-input-def { display: inline-flex; align-items: center; gap: 0.3em; }\n.mv-md-assign { margin: 0 0.1em; }\n.mv-md-input { font: inherit; font-size: 0.9em; }\ninput.mv-md-textbox { font-family: inherit; padding: 0.05em 0.3em; field-sizing: content; min-width: 3ch; }\ninput.mv-md-textbox[aria-invalid="true"] { outline: 2px solid #c33; outline-offset: 1px; }\ninput.mv-md-slider { vertical-align: middle; }\n.mv-md-output { font-variant-numeric: tabular-nums; min-width: 2ch; }\n';const ko=xo;if("undefined"!=typeof document&&!document.getElementById("inlinemath-css")){const e=document.createElement("style");e.id="inlinemath-css",e.textContent=xo,document.head.append(e)}return Object.defineProperty(e,"toText",{enumerable:!0,get:function(){return i.toText}}),e.CSS=ko,e.DEFAULTS=M,e.PATHS=r,e.View=G,e.casBlocks=function(e={}){const n=e.cas??yo(),s=void 0===e.steps?{}:{steps:e.steps},r=(e,o)=>{let a;try{a=n.read(e)}catch{return t.calculateBlock(e,o)}const u=o&&o[lo];u&&(a=a.flatMap(e=>Object.hasOwn(u,e)?u[e]:[e])),a=mo(a,o);const l=a[a.length-1],c=l?.startsWith("\\:")?bo[l.slice(2)]??l.slice(2):null,p=c&&vo.has(c),h="der"===l||"int"===l||"lim"===l;if(!p&&!h)return t.calculateBlock(e,o);const f=n.node(a),d=h&&f.op!==l,m=p?f.args:[f],g=e=>e?e.s:void 0,v=(e,t,i)=>{if(!t||"="!==t.op)return n.diff(e,g(t),{...s,order:i});const r=t.args[0].s,o=n.diff(e,r,{...s,order:i}),a=n.substitute(o.result,{[r]:t.args[1].s},s);return{...a,steps:[...o.steps??[],...a.steps??[]]}};let b;try{switch(d?"simplify-read":p?c:"der"===l?"derivative":"lim"===l?"lim":"antiderivative"){case"simplify-read":b=n.simplify(f,s);break;case"simplify":b=n.simplify(m[0],s);break;case"expand":b=n.expand(m[0],s);break;case"factor":b=n.factor(m[0],s);break;case"cancel":b=n.cancel(m[0],s);break;case"diff":b=v(m[0],m[1],m[2]?Number(m[2].s):1);break;case"integrate":b=n.integrate(m[0],g(m[1]),{...s,...m[3]?{from:m[2].s,to:m[3].s}:{}});break;case"solve":b=n.solve(m[0],g(m[1]),s);break;case"lim":b=n.limit(f,void 0,void 0,s);break;case"limit":b=(([e,t,i,r])=>{let o=r?go[r.s.replace(/^\\/,"")]:void 0;if(r&&!o)throw new Error(`a side is right or left, not ${r.s}`);if(t&&"→"===t.op){[t,i]=t.args;const e="^"===i.op?i.args[1].s.replace(/^\\/,""):null;"+"!==e&&"-"!==e||(o=go[e],i=i.args[0])}return n.limit(e,g(t),i,{...s,...o?{side:o}:{}})})(m);break;case"approx":b=n.approximate(m[0],{...s,digits:m[1]?Number(m[1].s):15});break;case"derivative":b=v(f.args[0],f.args[1],1);break;default:b=n.integrate(f,void 0,s)}}catch(t){return`(${e})`}if(r.last=b,!b.result)return`"${b.text}"`;const y=i.toText(fo(b.result));return/^-?\d+(\.\d+)?$/.test(y)?y:`(${y})`};return r},e.createVariables=fe,e.extractMath=ge,e.layout=I,e.markdownToHTML=function(e,t={}){return Te(we(e,t,t.variables||null),t)},e.mathCAS=yo,e.nodeAt=R,e.numberTree=V,e.pathOf=_,e.render=function(e,t,n={}){return new G(e,t,n)},e.renderMarkdown=Ie,e.renderMarkdownInto=function(e,t,n={}){const s=void 0===n.variables?de:n.variables||null;ze();const i=Le.get(e);i&&i.stop(i.store!==s);let r=we(t,n,s,e);if(e.innerHTML=Te(r,n),!s)return Le.delete(e),e;s.own(e,r.defs);let o=e.isConnected;const a=t=>{const i=t.target,r=i&&i.dataset&&i.dataset.mvVar;if(void 0!==r&&e.contains(i)){if("text"===i.type)try{K(i.value,{blocks:n.blocks,scope:{}}),i.removeAttribute("aria-invalid")}catch{return void i.setAttribute("aria-invalid","true")}s.set(r,i.value)}},u=i=>{const o=i.target.closest?.("[data-node]"),a=o&&o.closest("[data-mv-md]");if(!a||!e.contains(a))return;const u=Number(a.dataset.mvMd),l=r.trees[u];if(!l)return;const c=Number(o.dataset.node),p=_(l,c)||[];let h=null;for(let e=p.length;e>=0&&!h;e--){const t=R(l,p.slice(0,e));t&&void 0!==t.from&&(h={node:t,depth:e})}const f=h&&s.definitions().get(h.node.from);if(f&&f.input&&"textbox"===f.input.kind){i.preventDefault();const t=f.name,r=e.ownerDocument.querySelector(`[data-mv-var="${CSS.escape(t)}"]`),a=n.editable&&n.editable.toText;if(!a)return void(r&&(r.focus(),r.select()));const u=e=>K(e),c=R(l,p);return void Y(o,a(re(c,u)),{label:`Edit ${t}`,parse:e=>K(e,{blocks:n.blocks}),commit:e=>{const n=Q(re(h.node,u),p.slice(h.depth),e);s.set(t,a(n))}})}const d=f&&r.defs.get(f.name),m=d&&d.key===f.key&&void 0!==d.start?{...r.math[u],start:d.start,end:d.end,raw:t.slice(d.start,d.end)}:r.math[u];e.dispatchEvent(new CustomEvent("inlinemath:select",{bubbles:!0,detail:{index:u,start:m.start,end:m.end,raw:m.raw,source:m.source,id:c,path:p}}))};e.addEventListener("input",a),e.addEventListener("change",a),e.addEventListener("dblclick",u);const l=s.subscribe(i=>{i!==e&&(e.isConnected?(o=!0,ze(),(()=>{const i=we(t,n,s,e);i.drawn.forEach((t,n)=>{if(t===r.drawn[n]||i.inputs.has(n))return;const s=e.querySelector(`[data-mv-md="${n}"]`);s&&(s.outerHTML=t)});for(const t of e.querySelectorAll("[data-mv-var], [data-mv-out]")){const e=i.defs.get(t.dataset.mvVar??t.dataset.mvOut);if(!e)continue;const n=s.textOf(e);void 0!==t.dataset.mvOut?t.textContent=n:t.value!==n&&t!==t.ownerDocument?.activeElement&&(t.value=n)}r=i})()):o&&c(!0))});function c(t){l(),e.removeEventListener("input",a),e.removeEventListener("change",a),e.removeEventListener("dblclick",u),je.delete(p),Le.delete(e),t&&s.own(e,null)}const p={element:e,store:s,stop:c,connected:()=>o};return je.add(p),Le.set(e,p),e},e.select=D,e.shouldAnimate=ee,e.signature=B,e.stepsHTML=function(e,t={}){return`<ol class="mv-steps">${e.map(e=>{const n=J(fo(rt(e.from)),{...t,highlight:e.path&&e.path.length?{path:e.path}:void 0}),s=e.to===e.from?"":`<span class="mv-step-arrow" aria-label="becomes">⟶</span>${J(fo(rt(e.to)),t)}`,i=e.explanation?`<p class="mv-step-why">${wo(e.explanation)}</p>`:"";return`<li class="mv-step" data-rule="${wo(e.id)}"><span class="mv-step-name">${wo(e.name)}</span><div class="mv-step-maths">${n}${s}</div>${i}</li>`}).join("")}</ol>`},e.toHTML=J,e.tokensOf=fo,e.treeOf=K,e.variables=de,e}({},MathZetta,MathZetta,MathZetta,MathZetta);
1
+ /* Inline Math 0.4.2 — MIT license; MathZetta not included: load a MathZetta <script> (mathzetta.min.js or mathzetta.maths-display.min.js) first */
2
+ var InlineMath=function(e,t,n,s,i){"use strict";const r={"(":{fill:"M0.92,0 C0.1,0.2 0.1,0.8 0.92,1 L1,0.975 C0.48,0.75 0.48,0.25 1,0.025 Z"},")":{fill:"M0.08,0 C0.9,0.2 0.9,0.8 0.08,1 L0,0.975 C0.52,0.75 0.52,0.25 0,0.025 Z"},"{":{fill:"M1,0 C0.45,0 0.5,0.05 0.5,0.2 L0.5,0.38 C0.5,0.46 0.35,0.49 0.05,0.5 C0.35,0.51 0.5,0.54 0.5,0.62 L0.5,0.8 C0.5,0.95 0.45,1 1,1 L1,0.985 C0.68,0.985 0.64,0.95 0.64,0.8 L0.64,0.62 C0.64,0.53 0.55,0.505 0.3,0.5 C0.55,0.495 0.64,0.47 0.64,0.38 L0.64,0.2 C0.64,0.05 0.68,0.015 1,0.015 Z"},"}":{fill:"M0,0 C0.55,0 0.5,0.05 0.5,0.2 L0.5,0.38 C0.5,0.46 0.65,0.49 0.95,0.5 C0.65,0.51 0.5,0.54 0.5,0.62 L0.5,0.8 C0.5,0.95 0.55,1 0,1 L0,0.985 C0.32,0.985 0.36,0.95 0.36,0.8 L0.36,0.62 C0.36,0.53 0.45,0.505 0.7,0.5 C0.45,0.495 0.36,0.47 0.36,0.38 L0.36,0.2 C0.36,0.05 0.32,0.015 0,0.015 Z"},sqrt:{stroke:"M0,0.62 L0.18,0.55 L0.45,0.97 L0.98,0"},cancel:{stroke:"M0,1 L1,0"},int:{stroke:"M0.95,0.09 C0.9,0.01 0.72,0 0.66,0.12 C0.6,0.25 0.42,0.75 0.34,0.88 C0.28,0.99 0.1,0.99 0.05,0.91"},sum:{fill:"M0.04,0 L0.94,0 L0.98,0.24 L0.94,0.24 C0.9,0.1 0.8,0.07 0.62,0.07 L0.24,0.07 L0.58,0.5 L0.2,0.93 L0.64,0.93 C0.82,0.93 0.92,0.9 0.95,0.76 L0.99,0.76 L0.94,1 L0.02,1 L0.47,0.47 Z"},prod:{fill:"M0,0 L1,0 L1,0.04 L0.88,0.05 L0.88,0.95 L1,0.96 L1,1 L0.62,1 L0.62,0.96 L0.74,0.95 L0.74,0.06 L0.26,0.06 L0.26,0.95 L0.38,0.96 L0.38,1 L0,1 L0,0.96 L0.12,0.95 L0.12,0.05 L0,0.04 Z"}};function o(e,t,n=""){const s=r[e];return`<svg class="${t}" viewBox="0 0 1 1" preserveAspectRatio="none" aria-hidden="true"${n?` style="${n}"`:""}>${s.fill?`<path d="${s.fill}" fill="currentColor"/>`:`<path d="${s.stroke}" fill="none" stroke="currentColor" vector-effect="non-scaling-stroke"/>`}</svg>`}const a=.8,l=.2,u=.25,c=.7,f="−",h={"+":"add","-":"sub","*":"mul","/":"frac","^":"pow",_:"subscript",neg:"neg",pm:"pm","!":"factorial","=":"eq","===":"eq","≠":"neq","≠=":"neq","<":"lt",">":"gt","≤":"le","≥":"ge","≈":"approx","≡":"equiv","∈":"in","∉":"notin","∪":"union","∩":"intersect","→":"to","±":"pm","&":"and","|":"or","\\not":"not","\\xor":"xor","\\nand":"nand","\\nor":"nor","\\implies":"implies","\\iff":"iff","?:":"cases","()":"tuple","[]":"list","{}":"set","(]":"interval","[)":"interval","\\sumidx":"sum","\\prodidx":"prod",mod:"mod",pmod:"pmod",pmatrix:"matrix",bmatrix:"matrix",vmatrix:"matrix"},p={"=":"=","===":"=","≠":"≠","≠=":"≠","<":"<",">":">","≤":"≤","≥":"≥","∈":"∈","∉":"∉","→":"→","≈":"≈","≡":"≡","&":"∧","|":"∨","\\xor":"⊕","\\nand":"↑","\\nor":"↓","\\implies":"⇒","\\iff":"⇔"},d={"±":"±","∪":"∪","∩":"∩",mod:"mod"},m=["sin","cos","tan","csc","sec","cot","sinh","cosh","tanh"],g={arcsin:"sin",arccos:"cos",arctan:"tan",arcsec:"sec",arccsc:"csc",arccot:"cot",arcsinh:"sinh",arccosh:"cosh",arctanh:"tanh"},v=[...m,...Object.keys(g),"ln","det"],b={atan2:"atan2",max:"max",min:"min",gcd:"gcd",mean:"mean",round:"round",fixed:"fixed",expm1:"expm1",random:"random"},y={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]},w=["int","lim","\\sumidx","\\prodidx"],x={"\\partial":"∂","\\nabla":"∇","\\ell":"ℓ","\\infty":"∞","\\emptyset":"∅"},k={vec:"→",hat:"ˆ",widehat:"ˆ",tilde:"˜",dot:"˙",ddot:"¨"},q=/^[acegmnopqrsuvwxyzαγεημνοπρστυχω]$/,$=e=>"symbol"===e?.type&&q.test(n.GREEK[e.value]??e.value),S=["boxed","overline","bar","underline","cancel",...Object.keys(k)],M={prefix:"mv",display:!0,fnParens:"auto",trigPowers:!0,inverseTrig:"arc",derivativeBrackets:"[",scriptFractions:"slash",cases:!0,label:!0,mathml:null,attributes:null,style:null},O=e=>String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),A=e=>+e.toFixed(3)+"em",N=(e,t=a,n=l)=>({html:e,h:t,d:n});function E(...e){const t=e.flat().filter(Boolean);return{html:t.map(e=>e.html).join(""),h:Math.max(a,...t.map(e=>e.h)),d:Math.max(l,...t.map(e=>e.d))}}function I(e,t={}){const n=new T({...M,...t}),i=n.render(e,{level:0}),r=`${n.p}${n.o.display?` ${n.p}-display`:""}`,o="function"==typeof n.o.mathml?function(e,t,n,s){try{return String(e(t)).replace(/ id="mz-\d+"/g,"").replace(/^<math>/,`<math class="${n}-sr-math"${s?' display="block"':""}>`)}catch{return""}}(n.o.mathml,e,n.p,n.o.display):"",a=o?null:function(e,t){if(!1===t||null===t)return null;if("string"==typeof t)return t;try{return"function"==typeof t?t(e):s.toAudioSpeech(e)}catch{return null}}(e,n.o.label),l=null!==a||o?i.html.replace(/^<span /,'<span aria-hidden="true" '):i.html;return{html:`<span class="${r}"${null===a?"":` role="math" aria-label="${O(a)}"`}>${l}${o}</span>`,h:i.h,d:i.d}}class T{constructor(e){this.o=e,this.p=e.prefix}el(e,t,n="",s=""){return`<span class="${e.split(" ").map(e=>`${this.p}-${e}`).join(" ")}"${n?` style="${n}"`:""}${s}>${t}</span>`}text(e,t){const n=N(this.el(e,O(t)));return n.leaf={kind:e,content:O(t)},n}bin(e){return this.text("bin",e)}rel(e){return this.text("rel",e)}punct(e){return this.text("punct",e)}word(e){return this.text("word",e)}wrap(e,t,n){let s="";void 0!==e.id&&(s+=` data-node="${e.id}"`),"op"===e.type&&(s+=` data-op="${O(e.op)}"`);const i=this.o.attributes&&this.o.attributes(e)||{};for(const[e,t]of Object.entries(i))"class"!==e&&"style"!==e&&/^[A-Za-z_:][\w:.-]*$/.test(e)&&(s+=` ${e}="${O(t)}"`);const r=[i.style,this.o.style&&this.o.style(e)].filter(Boolean).join(";"),o=(n.leaf?["n",...t,n.leaf.kind]:["n",...t]).map(e=>`${this.p}-${e}`).concat(i.class?[O(i.class)]:[]).join(" "),a=n.leaf?n.leaf.content:n.html;return{html:`<span class="${o}"${r?` style="${O(r)}"`:""}${s}>${a}</span>`,h:n.h,d:n.d}}render(e,t){return"number"===e.type?this.number(e):"string"===e.type?this.wrap(e,["text"],this.text("text",e.value.replace(/^["'`]|["'`]$/g,""))):"symbol"===e.type?this.wrap(e,["symbol"],this.symbol(e.value)):this.operation(e,t)}number(e){const t=/^(-?\d*\.)(\d*)\.\.$/.exec(e.value);if(t){const[,n,s]=t;let i=1;for(let e=1;2*e<=s.length;e++)if(s.slice(-e)===s.slice(-2*e,-e)){i=e;break}let r=s;for(;r.endsWith(s.slice(-i))&&r.length>=i;)r=r.slice(0,-i);const o=this.text("num",(n+r).replace(/^-/,f)),a=this.text("num",s.slice(-i));return this.wrap(e,["number"],E(o,N(this.el("over",a.html),a.h+.14,a.d)))}return this.wrap(e,["number"],this.text("num",e.value.replace(/^-/,f)))}symbol(e){return n.GREEK[e]&&(e=n.GREEK[e]),x[e]?this.text("ord",x[e]):"\\+"===e||"\\-"===e?this.text("ord",e[1]):"-∞"===e?this.text("ord","−∞"):/^[A-Za-z]$/.test(e)||/^[α-ω]$/.test(e)?this.text("var",e):/^[A-Za-z]′+$/.test(e)?N(this.el("var",O(e[0]))+this.el("prime",O(e.slice(1)))):/^Δ[A-Za-z]$/.test(e)?N(this.el("ord","Δ")+this.el("var",e[1])):/^d[A-Za-zα-ω]$/.test(e)?N(this.el("ord","d")+this.el("var",e[1])):e.endsWith("⁻¹")?this.script(this.symbol(e.slice(0,-2)),this.text("num","−1"),{level:0}):/^\\[A-Za-z]+$/.test(e)?this.text("name",e.slice(1)):/^[A-Za-z]{2,}$/.test(e)?this.text("name",e):this.text("ord",e)}operation(e,t){const{op:s,args:i}=e,[r,o]=i,a=(e,n={})=>this.render(e,{...t,...n,forceParens:n.forceParens||!1,before:n.before||!1,leftFactor:!1}),l=h[s]??(/^[a-z0-9]+$/i.test(s)?s:"other"),u=t=>this.wrap(e,["op",`op-${l}`],t),c=(t,s)=>n.needsBrackets(e,t,s)&&"/"!==t.op?this.fence(a(t)):a(t);if(v.includes(s)||"log"===s)return u(this.named(e,t));if(b[s])return u(E(this.word(b[s]),this.fence(this.list(i,t))));if(n.isCustomFunction(s))return u(this.custom(e,t));const m=n.matrixRows(e);if(m)return u(this.matrix(e,m,t));if("{}"===s&&!i.length)return u(this.text("op","∅"));if(y[s])return u(this.fence(this.list(i,t),...y[s]));if(("|"===s||"&"===s)&&i.length>=2&&i.every(C)){const e=e=>"|"!==e.op&&"&"!==e.op||e.op===s?a(e):this.fence(a(e));return u(E(i.map((t,n)=>n?[this.text("conj","|"===s?"or":"and"),e(t)]:[e(t)]).flat()))}if(p[s]&&2===i.length)return u(E(c(r,"left"),this.rel(p[s]),c(o,"right")));if(d[s]&&2===i.length)return u(E(c(r,"left"),this.bin(d[s]),c(o,"right")));switch(s){case"+":if(n.isMinusOneTimes(o)){const e=o.args[1],t=n.needsBrackets({op:"-"},e,"right")?this.fence(a(e)):a(e);return u(E(c(r,"left"),this.bin(f),this.wrap(o,["op","op-mul"],t)))}return"number"===o.type&&o.value.startsWith("-")?u(E(c(r,"left"),this.bin(f),this.wrap(o,["number"],this.text("num",o.value.slice(1))))):u(E(c(r,"left"),this.bin("+"),this.signed(o,c(o,"right"))));case"-":return u(E(c(r,"left"),this.bin(f),this.signed(o,c(o,"right"))));case"*":return u(this.product(e,t));case"/":return u(this.fraction(e,t));case"^":return u(this.power(e,t));case"_":{const e=n.bracketOp(r)&&n.precedenceOf(n.bracketOp(r))<100;return u(this.script(e?this.fence(a(r)):a(r,{forceParens:!0}),null,t,a(o,{level:t.level+1})))}case"neg":return u(E(this.text("sign",f),n.unaryNeedsBrackets(s,r)?this.fence(a(r)):a(r,{before:t.before})));case"pm":return u(E(this.text("sign","±"),n.unaryNeedsBrackets(s,r)?this.fence(a(r)):a(r)));case"!":return u(E(n.unaryNeedsBrackets(s,r)?this.fence(a(r)):a(r,{forceParens:!0}),this.text("ord","!")));case"\\not":return u(E(this.text("sign","¬"),n.unaryNeedsBrackets(s,r)?this.fence(a(r)):a(r)));case"pmod":return u(E(a(r),this.fence(E(this.word("mod"),this.text("space",""),a(o)))));case"sqrt":return u(this.radical(a(r)));case"root":return u(this.radical(a(o),this.render(r,{level:t.level+2})));case"abs":return u(this.fence(a(r),"|","|"));case"floor":return u(this.fence(a(r),"⌊","⌋"));case"ceil":return u(this.fence(a(r),"⌈","⌉"));case"loglog":return u(E(this.word("ln"),this.fence(E(this.word("ln"),this.fence(a(r))))));case"logloglog":return u(E(this.word("ln"),this.fence(E(this.word("ln"),this.fence(E(this.word("ln"),this.fence(a(r))))))));case"perm":return u(this.script(this.script(N(""),this.render(r,{level:t.level+1}),t),null,t,this.render(o,{level:t.level+1}),this.word("P")));case"comb":return u(this.fence(this.stack(a(r),a(o),!1)));case"?:":return u(this.o.cases?this.cases(e,t):E(a(r),this.bin("?"),a(o),this.bin(":"),a(i[2])));case"sum":case"prod":{const e={op:"sum"===s?"+":"*"},t=(t,s)=>n.needsBrackets(e,t,s?"right":"left")?this.fence(a(t)):a(t);return u(E(i.map((e,n)=>n?[this.bin("sum"===s?"+":"·"),t(e,n)]:[t(e,n)]).flat()))}case"setbuilder":return u(this.fence(E(a(r),this.bin("|"),a(o)),"{","}"));case"evaluated":{const e=e=>this.render(e,{...t,level:t.level+1});return u(this.script(this.fence(a(r),"[","]"),e(i[3]),t,e(i[2])))}case"der":return u(this.derivative(e,t));case"int":return u(this.integral(i,t));case"lim":return u(this.limit(i,t));case"\\sumidx":return u(this.bigOperator("sum",i,t));case"\\prodidx":return u(this.bigOperator("prod",i,t))}throw new Error(`Inline Math cannot draw '${s}'`)}signed(e,t){return("number"===e.type?e.value.startsWith("-"):"neg"===e.op||"pm"===e.op)&&!t.fenced?this.fence(t):t}list(e,t){return E(e.map((e,n)=>n?[this.punct(","),this.render(e,t)]:[this.render(e,t)]).flat())}product(e,t){const[s,i]=e.args;if(n.isMinusOneTimes(e))return E(this.text("sign",f),n.unaryNeedsBrackets("neg",i)?this.fence(this.render(i,t)):this.render(i,t));const r=n.bracketedSides(e);w.includes(s.op)&&(r.left=!0);const o=!e.written&&n.isImplicitProduct(s,i,r),a=function(e){for(;"op"===e.type;){if(v.includes(e.op)||"log"===e.op||b[e.op]||n.isCustomFunction(e.op))return!0;if("^"!==e.op&&"*"!==e.op)return!1;e=e.args[0]}return!1}(i),l=r.left?this.fence(this.render(s,t)):this.render(s,{...t,before:o&&!a,leftFactor:!0}),u=r.right?this.fence(this.render(i,t)):this.render(i,{...t,before:t.before});return E(l,o?N(this.el(a?"fnspace":"times","")):this.bin("cross"===e.written?"×":"·"),u)}named(e,t,n=null){const{op:s,args:i}=e,r="log"===s?i[1]:i[0];let o;o=g[s]&&"power"===this.o.inverseTrig?this.script(this.word(g[s]),this.text("num","−1"),t):this.word(s),n&&(o=this.script(o,n,t)),"log"===s&&(o=this.script(o,null,t,this.render(i[0],{level:t.level+1})));const a="auto"===this.o.fnParens&&!t.forceParens&&!t.before&&L(r),l=this.render(r,{...t,forceParens:!1,before:!1});return E(o,a?E(N(this.el("fnspace","")),l):this.fence(l))}custom(e,t){const s=n.customName(e.op),i=e.args;if(S.includes(s)&&1===i.length)return this.decorate(s,this.render(i[0],t),i[0]);return E(/^[A-Za-z]′*(⁻¹)?$/.test(s)?this.symbol(s):this.word(s),N(this.el("callgap","")),this.fence(this.list(i,t)))}decorate(e,t,n){switch(e){case"boxed":return N(this.el("boxed",t.html),t.h+.22,t.d+.22);case"cancel":return N(this.el("cancel",t.html+o("cancel",`${this.p}-cancel-line`)),t.h,t.d);case"underline":return N(this.el("underline",t.html),t.h,t.d+.12);case"overline":case"bar":return N(this.el("over"+($(n)?" over-low":""),t.html),t.h+.14,t.d);default:{const s=$(n);return N(this.el("accent"+(s?" accent-low":""),this.el(`accent-mark accent-${e}`,k[e])+t.html),t.h+.3,t.d)}}}fraction(e,t){const[s,i]=e.args;if(t.level>0&&"slash"===this.o.scriptFractions&&L(s,!0)&&L(i,!0)){const e={...t,leftFactor:!1},r=(t,s)=>"op"!==t.type||L(t)&&(!s||"*"!==t.op||n.isMinusOneTimes(t))?this.render(t,e):this.fence(this.render(t,e)),o=E("op"===s.type&&"neg"===s.op?this.render(s,e):r(s,!1),this.text("ord","/"),r(i,!0));return t.leftFactor?this.fence(o):o}const r=t.level>0||t.inFraction||!this.o.display?.8:1,o={...t,inFraction:!0,forceParens:!1,before:!1};return this.stack(this.render(s,o),this.render(i,o),!0,r)}stack(e,t,n=!0,s=1){const i=e=>1===s?e.html:this.el("scaled",e.html,`font-size:${A(s)}`),r=n?.06:0,o=u+r/2+.1+Math.max(l,s*e.d),c=this.el("frac"+(n?"":" frac-nobar"),this.el("numer",i(e))+this.el("denom",i(t)),`vertical-align:${A(o)}`);return N(c,o+Math.max(a,s*e.h),Math.max(a,s*t.h)+Math.max(l,s*t.d)+.1+r/2-u)}power(e,t){const[s,i]=e.args,r={...t,level:t.level+1,forceParens:!1,before:!1,inFraction:!1,leftFactor:!1},o=()=>this.render(i,r);if(this.o.trigPowers&&m.includes(s.op)&&Z(i))return this.wrap(s,["op",`op-${s.op}`],this.named(s,t,o()));if("_"===s.op){const e=this.render(s.args[1],r);return this.wrap(s,["op","op-subscript"],this.script(this.render(s.args[0],{...t,forceParens:!0}),o(),t,e))}const a=n.needsBrackets(e,s,"left")||"number"===s.type&&s.value.startsWith("-")||"/"===s.op||v.includes(s.op)||w.includes(s.op)?this.fence(this.render(s,t)):this.render(s,{...t,forceParens:!0});return this.script(a,o(),t)}script(e,t,n,s=null,i=null){const r=n.level>0?.8:c,o=i?E(e,i):e;let a=t?Math.max(.42,e.h-.38,r*t.d+.12):0,l=s?Math.max(.2,e.d-.05,r*s.h-.45):0;if(t&&s){const e=.1-(a-r*t.d-(r*s.h-l));e>0&&(l+=e)}const u=e=>this.el("script",e.html,`font-size:${A(r)}`);if(t&&!s)return N(e.html+this.el("sup",t.html,`font-size:${A(r)};vertical-align:${A(a/r)}`),Math.max(o.h,a+r*t.h),Math.max(o.d,r*t.d-a));if(s&&!t)return N(o.html+this.el("sub",s.html,`font-size:${A(r)};vertical-align:${A(-l/r)}`),Math.max(o.h,r*s.h-l),Math.max(o.d,l+r*s.d));const f=a+r*t.h,h=l+r*s.d,p=this.el("subsup",u(t)+u(s),`vertical-align:${A(a)};height:${A(f+h)}`);return N(o.html+p,Math.max(o.h,f),Math.max(o.d,h))}radical(e,t=null){const n=Math.max(e.h,a)+.1+.06,s=Math.max(e.d,l),i=n+s,r=.5+.06*(i-1),u=o("sqrt",`${this.p}-hook`,`width:${A(r)};left:${A(-r)}`);let f="";if(t){const e=.8*c;f=this.el("rootindex",t.html,`font-size:${A(e)};vertical-align:${A((.55*i-s)/e)}`)}return N(this.el("sqrt",f+this.el("radicand",u+e.html,`margin-left:${A(r+.05)}`)),n,s)}fence(e,t="(",n=")"){const s=Math.max(e.h,a)+Math.max(e.d,l),i=s>1.25,r=i?.1:0,u=(e,t)=>{if(!e)return{html:"",w:0};const n={"(":.26,")":.26,"{":.36,"}":.36}[e];if(n){const r=n+(i?Math.min(.2,.05*(s-1)):0);return{html:o(e,`${this.p}-delim ${this.p}-delim-${t}`,`width:${A(r)}`),w:r+.1}}const r={"[":"lbrack","]":"rbrack","|":"vert","⌊":"lfloor","⌋":"rfloor","⌈":"lceil","⌉":"rceil"}[e];return{html:this.el(`delim ${r} delim-${t}`,""),w:"|"===e?.18:.3}},c=u(t,"l"),f=u(n,"r");if(!i){const t=N(this.el("fence fence-line",c.html+e.html+f.html),Math.max(e.h,a),Math.max(e.d,l));return t.fenced=!0,t}const h=`padding:${A(r)} ${A(f.w)} ${A(r)} ${A(c.w)}`,p=N(this.el("fence",c.html+e.html+f.html,h),Math.max(e.h,a)+r,Math.max(e.d,l)+r);return p.fenced=!0,p}derivative(e,t){const s=this.leibniz(e,t),{by:i,at:r}=n.derivativeOrder(e);if(!r)return s;const o=e.args[1],a=this.render({...o,args:[{...i,id:void 0},r]},{...t,level:t.level+1});return this.script(this.fence(s,"","|"),null,t,a)}leibniz(e,t){const{n:s,body:i,by:r,variable:o}=n.derivativeOrder(e),a={...t,level:t.level+1},l=()=>this.text("d","d"),u=()=>s>1?this.render({type:"number",value:String(s)},a):null,c={...t,inFraction:!0},f=E(l(),u()?this.script(this.render(r,c),u(),c):this.render(r,c)),h=e=>E(u()?this.script(l(),u(),c):l(),e||[]),p=t.level>0||t.inFraction||!this.o.display?.8:1;if(o)return this.stack(h(this.render(i,c)),f,!0,p);const d=n.bracketOp(i)&&n.precedenceOf(n.bracketOp(i))<100,[m,g]="("===this.o.derivativeBrackets?["(",")"]:["[","]"],v=d?this.fence(this.render(i,t),m,g):this.render(i,t);return E(this.stack(h(),f,!0,p),v)}integral(e,t){const[s,i,r,o]=e,a=e=>this.render(e,t),l=e=>e?this.render(e,{...t,level:t.level+1}):null,u=()=>this.text("var",n.firstVariable(s)||"x");let c,f=null,h=null;switch(e.length){case 1:c=u();break;case 2:n.isVariable(i)?c=a(i):(c=u(),f=l(i));break;case 3:n.isVariable(i)?(c=a(i),f=l(r)):(c=u(),f=l(i),h=l(r));break;default:c=a(i),f=l(r),h=l(o)}const p=a(s),d=N(this.el("dx",this.el("d","d")+c.html),c.h,c.d);return E(this.bigSign("int",p,f,h,t),p,d)}bigSign(e,t,n,s,i){const r=!this.o.display||i.level>0,a=Math.max(r?.6:.95,Math.max(t.h-u,t.d+u)+.12),l=o(e,`${this.p}-bigsign ${this.p}-${e}sign`,`height:${A(2*a)};width:${A(r?.38:.5)};vertical-align:${A(u-a)}`);if(!n&&!s)return N(l,u+a,a-u);const f=c,h=s||N(""),p=n||N(""),d=u+a-f*h.h;p.d;const m=this.el("limits",this.el("script",h.html,`font-size:${A(f)}`)+this.el("script lower",p.html,`font-size:${A(f)}`),`vertical-align:${A(d)};height:${A(2*a)}`);return N(l+m,u+a,a-u)}limit(e,t){const[s,i,r,o]=e,a={...t,level:t.level+1},l=e=>this.render(e,a),u=()=>this.rel("→");let c;switch(e.length){case 1:return E(this.word("lim"),N(this.el("fnspace","")),this.body(s,t));case 2:{const e=n.firstVariable(s),t="number"===i.type||"symbol"===i.type&&i.value.includes("∞");c=e&&t?E(this.text("var",e),u(),l(i)):l(i);break}case 3:c=E(l(i),u(),l(r));break;default:{const e=n.firstLeaf(o).toLowerCase().startsWith("r")?"+":f;c=E(l(i),u(),this.script(l(r),this.wrap(o,["symbol"],this.text("ord",e)),a))}}return E(this.under(this.word("lim"),c,t),this.body(s,t))}under(e,t,n){return!this.o.display||n.level>0?this.script(e,null,n,t):N(this.el("under",e.html+this.el("script",t.html,`font-size:${A(.7)}`)),e.h,Math.max(e.d,l)+.05+.7*(t.h+t.d))}body(e,t){const s=n.bracketOp(e);return s&&n.precedenceOf(s)<n.precedenceOf("*")?this.fence(this.render(e,t)):this.render(e,t)}bigOperator(e,t,n){const[s,i,r]=t,a={...n,level:n.level+1},l=i?this.render(i,a):null,f=r?this.render(r,a):null,h=this.body(s,n);if(!this.o.display||n.level>0){const t=.55,s=o(e,`${this.p}-bigsign`,`height:${A(2*t)};width:${A(.8)};vertical-align:${A(u-t)}`);return E(this.script(N(s,u+t,t-u),f,n,l),h)}const p=.68,d=c,m=o(e,`${this.p}-bigsign`,`height:${A(1.36)};width:${A("sum"===e?1:1.05)}`),g=f?1.01+d*f.d:u-p,v=e=>this.el("script",e.html,`font-size:${A(d)}`),b=this.el("bigop",(f?v(f):"")+m+(l?v(l):""),`vertical-align:${A(g)}`);return E(N(b,.93+(f?.08+d*(f.h+f.d):0),p-u+(l?.08+d*(l.h+l.d):0)),h)}matrix(e,t,s){const i=t.map(e=>e.map(e=>this.render(e,s))),r=i.map(e=>({h:Math.max(a,...e.map(e=>e.h)),d:Math.max(l,...e.map(e=>e.d))})),o=r.reduce((e,t)=>e+t.h+t.d,0)+.3*(t.length-1),c=u+o/2-r[0].h,f=i.map((t,n)=>{const s=t.map(e=>this.el("matrix-cell",e.html)).join(""),i=e.args[n];return i&&"op"===i.type&&"[]"===i.op?this.wrap(i,["op","op-list","matrix-row"],N(s)).html:s}).join(""),h=t[0].length,p=N(this.el("matrix",f,`grid-template-columns:repeat(${h},auto);vertical-align:${A(c)}`),u+o/2,o/2-u),[d,m]=n.MATRICES[e.op]??["[","]"];return this.fence(p,d,m)}cases(e,t){const n=[];let s=e;for(;"op"===s.type&&"?:"===s.op;)n.push([this.render(s.args[1],t),E(this.word("if"),this.text("space",""),this.render(s.args[0],t))]),s=s.args[2];"symbol"===s.type&&"unchanged"===s.value||n.push([this.render(s,t),this.word("otherwise")]);const i=n.map(([e,t])=>({h:Math.max(e.h,t.h),d:Math.max(e.d,t.d)})),r=i.reduce((e,t)=>e+t.h+t.d,0)+.25*(n.length-1),o=u+r/2-i[0].h,a=n.map(([e,t])=>this.el("case-value",e.html)+this.el("case-cond",t.html)).join(""),l=N(this.el("cases",a,`vertical-align:${A(o)}`),u+r/2,r/2-u);return this.fence(l,"{","")}}function L(e,t=!1){return"number"===e.type?!e.value.startsWith("-")||t:"symbol"===e.type||"op"===e.type&&("abs"===e.op||n.matrixRows(e)?!t:!t||"neg"!==e.op&&"^"!==e.op?"*"===e.op&&!n.isMinusOneTimes(e)&&e.args.every(e=>"number"===e.type&&!e.value.startsWith("-")||z(e)||"*"===e.op&&L(e,t)):L(e.args[0],!0)&&("neg"===e.op||L(e.args[1],!0)))}const j=["=","===","≠","≠=","<",">","≤","≥","≈","≡","∈","∉"],C=e=>"op"===e.type&&e.args.length>=2&&(2===e.args.length&&j.includes(e.op)||("|"===e.op||"&"===e.op)&&e.args.every(C)),z=e=>"symbol"===e.type&&(1===e.value.length||/^[α-ωΑ-Ω]$/.test(e.value)||Boolean(n.GREEK[e.value])),Z=e=>"number"===e.type&&/^[1-9]\d*$/.test(e.value)&&Number(e.value)<10;for(const e of[h,p,d,g,b,y,x,k])Object.setPrototypeOf(e,null);function B(e){const{id:t,from:n,...s}=e;return s.args&&(s.args=s.args.map(B)),s}const F=e=>n.toPostfix(e).join(" ");function D(e,t){const s=new Set;P(e,t,s);const i=[];return n.walk(e,e=>{s.has(e)&&i.push(e)}),i}function P(e,t,s){if(null!=t)if(Array.isArray(t))t.forEach(t=>P(e,t,s));else if("number"!=typeof t)if("function"!=typeof t){if("string"==typeof t){const i=F(n.parseTree(t));return void n.walk(e,e=>{F(e)===i&&s.add(e)})}if(t.path){const n=R(e,t.path);return void(n&&s.add(n))}if(t.type){const i=F(t);n.walk(e,e=>{e!==t&&F(e)!==i||s.add(e)})}}else n.walk(e,(e,n)=>{t(e,n)&&s.add(e)});else n.walk(e,e=>{e.id===t&&s.add(e)})}function R(e,t){let n=e;for(const e of t){if("op"!==n.type||!n.args[e])return null;n=n.args[e]}return n}function W(e,t){const n=[],s=e=>{if(e.id===t)return!0;if("op"!==e.type)return!1;for(let t=0;t<e.args.length;t++){if(n.push(t),s(e.args[t]))return!0;n.pop()}return!1};return s(e)?n:null}function _(e){let t=0;const s=e=>{"op"===e.type&&(e.args.forEach(s),n.operator(e.op)?.arity===n.VARIADIC&&t++),e.id=t++};return s(e),e}function V(e,t={}){const{blocks:s}=t;if("string"==typeof e)return n.parseTree(e,s?{blocks:e=>s(e,t.scope)}:{});if(Array.isArray(e))return n.fromPostfix(e);if(e&&"object"==typeof e&&e.type){if(void 0!==e.id)return e;const t=structuredClone(e);return n.walk(t,e=>{"op"!==e.type&&void 0!==e.value&&(e.value=String(e.value))}),_(t)}throw new Error("Inline Math needs an expression, standard postfix or a tree")}function U(e,t){const{colors:n,highlight:s,scope:i,blocks:r,...o}=t,a=new Map;for(const[t,s]of function(e){return e?Array.isArray(e)?e:Object.entries(e).map(([e,t])=>[/^\d+$/.test(e)?Number(e):e,t]):[]}(n))if(H(s))for(const n of D(e,t))a.set(n,`color:${s}`);const l=new Set(void 0===s?[]:D(e,s));if(!a.size&&!l.size)return o;const u=o.prefix||"mv";return{...o,style:e=>[a.get(e),o.style&&o.style(e)].filter(Boolean).join(";"),attributes:e=>{const t={...o.attributes?o.attributes(e):{}};return l.has(e)&&(t.class=[t.class,`${u}-hl`].filter(Boolean).join(" ")),t}}}function H(e){return"string"==typeof e&&/^[#\w\s.,%()/+-]+$/.test(e)&&!/url\s*\(|expression/i.test(e)}function K(e,n={}){return V(e,{...n,blocks:n.blocks??t.calculateBlock})}function J(e,n={}){return function(e,t={}){const n=V(e,t);return I(n,U(n,t)).html}(e,{...n,blocks:n.blocks??t.calculateBlock})}function Q(e,t,n){const s=(e,i)=>i===t.length?n:{...e,args:e.args.map((e,n)=>n===t[i]?s(e,i+1):e)};return B(s(e,0))}function Y(e,t,{parse:n,commit:s,cancel:i,label:r="Edit",prefix:o="mv"}){const a=e.ownerDocument;if(!a||!a.body)return null;const l=a.defaultView,u=e.getBoundingClientRect(),c=a.createElement("input");c.type="text",c.className=`${o}-edit`,c.value=t,c.spellcheck=!1,c.autocomplete="off",c.setAttribute("aria-label",r);const f=()=>{c.style.width=`${Math.max(4,c.value.length+2)}ch`},h=l.getComputedStyle(e);Object.assign(c.style,{position:"absolute",left:`${u.left+l.scrollX}px`,top:`${u.top+l.scrollY+u.height/2}px`,minWidth:`${Math.max(u.width,32)}px`,fontSize:h.fontSize}),f(),a.body.appendChild(c),l.getSelection?.()?.removeAllRanges(),c.focus(),c.select();let p=!1;const d=()=>{p=!0,c.remove()};c.cancelEdit=()=>{p||(d(),i&&i())};const m=e=>{if(p)return!0;if(!e||c.value===t)return d(),i&&i(),!0;let r;try{r=n(c.value)}catch(e){return c.setAttribute("aria-invalid","true"),c.title=e.message,!1}return d(),s(r,c.value),!0};return c.addEventListener("keydown",e=>{e.stopPropagation(),"Enter"===e.key&&(e.preventDefault(),m(!0)),"Escape"===e.key&&(e.preventDefault(),m(!1))}),c.addEventListener("input",()=>{f(),c.removeAttribute("aria-invalid"),c.removeAttribute("title")}),c.addEventListener("blur",()=>{m(!0)||m(!1)}),c}class G{constructor(e,t,n={}){this.element=e,this.options=n,this.p=n.prefix||"mv",this.handlers=[],this.clicks=[],this.active=null,this.live=X(e,n.announce,this.p),this.set(t)}set(e,{animate:t=!1,duration:n=600,easing:s="ease-in-out"}={}){const i=K(e,this.options),{html:r}=I(i,U(i,this.options));if(this.editor){const e=this.editor;this.editor=null,e.cancelEdit?.()}const o=ee(t)&&this.tree?this.snapshot():null,a=void 0!==this.tree;return this.tree=i,this.element.innerHTML=r,this.root=this.element.firstElementChild,this.handlers.length&&this.root.classList.add(`${this.p}-clickable`),this.editing&&this.root.classList.add(`${this.p}-editable`),this.active=null,(this.clicks.length||this.editing)&&this.focusable(),o&&this.morph(o,{duration:n,easing:s}),a&&this.live&&this.announce(this.spoken()),this}spoken(){const e=this.root&&this.root.getAttribute&&this.root.getAttribute("aria-label");if(e)return e;try{return s.toAudioSpeech(this.tree)}catch{return""}}announce(e){return this.say(this.live,e)}say(e,t){if(!e)return this;e.textContent="";const n=()=>{e.textContent=t};return"function"==typeof requestAnimationFrame?requestAnimationFrame(()=>requestAnimationFrame(n)):setTimeout(n,50),this}nodes(e){return D(this.tree,e)}elements(e){return this.nodes(e).map(e=>this.elementOf(e)).filter(Boolean)}elementOf(e){return void 0===e.id?null:this.root.querySelector(`[data-node="${e.id}"]`)}highlight(e,t=`${this.p}-hl`){return this.elements(e).forEach(e=>e.classList.add(t)),this}unhighlight(e=null,t=`${this.p}-hl`){return(null===e?this.root.querySelectorAll(`.${t}`):this.elements(e)).forEach(e=>e.classList.remove(t)),this}color(e,t){return this.elements(e).forEach(e=>{e.style.color=t||""}),this}on(e,t){const n=e=>{const n=e.target.closest?.("[data-node]");if(!n||!this.root.contains(n))return;const s=Number(n.dataset.node),i=D(this.tree,s)[0];t({node:i,id:s,path:W(this.tree,s),element:n,event:e})};this.element.addEventListener(e,n);const s=[e,n];return this.handlers.push(s),this.root.classList.add(`${this.p}-clickable`),"click"===e&&(this.clicks.push(t),this.keyboard()),()=>{this.element.removeEventListener(e,n),this.clicks=this.clicks.filter(e=>e!==t),this.handlers=this.handlers.filter(e=>e!==s),!this.handlers.length&&this.root&&this.root.classList.remove(`${this.p}-clickable`)}}destroy(){if(this.editor){const e=this.editor;this.editor=null,e.cancelEdit?.()}for(const[e,t]of this.handlers)this.element.removeEventListener(e,t);this.handlers=[],this.clicks=[],this.keyListener&&this.element.removeEventListener("keydown",this.keyListener),this.editListener&&this.element.removeEventListener("dblclick",this.editListener),this.keyListener=this.editListener=null,this.keysOn=this.editOn=!1;for(const e of new Set([this.live,this.partsLive]))e&&"view"===e.dataset?.mvMadeBy&&e.remove();return this.live=this.partsLive=null,this}editable({toText:e,onEdit:t}={}){if("function"!=typeof e)throw new Error("editable needs { toText } (import { toText } from 'mathzetta/text')");return this.editing={toText:e,onEdit:t},this.root&&this.root.classList&&this.root.classList.add(`${this.p}-editable`),this.keyboard(),!this.editOn&&this.element.addEventListener&&(this.editOn=!0,this.editListener=e=>{const t=e.target.closest?.("[data-node]");t&&this.root.contains(t)&&(e.preventDefault(),this.edit(D(this.tree,Number(t.dataset.node))[0]))},this.element.addEventListener("dblclick",this.editListener)),this}edit(e=this.tree,{returnFocus:t=!1}={}){if(!this.editing)throw new Error("call editable({ toText }) first");const n="object"==typeof e&&e&&e.type?e:this.nodes(e)[0];if(!n)return null;const i=W(this.tree,n.id)||[],r=this.elementOf(n)||this.root;let o="Edit";try{o=`Edit ${s.toAudioSpeech(n)}`}catch{}const a=()=>{t&&this.root.focus&&this.root.focus()};return this.editor=Y(r,this.editing.toText(n),{label:o,prefix:this.p,parse:e=>K(e,this.options),commit:(e,n)=>{this.set(Q(this.tree,i,e),{animate:!0});const s=R(this.tree,i);t&&s&&this.focusPart(s===this.tree?null:s),a(),this.editing.onEdit&&this.editing.onEdit({tree:this.tree,text:this.editing.toText(this.tree),path:i,part:n})},cancel:a}),this.editor}focusable(){this.root&&this.root.setAttribute&&(this.root.setAttribute("tabindex","0"),this.root.getAttribute("aria-label")||(this.root.setAttribute("role","math"),this.root.setAttribute("aria-label",this.spoken())),this.root.setAttribute("aria-description",this.editing?"Arrow keys move between parts, F2 edits one.":"Arrow keys move between parts, Enter selects one."))}keyboard(){this.focusable(),!this.keysOn&&this.element.addEventListener&&(this.keysOn=!0,this.partsLive=this.live||X(this.element,!0,this.p),this.keyListener=e=>this.key(e),this.element.addEventListener("keydown",this.keyListener))}key(e){if(!this.root||!this.root.contains(e.target))return;const t=this.active;let n;switch(e.key){case"ArrowDown":n=t?this.partsOf(t)[0]:this.partsOf(this.tree)[0];break;case"ArrowUp":n=t?this.outerOf(t):void 0;break;case"ArrowRight":n=t?this.neighbor(t,1):this.partsOf(this.tree)[0];break;case"ArrowLeft":n=t?this.neighbor(t,-1):void 0;break;case"Home":case"Escape":n=null;break;case"F2":if(!this.editing)return;return e.preventDefault(),void this.edit(t||this.tree,{returnFocus:!0});case"Enter":case" ":{e.preventDefault();const n=t||this.tree,s=this.elementOf(n)||this.root,i={node:n,id:n.id,path:W(this.tree,n.id),element:s,event:e};for(const e of this.clicks)e(i);return}default:return}e.preventDefault(),void 0!==n&&this.focusPart(n)}focusPart(e){const t=`${this.p}-focus`;this.root.querySelectorAll(`.${t}`).forEach(e=>e.classList.remove(t)),this.active=e;const n=e&&this.elementOf(e);n&&n.classList.add(t);let i="";try{i=e?s.toAudioSpeech(e):this.spoken()}catch{i=""}return this.say(this.partsLive,i),this}partsOf(e){const t=[],n=e=>{this.elementOf(e)?t.push(e):"op"===e.type&&e.args.forEach(n)};return e&&"op"===e.type&&e.args.forEach(n),t}outerOf(e){const t=W(this.tree,e.id);for(let e=t?t.length-1:-1;e>0;e--){const n=R(this.tree,t.slice(0,e));if(n&&this.elementOf(n))return n}return null}neighbor(e,t){const n=this.partsOf(this.outerOf(e)||this.tree),s=n.indexOf(e);return s<0?void 0:n[s+t]}segments(e={}){return s.toSpeechSegments(this.tree,e)}showSegment(e,t=`${this.p}-hl`){return this.unhighlight(null,t),e&&void 0!==e.id&&this.highlight(e.id,t),this}snapshot(){const e=new Map,t=n=>{const s=this.elementOf(n);if(s){const t=F(n);e.has(t)||e.set(t,[]),e.get(t).push({rect:s.getBoundingClientRect(),node:n,sig:t})}"op"===n.type&&n.args.forEach(t)};return t(this.tree),e}morph(e,{duration:t,easing:n}){if("undefined"==typeof Element||!Element.prototype.animate)return;const s=t=>{if("op"===t.type)for(const n of t.args){const t=e.get(F(n)),i=t?t.findIndex(e=>e.node===n):-1;i>-1&&t.splice(i,1),s(n)}},i=r=>{const o=this.elementOf(r),a=o&&e.get(F(r));if(a&&a.length){const{rect:e,node:i}=a.shift();s(i);const r=o.getBoundingClientRect(),l=e.left-r.left,u=e.top-r.top,c=r.width?e.width/r.width:1,f=r.height?e.height/r.height:1;return void((Math.abs(l)+Math.abs(u)>.5||Math.abs(c-1)+Math.abs(f-1)>.01)&&o.animate([{transformOrigin:"0 0",transform:`translate(${l}px, ${u}px) scale(${c}, ${f})`},{transformOrigin:"0 0",transform:"none"}],{duration:t,easing:n}))}"op"===r.type?r.args.forEach(i):o&&o.animate([{opacity:0},{opacity:0},{opacity:1}],{duration:t,easing:n})};i(this.tree)}}function X(e,t,n){if(!t)return null;if("object"==typeof t&&1===t.nodeType)return t;if("undefined"==typeof document||!e.insertAdjacentElement)return null;const s=e.nextElementSibling;if(s&&"view"===s.dataset?.mvMadeBy&&s.classList.contains(`${n}-sr-only`))return s;const i=document.createElement("span");return i.dataset.mvMadeBy="view",i.className=`${n}-sr-only`,i.setAttribute("aria-live","polite"),i.setAttribute("aria-atomic","true"),e.insertAdjacentElement("afterend",i),i}function ee(e){return!!e&&("always"===e||!("function"==typeof matchMedia&&matchMedia("(prefers-reduced-motion: reduce)").matches))}const te=Symbol.for("inlinemath.expressions"),ne=new Set(["symbol","number"]);function se(e){return e?"symbol"===e.type?e.value:"op"===e.type&&"_"===e.op&&2===e.args.length&&"symbol"===e.args[0].type&&ne.has(e.args[1].type)?`${e.args[0].value}_${e.args[1].value}`:null:null}function ie(e){const{id:t,...n}=e;return n.args&&(n.args=n.args.map(ie)),n}function re(e,t){const n=(e,s)=>{if(!s&&void 0!==e.from)return t(e.from);const{id:i,from:r,...o}=e;return o.args&&(o.args=o.args.map(e=>n(e,!1))),o};return n(e,!0)}const oe=new Set;function ae(e,t){let s=!1;const i=new Set,r=(e,o=oe)=>{const a=se(e);if(null!==a){if(!i.has(a)&&!o.has(a)){const e=t(a);if(e){s=!0,i.add(a);const t={...r(B(e)),from:a};return i.delete(a),t}}return e}if(e.args){const t=function(e){const[t,s]=e.args,i=e=>e&&"symbol"===e.type?e.value:null;switch(e.op){case"der":return"="===s?.op?i(s.args[0])&&{name:i(s.args[0]),where:e=>0===e,index:1}:i(s)&&{name:i(s),where:e=>e<=1};case"int":{const r=i(s)??(3===e.args.length||1===e.args.length?n.firstVariable(t)||"x":null);return r&&{name:r,where:e=>0===e||1===e&&i(s)===r}}case"lim":return"→"===s?.op&&i(s.args[0])&&{name:i(s.args[0]),where:e=>0===e,index:1};case"\\sumidx":case"\\prodidx":return("="===s?.op||"∈"===s?.op)&&i(s.args[0])&&{name:i(s.args[0]),where:e=>0===e,index:1};default:return null}}(e);if(!t)return{...e,args:e.args.map(e=>r(e,o))};const s=new Set([...o,t.name]);return{...e,args:e.args.map((e,n)=>n===t.index?{...e,args:e.args.map((e,t)=>r(e,0===t?s:o))}:r(e,t.where(n)?s:o))}}return e},o=r(e);return{tree:s?ie(o):e,changed:s}}const le="[-+]?(?:\\d+\\.?\\d*|\\.\\d+)",ue=new RegExp(`^(${le})\\s*\\.\\.\\s*(${le})(?:\\s+step\\s+(${le}))?(?:\\s*=\\s*(${le}))?$`);function ce(e){const t=/^\s*\[\[([\s\S]*)\]\]\s*$/.exec(e);if(!t||/\]\s*,\s*\[/.test(t[1]))return null;const n=t[1].trim(),s=ue.exec(n);if(s){const e=Number(s[1]),t=Number(s[2]);if(!(t>e))return null;const n=void 0!==s[3]?Number(s[3]):Number.isInteger(e)&&Number.isInteger(t)?1:(t-e)/100;if(!(n>0))return null;const i=void 0!==s[4]?Math.min(t,Math.max(e,Number(s[4]))):e;return{kind:"slider",min:e,max:t,step:n,default:String(i)}}if(n.includes("|")){const e=n.split("|").map(e=>e.trim()).filter(Boolean);if(e.length)return{kind:"dropdown",options:e,default:e[0]}}return{kind:"textbox",default:n}}const fe=Symbol("set on the page");class he{constructor(){this.owners=new Map,this.chosen=new Map,this.listeners=new Set}definitions(e){const t=new Map;for(const[n,s]of this.owners)if(n!==e)for(const[e,n]of s)t.delete(e),t.set(e,n);return t}textOf(e){const t=this.chosen.get(e.name);return t&&t.key===e.key?t.text:e.text}get(e){const t=this.definitions().get(e);return t?this.textOf(t):void 0}names(){return[...this.definitions().keys()]}set(e,t){t=String(t);const n=this.definitions().get(e);if(n&&n.input){const s=this.chosen.get(e);if(s&&s.key===n.key&&s.text===t)return this;this.chosen.set(e,{key:n.key,text:t})}else{const n=new Map(this.owners.get(fe));n.set(e,{name:e,text:t,key:`page:${t}`,input:null}),this.owners.delete(fe),this.owners.set(fe,n)}return this.notify(null,e),this}clear(e){return void 0===e?(this.owners.clear(),this.chosen.clear()):(this.owners.get(fe)?.delete(e),this.chosen.delete(e)),this.notify(null,e),this}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}own(e,t){const n=this.owners.get(e);var s,i;(s=n,i=t,(s?.size??0)===(i?.size??0)&&[...s??[]].every(([e,t])=>i?.get(e)?.key===t.key))?t&&this.owners.set(e,t):(t&&t.size?this.owners.set(e,t):this.owners.delete(e),this.notify(e))}notify(e,t){for(const n of[...this.listeners])n(e,t)}}function pe(){return new he}const de=pe(),me=new RegExp("(\\d+)","g");function ge(e,{delimiters:t=["$$","$","\\[","\\("]}={}){const n=[];let s="",i=0;const r=String(e).replace(/[\uE000-\uE003]/g,"�"),o=e=>0===e||"\n"===r[e-1],a=function(e){const t=new Map,n=e=>/^( {4}|\t)/.test(e);let s=0,i=!0,r=!1,o=-1;for(const a of e.split("\n")){const e=!a.trim();o>-1&&!e&&!n(a)&&(t.set(o,s-1),o=-1),o<0&&!e&&n(a)&&i&&!r&&(o=s),e||n(a)||(r=Me.test(a)||r&&/^\s/.test(a)),i=e,s+=a.length+1}o>-1&&t.set(o,e.length);return t}(r);let l=-1;const u=new Set,c=(e,t,s)=>(n.push({source:e,display:t,raw:s,start:i,end:i+s.length}),`${n.length-1}`);for(;i<r.length;){if(a.has(i)){s+=r.slice(i,a.get(i)),i=a.get(i);continue}if(o(i)){const e=/^( {0,3})(`{3,}|~{3,})([^\n]*)\n?/.exec(r.slice(i));if(e){const t=e[2],n=new RegExp(`\\n {0,3}${"`"===t[0]?"`":"~"}{${t.length},}[ \\t]*(?=\\n|$)`),o=r.slice(i+e[0].length),a=n.exec(`\n${o}`),l=a?o.slice(0,Math.max(0,a.index-1)):o,u=e[0].length+(a?a.index-1+a[0].length:o.length),f=r.slice(i,i+u);"math"===e[3].trim()?s+=c(l,!0,f):s+=f,i+=u;continue}}const e=r[i];if("`"===e){const e=/^`+/.exec(r.slice(i))[0],t=r.indexOf(e,i+e.length);if(t>-1){s+=r.slice(i,t+e.length),i=t+e.length;continue}s+=e,i+=e.length;continue}if("\\"===e){const e=r.slice(i,i+2),n="\\["===e?"\\]":"\\("===e?"\\)":null;if(n&&t.includes(e)){const t=u.has(n)?-1:r.indexOf(n,i+2);if(t<0&&u.add(n),t>-1){s+=c(r.slice(i+2,t),"\\["===e,r.slice(i,t+2)),i=t+2;continue}}s+=e,i+=2;continue}if("$"===e)if("$"===r[i+1]&&t.includes("$$")){const e=r.indexOf("$$",i+2);if(e>-1){s+=c(r.slice(i+2,e),!0,r.slice(i,e+2)),i=e+2;continue}}else if(t.includes("$")&&r[i+1]&&!/\s/.test(r[i+1])&&i+1>=l){const{end:e,stop:t}=ve(r,i+1);if(e>-1){s+=c(r.slice(i+1,e),!1,r.slice(i,e+1)),i=e+1;continue}l=t}s+=e,i++}return{text:s,math:n}}function ve(e,t){for(let n=t;n<e.length;n++){const t=e[n];if("\\"!==t){if("`"===t)return{end:-1,stop:n};if("\n"===t&&/^\n[ \t]*\n/.test(e.slice(n,n+64)))return{end:-1,stop:n};if("$"===t&&!/\s/.test(e[n-1])&&!/\d/.test(e[n+1]??"")&&"$"!==e[n+1])return{end:n,stop:n}}else n++}return{end:-1,stop:e.length}}const be=e=>String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),ye=/^\s*([A-Za-z\u0370-\u03ff](?:_\{?\w+\}?)?)\s*=\s*([^=<>≤≥]+)$/;function we(e,s,i,r){const{text:o,math:a}=ge(e,s),l=i?i.definitions(r):new Map,u=e=>i?i.textOf(e):e.text,c={...s.scope??{}},f={},h=new Map,p=new Set,d=[],m=e=>{const t=new Map;return n=>{const s=l.get(n);if(!s)return null;if(!t.has(n)){let i=null;try{i=K(u(s),e)}catch{}t.set(n,i)}return t.get(n)}};let g=!0;const v=a.map((e,i)=>{const{source:r,display:o}=e;g&&r.includes("{{")&&((()=>{for(const e of Object.keys(f))delete f[e];Object.assign(f,c);for(const e of l.keys())delete f[e];let e=[...l.values()];for(;e.length;){const n=e.filter(e=>{try{const n=t.calculate(u(e),f);if("number"==typeof n.value||"bigint"==typeof n.value||Array.isArray(n.value))return f[e.name]=n.exact?n.text:n.value,!1}catch{}return!0});if(n.length===e.length)break;e=n}const s={},i=m({});for(const e of l.keys()){const t=i(e);if(t)try{s[e]=n.toPostfix(ae(t,t=>t===e?null:i(t)).tree)}catch{}}f[te]=s})(),g=!1);const a=o?"mv-md-display":"mv-md-math",v=(e,t="")=>`<span class="${a}${t}" data-mv-md="${i}">${e}</span>`;try{const n={...s.math,display:o,blocks:s.blocks,scope:f},a=function(e){let t=e.trim();const n=t.startsWith("_");n&&(t=t.slice(1).trimStart());let s=t.indexOf(":="),i=2;s<0&&n&&(s=t.search(/(?<![<>!≤≥=])=(?!=)/),i=1);const r=n?{error:"a hidden $_…$ saves a variable: $_A := 2+2$"}:null;if(s<=0)return r;const o=t.slice(0,s).trim(),a=t.slice(s+i).trim();let l=null;try{l=/\{\{/.test(o)?null:se(K(o))}catch{}return null!==l&&a?{hidden:n,lhs:o,name:l,rhs:a,input:ce(a)}:r}(r);if(a&&a.error)throw new Error(a.error);if(a){const{name:t,input:s,hidden:r}=a,o=s?{name:t,text:s.default,input:s,key:`input:${JSON.stringify(s)}`}:{name:t,text:a.rhs,input:null,key:`expr:${a.rhs}`,start:e.start,end:e.end};let c="";if(s){const e=function(e,t){const{input:n,name:s}=e,i=`class="mv-md-input mv-md-${n.kind}" data-mv-var="${be(s)}" aria-label="${be(s)}"`;if("dropdown"===n.kind)return`<select ${i}>${n.options.map(e=>`<option value="${be(e)}"${e===t?" selected":""}>${be(e)}</option>`).join("")}</select>`;return"slider"===n.kind?`<input type="range" ${i} min="${n.min}" max="${n.max}" step="${n.step}" value="${be(t)}"><output class="mv-md-output" data-mv-out="${be(s)}">${be(t)}</output>`:`<input type="text" ${i} value="${be(t)}" size="${Math.max(4,t.length+1)}" spellcheck="false" autocomplete="off">`}(o,u(o));c=r?e:`${J(a.lhs,n)}<span class="mv-md-assign" aria-hidden="true">≔</span>${e}`,p.add(i)}else{const e=ae(K(a.rhs,n),m(n)).tree;if(!r){const t=_({type:"op",op:"=",args:[B(K(a.lhs)),void 0===e.id?e:B(e)]});d[i]=t,c=function(e,t="mv"){return e.replace(`<span class="${t}-rel">=</span>`,`<span class="${t}-rel ${t}-rel-def">≔</span>`).replace(/(aria-label="[^"]*?) equals /,"$1 is defined as ").replace("<mo>=</mo>","<mo>≔</mo>")}(J(t,n),n.prefix)}}return l.delete(t),l.set(t,o),h.set(t,o),g=!0,r&&!s?"":v(c,s?" mv-md-input-def":"")}const{tree:b,changed:y}=ae(K(r,n),m(n));y&&_(b),d[i]=b;const w=J(b,n);return!y&&!1!==s.define&&function(e,n,s){const i=ye.exec(e);if(!i||/\{\{/.test(i[2]))return!1;const r=i[1].replace(/[{}]/g,"");if(s.has(r))return!1;try{const e=t.calculate(i[2],n);if("number"==typeof e.value||"bigint"==typeof e.value||Array.isArray(e.value))return n[r]=e.exact?e.text:e.value,!0}catch{}return!1}(r,c,l)&&(g=!0),v(w)}catch(t){return`<span class="mv-md-error" data-mv-md="${i}" title="${be(t.message)}"><code>${be(e.raw)}</code></span>`}});return{text:o,math:a,drawn:v,defs:h,inputs:p,trees:d}}const xe=/^(https?:|mailto:|#|\/|\.{0,2}\/|[^:]*$)/i,ke=e=>xe.test(e.trim())?be(e.trim()):"#",qe=/\uE002(\d+)\uE003/g;function $e(e,t,n,s=[]){const i=e=>(s.push(e),`${s.length-1}`),r=e=>(e=>e.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&"))(n(e).replace(qe,(e,t)=>(s[Number(t)]??"").replace(/<[^>]*>/g,"")));let o=e;o=o.replace(/(`+)([\s\S]*?[^`])\1(?!`)/g,(e,t,s)=>i(`<code>${be(n(s.trim()))}</code>`)),o=o.replace(/\\([\\`*_{}[\]()#+\-.!|~$<>"'])/g,(e,t)=>i(be(t))),o=o.replace(/<((?:https?:\/\/|mailto:)[^\s>]+)>/g,(e,t)=>i(`<a href="${ke(t)}">${be(t)}</a>`)),t.html&&(o=o.replace(/<\/?[A-Za-z][^>]*>/g,e=>i(e))),o=o.replace(/!\[([^\[\]]*)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,t,n,s)=>i(`<img src="${ke(r(n))}" alt="${be(r(t))}"${s?` title="${be(r(s))}"`:""}>`)),o=o.replace(/\[([^\[\]]+)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,o,a,l)=>i(`<a href="${ke(r(a))}"${l?` title="${be(r(l))}"`:""}>${$e(o,t,n,s)}</a>`)),o=o.replace(/&(?!#\d{1,7};|#x[0-9a-f]{1,6};|[a-z][a-z0-9]{1,31};)/gi,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),o=o.replace(/(\*\*\*|___)(?=\S)([\s\S]*?\S)\1/g,"<strong><em>$2</em></strong>"),o=o.replace(/(\*\*\*|___)(?=\S)([^*_]*?\S)(\*\*|__)(?![*_])([\s\S]*?\S)(\*|_)(?![*_])/g,"<em><strong>$2</strong>$4</em>"),o=o.replace(/(\*\*\*|___)(?=\S)([^*_]*?\S)(\*|_)(?![*_])([\s\S]*?\S)(\*\*|__)(?![*_])/g,"<strong><em>$2</em>$4</strong>"),o=o.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g,"<strong>$2</strong>"),o=o.replace(/(^|[^*\w])\*(?=\S)([\s\S]*?\S)\*(?!\*)/g,"$1<em>$2</em>"),o=o.replace(/(^|[^_\w])_(?=\S)([\s\S]*?\S)_(?![_\w])/g,"$1<em>$2</em>"),o=o.replace(/~~(?=\S)([\s\S]*?\S)~~/g,"<del>$1</del>"),o=o.replace(/( {2,}|\\)\n/g,"<br>\n");for(let e=0;e<8&&/\uE002\d+\uE003/.test(o);e++)o=o.replace(qe,(e,t)=>s[Number(t)]??"");return o}const Se=/^( {0,3})(#{1,6}\s|>|```|~~~|([-*+]|\d{1,9}[.)])\s|(\*[ \t]*){3,}$|(-[ \t]*){3,}$|(_[ \t]*){3,}$)/,Me=/^( {0,3})([-*+]|\d{1,9}[.)])(\s+|$)/,Oe=/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/,Ae=e=>Se.test(e)&&!/^ {0,3}[-=]+\s*$/.test(e)&&!/^ {0,3}(?!1[.)])\d{1,9}[.)]\s/.test(e);function Ne(e){const t=e.trim();let n=t.length;for(;n>0&&"#"===t[n-1];)n--;return n===t.length?t:0===n?"":/[ \t]/.test(t[n-1])?t.slice(0,n).trimEnd():t}function Ee(e,t,n,s=0){const i=[];let r=0;const o=e=>$e(e,t,n);if(s>100)return`<p>${o(e.join("\n"))}</p>`;for(;r<e.length;){const a=e[r];if(!a.trim()){r++;continue}const l=/^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)/.exec(a);if(l){const t=[];for(r++;r<e.length&&!new RegExp(`^ {0,3}${"`"===l[1][0]?"`":"~"}{${l[1].length},}\\s*$`).test(e[r]);)t.push(e[r++]);r++;const s=l[2]?` class="language-${be(l[2])}"`:"";i.push(`<pre><code${s}>${be(n(t.join("\n")))}</code></pre>`);continue}const u=/^ {0,3}(#{1,6})[ \t]+/.exec(a);if(u){i.push(`<h${u[1].length}>${o(Ne(a.slice(u[0].length)))}</h${u[1].length}>`),r++;continue}if(/^ {0,3}((\*[ \t]*){3,}|(-[ \t]*){3,}|(_[ \t]*){3,})$/.test(a)){i.push("<hr>"),r++;continue}if(/^ {0,3}>/.test(a)){const o=[];for(;r<e.length&&e[r].trim()&&(/^ {0,3}>/.test(e[r])||o.length);)o.push(e[r].replace(/^ {0,3}> ?/,"")),r++;i.push(`<blockquote>\n${Ee(o,t,n,s+1)}\n</blockquote>`);continue}const c=Me.exec(a);if(c){const o=/\d/.test(c[2]),a=o?parseInt(c[2],10):1,l=[];let u=!1;for(;r<e.length;){const t=Me.exec(e[r]);if(!t||/\d/.test(t[2])!==o)break;const n=t[0].length,s=[e[r].slice(n)];for(r++;r<e.length;){const t=e[r];if(!t.trim()){const t=e[r+1];if(void 0!==t&&t.startsWith(" ".repeat(Math.min(n,4)))&&t.trim()){s.push(""),u=!0,r++;continue}void 0!==t&&Me.test(t)&&(u=!0);break}if(t.startsWith(" ".repeat(Math.min(n,4))))s.push(t.slice(Math.min(n,4)));else{if(Me.test(t)||Se.test(t))break;s.push(t)}r++}for(l.push(s);r<e.length&&!e[r].trim()&&void 0!==e[r+1]&&Me.test(e[r+1]);)r++}const f=o?"ol":"ul",h=l.map(e=>{let i=Ee(e,t,n,s+1);return u||(i=i.replace(/^<p>([\s\S]*?)<\/p>/,"$1").replace(/\n<p>([\s\S]*?)<\/p>/g,"\n$1")),`<li>${i}</li>`});i.push(`<${f}${o&&1!==a?` start="${a}"`:""}>\n${h.join("\n")}\n</${f}>`);continue}if(a.includes("|")&&void 0!==e[r+1]&&Oe.test(e[r+1])&&e[r+1].includes("-")){const t=e=>e.trim().replace(/^\|/,"").replace(/\|$/,"").split(/(?<!\\)\|/).map(e=>e.trim()),n=t(e[r+1]).map(e=>e.startsWith(":")&&e.endsWith(":")?"center":e.endsWith(":")?"right":e.startsWith(":")?"left":""),s=(e,t,s)=>`<${e}${n[s]?` style="text-align:${n[s]}"`:""}>${o(t)}</${e}>`,l=t(a);r+=2;const u=[];for(;r<e.length&&e[r].trim()&&e[r].includes("|");)u.push(t(e[r++]));i.push(`<table>\n<thead><tr>${l.map((e,t)=>s("th",e,t)).join("")}</tr></thead>\n<tbody>\n${u.map(e=>`<tr>${l.map((t,n)=>s("td",e[n]??"",n)).join("")}</tr>`).join("\n")}\n</tbody>\n</table>`);continue}if(/^( {4}|\t)/.test(a)){const t=[];for(;r<e.length&&(/^( {4}|\t)/.test(e[r])||!e[r].trim());)t.push(e[r++].replace(/^( {4}|\t)/,""));for(;t.length&&!t[t.length-1].trim();)t.pop();i.push(`<pre><code>${be(n(t.join("\n")))}</code></pre>`);continue}const f=[];for(;r<e.length&&e[r].trim()&&(!f.length||!Ae(e[r]));){if(f.length&&/^ {0,3}(=+|-+)\s*$/.test(e[r])){const t="="===e[r].trim()[0]?1:2;i.push(`<h${t}>${o(f.join("\n"))}</h${t}>`),f.length=0,r++;break}f.push(e[r].replace(/^ {0,3}/,"")),r++}f.length&&i.push(`<p>${o(f.join("\n"))}</p>`)}return i.join("\n")}function Ie(e,t={},n=e=>e){return Ee(String(e).replace(/\r\n?/g,"\n").replace(/[\uE002\uE003]/g,"�").split("\n"),t,n)}function Te({text:e,math:t,drawn:n},s){return(s.render?s.render(e):Ie(e,s,e=>e.replace(me,(e,n)=>t[Number(n)]?.raw??""))).replace(new RegExp("<p>\\s*(\\d+)\\s*</p>","g"),(e,s)=>t[Number(s)].display&&n[Number(s)]?`<div class="mv-md-block">${n[Number(s)]}</div>`:e).replace(me,(e,t)=>n[Number(t)]??"").replace(/<p>\s*<\/p>\n?/g,"")}const Le=new WeakMap,je=new Set;function Ce(){for(const e of je)e.connected()&&!e.element.isConnected&&e.stop(!0)}const ze=new Map,Ze=-1,Be="\\:",Fe=e=>"string"==typeof e&&e.startsWith(Be)&&e.length>2;function De(e){if(!e||!e.symbol)throw new Error("operator needs a symbol");if(!Number.isInteger(e.arity)||e.arity<0&&e.arity!==Ze)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 t={symbol:e.symbol,arity:e.arity,commutative:!!e.commutative,fold:"function"==typeof e.fold?e.fold:null,label:e.label||e.symbol};return ze.set(t.symbol,t),t}const Pe=Object.freeze({symbol:Be,arity:Ze,commutative:!1,fold:null,label:"function"});function Re(e){const t=ze.get(e);return t||(Fe(e)?{...Pe,symbol:e,label:e.slice(2)}:null)}function We(e){return ze.has(e)||Fe(e)}const _e=e=>Number.isFinite(e)&&Number.isInteger(e)?e:null,Ve=e=>Number.isFinite(e)?e:null;!function(){De({symbol:"+",arity:2,commutative:!0,label:"add",fold:(e,t)=>Ve(e+t)}),De({symbol:"-",arity:2,label:"subtract",fold:(e,t)=>Ve(e-t)}),De({symbol:"*",arity:2,commutative:!0,label:"multiply",fold:(e,t)=>Ve(e*t)}),De({symbol:"/",arity:2,label:"divide",fold:(e,t)=>0===t?null:_e(e/t)}),De({symbol:"^",arity:2,label:"power",fold:(e,t)=>Number.isInteger(t)&&Math.abs(t)<=64?Ve(e**t):null}),De({symbol:"neg",arity:1,label:"negate",fold:e=>Ve(-e)}),De({symbol:"pm",arity:1,label:"plus or minus"}),De({symbol:"±",arity:2,label:"plus or minus"}),De({symbol:"mod",arity:2,label:"modulo",fold:(e,t)=>0===t?null:_e((e%t+t)%t)}),De({symbol:"!",arity:1,label:"factorial",fold:e=>Number.isInteger(e)&&e>=0&&e<=18?[...Array(e).keys()].reduce((e,t)=>e*(t+1),1):null}),De({symbol:"_",arity:2,label:"subscript"}),De({symbol:"der",arity:2,label:"derivative"}),De({symbol:"evaluated",arity:4,label:"evaluated from a to b"}),De({symbol:"setbuilder",arity:2,label:"the set of … such that"}),De({symbol:"int",arity:Ze,label:"integral"}),De({symbol:"lim",arity:Ze,label:"limit"}),De({symbol:"\\sumidx",arity:Ze,label:"sum over an index"}),De({symbol:"\\prodidx",arity:Ze,label:"product over an index"}),De({symbol:"abs",arity:1,label:"absolute value",fold:e=>Ve(Math.abs(e))}),De({symbol:"floor",arity:1,label:"floor",fold:e=>Ve(Math.floor(e))}),De({symbol:"ceil",arity:1,label:"ceiling",fold:e=>Ve(Math.ceil(e))}),De({symbol:"round",arity:2,label:"round",fold:(e,t)=>Number.isInteger(t)?Ve(Math.round(e*10**t)/10**t):null}),De({symbol:"fixed",arity:2,label:"fixed",fold:()=>null}),De({symbol:"sqrt",arity:1,label:"square root",fold:e=>_e(Math.sqrt(e))}),De({symbol:"root",arity:2,label:"nth root",fold:(e,t)=>_e(Math.round(t**(1/e))**e===t?Math.round(t**(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"])De({symbol:e,arity:1,label:e});De({symbol:"log",arity:2,label:"log to a base"}),De({symbol:"atan2",arity:2,label:"atan2"}),De({symbol:"perm",arity:2,label:"permutations"}),De({symbol:"comb",arity:2,label:"combinations"}),De({symbol:"random",arity:0,label:"random"});for(const e of["max","min","gcd","mean","sum","prod"])De({symbol:e,arity:Ze,label:e});for(const e of["()","[]","{}","(]","[)"])De({symbol:e,arity:Ze,label:"group"});for(const e of["pmatrix","bmatrix","vmatrix"])De({symbol:e,arity:Ze,label:"matrix"});De({symbol:"det",arity:1,label:"determinant"});for(const e of["=","===","≠","≠=","<",">","≤","≥","∈","∉","∪","∩","≈","≡","→","pmod","&","|","\\xor","\\nand","\\nor","\\implies","\\iff"])De({symbol:e,arity:2,label:e});De({symbol:"\\not",arity:1,label:"not"}),De({symbol:"?:",arity:3,label:"if then else"})}();const Ue="num",He="sym",Ke="op",Je=Object.freeze([]);class Qe extends Error{constructor(e){super(e),this.name="ExprError"}}function Ye(e){if("number"!=typeof e||!Number.isFinite(e))throw new Qe(`not a finite number: ${e}`);const t=(n=e,Object.is(n,-0)?"0":String(n));var n;return Object.freeze({type:Ue,token:t,value:e,args:Je,s:t})}function Ge(e){if("string"!=typeof e||""===e)throw new Qe("symbol needs a non-empty token");return Object.freeze({type:He,token:e,value:null,args:Je,s:e})}function Xe(e){const t=/^(-?)0*(\d+?)(?:\.(\d*?)0*)?$/.exec(String(e));if(!t)throw new Qe(`not an exact decimal: ${e}`);const[,n,s,i=""]=t,r=i?`${s}.${i}`:s,o=/^0(\.0*)?$/.test(r)?"0":n+r;return Object.freeze({type:Ue,token:o,value:Number(o),args:Je,s:o})}const et=/^-?\d+(\.\d+)?$/;function tt(e){const t=String(e);if(et.test(t))return Xe(t);if(""!==t&&!/\s/.test(t)){const e=Number(t);if(Number.isFinite(e))return Ye(e)}return Ge(t)}function nt(e,t){const n=Re(e);if(!n)throw new Qe(`unknown operator "${e}"`);if(n.arity!==Ze&&t.length!==n.arity)throw new Qe(`"${e}" takes ${n.arity} operand(s), got ${t.length}`);const s=Object.freeze(t.slice()),i=n.arity===Ze?` ${s.length}`:"",r=`${s.length?s.map(e=>e.s).join(" "):""}${s.length,""}${i} ${e}`.trimStart();return Object.freeze({type:Ke,op:e,token:e,value:null,args:s,s:r})}const st=e=>e.type===Ue,it=e=>e.type===Ke;function rt(e){return ot(function(e){const t=String(e).trim();return""===t?[]:t.split(/\s+/)}(e))}function ot(e){if(!Array.isArray(e))throw new Qe("fromPostfix needs an array of tokens");if(0===e.length)throw new Qe("empty expression");const t=[];for(let n=0;n<e.length;n++){const s=String(e[n]);if(We(s)){let e=Re(s).arity;if(e===Ze){const i=t.pop();if(e=i&&i.type===Ue&&Number.isInteger(i.value)&&i.value>=0?i.value:-1,e<0)throw new Qe(`"${s}" at position ${n+1} takes any number of operands, so a count must come before it`)}if(t.length<e)throw new Qe(`"${s}" at position ${n+1} needs ${e} operand(s), only ${t.length} on the stack`);const i=t.splice(t.length-e,e);t.push(nt(s,i))}else t.push(tt(s))}if(1!==t.length){const n=[...new Set(e.filter(e=>!We(e)))];throw new Qe(`expression leaves ${t.length} values on the stack; it should leave exactly 1. Read as operands: ${n.join(", ")} — is one of those meant to be an operator?`)}return t[0]}function at(e){if(e.type!==Ke)return 0;let t=0;for(const n of e.args)t=Math.max(t,at(n));return t+1}function lt(e){if(e.type!==Ke)return 1;let t=1;for(const n of e.args)t+=lt(n);return t}function ut(e,t=[]){if(e.type!==Ke)t.push(e.token);else for(const n of e.args)ut(n,t);return t}function ct(e){return e.type===Ue||e.type!==He&&e.args.every(ct)}function ft(e,t="pre",n=[],s=[]){"pre"===t&&s.push({node:e,path:n});for(let i=0;i<e.args.length;i++)ft(e.args[i],t,n.concat(i),s);return"post"===t&&s.push({node:e,path:n}),s}function ht(e,t){let n=e;for(const e of t){if(!n.args[e])throw new Qe(`bad path [${t.join(",")}]`);n=n.args[e]}return n}function pt(e,t,n){if(0===t.length)return n;const[s,...i]=t,r=e.args.slice();return r[s]=pt(r[s],i,n),nt(e.op,r)}class dt extends Error{constructor(e){super(e),this.name="CasError"}}const mt=1e5,gt=e=>e<0n?-e:e,vt=e=>0n===e?0:gt(e).toString(2).length;function bt(e,t){for(e=gt(e),t=gt(t);t;)[e,t]=[t,e%t];return e}class yt{constructor(e,t=1n){if(0n===t)throw new dt("division by zero");t<0n&&(e=-e,t=-t);const n=bt(e,t)||1n;if(this.n=e/n,this.d=t/n,vt(this.n)>mt||vt(this.d)>mt)throw new dt("a number too large to keep exactly")}static of(e){return new yt(BigInt(e))}add(e){return new yt(this.n*e.d+e.n*this.d,this.d*e.d)}sub(e){return new yt(this.n*e.d-e.n*this.d,this.d*e.d)}mul(e){return new yt(this.n*e.n,this.d*e.d)}div(e){if(0n===e.n)throw new dt("division by zero");return new yt(this.n*e.d,this.d*e.n)}neg(){return new yt(-this.n,this.d)}abs(){return this.n<0n?this.neg():this}inv(){return yt.ONE.div(this)}pow(e){if((e=BigInt(e))<0n)return this.inv().pow(-e);if((0n===this.n||1n===gt(this.n))&&1n===this.d)return 0n===e||-1n===this.n&&e%2n==0n?yt.ONE:this;if(BigInt(Math.max(vt(this.n),vt(this.d)))*e>BigInt(mt))throw new dt("a power too large to work out exactly");return new yt(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 t=this.n*e.d,n=e.n*this.d;return t<n?-1:t>n?1:0}floor(){const e=this.n/this.d;return new yt(this.n<0n&&e*this.d!==this.n?e-1n:e)}ceil(){return this.neg().floor().neg()}toNumber(){const e=Number(this.n),t=Number(this.d);if(Number.isFinite(e)&&Number.isFinite(t))return e/t;const n=BigInt(Math.max(vt(this.n),vt(this.d))-1e3);return Number(this.n>>n)/Number(this.d>>n)}toString(){return 1n===this.d?String(this.n):`${this.n}/${this.d}`}}function wt(e){const t=/^(-?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(String(e));if(!t||""===t[2]&&!t[3])return null;const[,n,s,i="",r="0"]=t;let o=new yt(BigInt((s||"0")+i),10n**BigInt(i.length));const a=Number(r);return a&&(o=o.mul(yt.of(10).pow(a))),n?o.neg():o}function xt(e,t){if(e<2n)return e;if(t>=vt(e))return 1n;const n=BigInt(t);let s=1n<<BigInt(Math.ceil(vt(e)/t));for(;;){const t=((n-1n)*s+e/s**(n-1n))/n;if(t>=s)break;s=t}for(;s**n>e;)s--;for(;(s+1n)**n<=e;)s++;return s}yt.ZERO=new yt(0n),yt.ONE=new yt(1n),yt.MINUS_ONE=new yt(-1n),yt.HALF=new yt(1n,2n);const kt=(()=>{const e=[],t=new Uint8Array(1e4);for(let n=2;n<t.length;n++)if(!t[n]){e.push(BigInt(n));for(let e=n*n;e<t.length;e+=n)t[e]=1}return e})();function qt(e,t){const n=BigInt(t);let s=1n,i=1n,r=e;for(const e of kt){if(e*e>r)break;if(r%e)continue;let t=0n;for(;r%e===0n;)r/=e,t++;s*=e**(t/n),i*=e**(t%n)}if(r>1n){const e=function(e,t){if(e<0n)return null;if(e<2n)return e;const n=xt(e,t);return n**BigInt(t)===e?n:null}(r,t);null!==e?s*=e:i*=r}return{outside:s,inside:i}}const $t=new Set(["pi","e","π"]),St={complex:!1};function Mt(e,t){const n=St.complex;St.complex=Boolean(e);try{return t()}finally{St.complex=n}}const Ot=e=>$t.has(e)||St.complex&&"i"===e,At=e=>St.complex&&"atom"===e.k&&"sym"===e.node.type&&"i"===e.node.token,Nt=e=>({k:"num",q:e}),Et=Nt(yt.ONE),It=Nt(yt.ZERO),Tt=Nt(yt.HALF),Lt=e=>"num"===e.k,jt=e=>({k:"atom",node:e}),Ct=new WeakMap;function zt(e){let t=Ct.get(e);return void 0===t&&Ct.set(e,t=mn(e).s),t}function Zt(e){if("num"===e.k)return 0;if("atom"===e.k)return"sym"===e.node.type&&Ot(e.node.token)?0:1;if("add"===e.k)return Math.max(...e.terms.map(e=>Zt(e.x)));let t=0;for(const n of e.fs){const e=Zt(n.b);e&&(t+=e*(Lt(n.e)?n.e.q.toNumber():1))}return t}function Bt(e,t){return"num"===e.k?t&&!Lt(t)?3:0:At(e)?1.5:"atom"===e.k&&"sym"===e.node.type?Ot(e.node.token)?t&&!Lt(t)?3:1:2:"atom"===e.k?3:4}const Ft=(e,t)=>e<t?-1:e>t?1:0;function Dt(e){const t=new Map,n=(e,n)=>{"atom"!==e.k||"sym"!==e.node.type||Ot(e.node.token)||t.set(e.node.token,(t.get(e.node.token)??0)+n)};if("mul"===e.k)for(const t of e.fs)n(t.b,Lt(t.e)?t.e.q.toNumber():1);else n(e,1);return t}function Pt(e,t){const n=Zt(t.x)-Zt(e.x);if(n)return n;const s=Dt(e.x),i=Dt(t.x);for(const e of[...new Set([...s.keys(),...i.keys()])].sort()){const t=(i.get(e)??0)-(s.get(e)??0);if(t)return t}return Ft(zt(e.x),zt(t.x))}function Rt(e,t){return e.isOne?t:e.isZero?It:Ut([Nt(e),t])}function Wt(e){if("num"===e.k)return{coef:e.q,rest:null};if("mul"!==e.k||e.c.isOne)return{coef:yt.ONE,rest:e};const t=1===e.fs.length&&Lt(e.fs[0].e)&&e.fs[0].e.q.isOne?e.fs[0].b:{k:"mul",c:yt.ONE,fs:e.fs};return{coef:e.c,rest:t}}function _t(e){let t=yt.ZERO;const n=new Map,s=(e,t)=>{const s=zt(t),i=n.get(s);i?i.coef=i.coef.add(e):n.set(s,{coef:e,x:t})};for(const n of e)if("num"===n.k)t=t.add(n.q);else if("add"===n.k){t=t.add(n.c);for(const e of n.terms)s(e.coef,e.x)}else{const{coef:e,rest:t}=Wt(n);s(e,t)}const i=[...n.values()].filter(e=>!e.coef.isZero);return i.length?t.isZero&&1===i.length?Rt(i[0].coef,i[0].x):(i.sort(Pt),{k:"add",c:t,terms:i}):Nt(t)}function Vt(e,t){if(!Lt(t))return e.isOne?{coef:yt.ONE,fs:[]}:{coef:yt.ONE,fs:[{b:Nt(e),e:t}]};const n=t.q;if(n.isInteger)return{coef:e.pow(n.n),fs:[]};if(e.isZero){if(n.sign<0)throw new dt("division by zero");return{coef:yt.ZERO,fs:[]}}if(e.isOne)return{coef:yt.ONE,fs:[]};if(e.sign<0){if(n.d%2n==1n){const{coef:s,fs:i}=Vt(e.neg(),t);return{coef:n.n%2n==0n?s:s.neg(),fs:i}}if(St.complex&&2n===n.d){const{coef:s,fs:i}=Vt(e.neg(),t);return{coef:s,fs:[...i,{b:Jt,e:Nt(new yt(n.n))}]}}return{coef:yt.ONE,fs:[{b:Nt(e),e:t}]}}if(!e.isInteger){const s=Vt(new yt(e.n),t),i=Vt(new yt(e.d),Nt(n.neg()));return{coef:s.coef.mul(i.coef),fs:[...s.fs,...i.fs]}}const s=n.floor(),i=n.sub(s);if(BigInt(vt(e.n))*i.n>BigInt(mt)||i.d>1000n)return{coef:yt.ONE,fs:[{b:Nt(e),e:t}]};let r=s.isZero?yt.ONE:e.pow(s.n);const{outside:o,inside:a}=qt(e.n**i.n,Number(i.d));r=r.mul(new yt(o));return{coef:r,fs:a>1n?[{b:Nt(new yt(a)),e:Nt(new yt(1n,i.d))}]:[]}}function Ut(e){let t=yt.ONE;const n=new Map,s=(e,t)=>{const s=zt(e),i=n.get(s);i?i.e=_t([i.e,t]):n.set(s,{b:e,e:t})};for(const n of e)if("num"===n.k)t=t.mul(n.q);else if("mul"===n.k){t=t.mul(n.c);for(const e of n.fs)s(e.b,e.e)}else s(n,Et);if(t.isZero)return It;const i=[],r=new Map;for(const e of n.values())if(!Lt(e.e)||!e.e.q.isZero){if("num"===e.b.k){if(Lt(e.e)&&!e.e.q.isInteger&&e.b.q.sign>0&&e.b.q.isInteger){const t=e.e.q.toString(),n=r.get(t);n?n.n*=e.b.q.n:r.set(t,{n:e.b.q.n,e:e.e});continue}const n=Vt(e.b.q,e.e);t=t.mul(n.coef),i.push(...n.fs);continue}if("mul"===e.b.k&&Lt(e.e)&&e.e.q.isInteger){const n=Ht(e.b,e.e);"mul"===n.k?(t=t.mul(n.c),i.push(...n.fs)):"num"===n.k?t=t.mul(n.q):i.push({b:n,e:Et});continue}i.push(e)}for(const{n:e,e:n}of r.values()){const s=Vt(new yt(e),n);t=t.mul(s.coef),i.push(...s.fs)}if(t.isZero)return It;const o=new Map;for(const e of i){const t=zt(e.b),n=o.get(t);n?n.e=_t([n.e,e.e]):o.set(t,{...e})}let a=[...o.values()].filter(e=>!(Lt(e.e)&&e.e.q.isZero));if(St.complex){a=a.flatMap(e=>{if(!At(e.b)||!Lt(e.e)||!e.e.q.isInteger)return[e];const n=(e.e.q.n%4n+4n)%4n;return n>=2n&&(t=t.neg()),n%2n?[{b:e.b,e:Et}]:[]});const e=a.filter(e=>"add"===e.b.k&&Lt(e.e)&&e.e.q.isInteger&&Yt(e.b)),n=a.some(e=>At(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||n||!e[0].e.q.isOne)){const s=a.filter(t=>!e.includes(t)&&!At(t.b));let i=n?[Jt]:[Et];for(const t of e){const e=t.e.q.sign<0?en(t.b):t.b;for(let n=0n;n<(t.e.q.sign<0?-t.e.q.n:t.e.q.n);n++)i=Gt(i,yn(e))}return Ut([Nt(t),_t(i),...s.map(e=>Kt(e.b,e.e))])}}if(a.some(e=>"num"===e.b.k&&Lt(e.e)&&e.e.q.compare(yt.ONE)>=0))return Ut([Nt(t),...a.map(e=>"num"===e.b.k?Ht(e.b,e.e):{k:"mul",c:yt.ONE,fs:[e]})]);if(!a.length)return Nt(t);if(1===a.length&&!t.isOne&&"add"===a[0].b.k&&Lt(a[0].e)&&a[0].e.q.isOne){const e=a[0].b;return _t([Nt(t.mul(e.c)),...e.terms.map(e=>Rt(t.mul(e.coef),e.x))])}return t.isOne&&1===a.length&&Lt(a[0].e)&&a[0].e.q.isOne?a[0].b:(a=a.sort((e,t)=>Bt(e.b,e.e)-Bt(t.b,t.e)||Ft(zt(e.b),zt(t.b))),{k:"mul",c:t,fs:a})}function Ht(e,t){if(St.complex&&Lt(t)&&t.q.isInteger){if(At(e))return Ut([{k:"mul",c:yt.ONE,fs:[{b:e,e:t}]}]);if("add"===e.k&&Yt(e)&&!t.q.isOne)return Ut([{k:"mul",c:yt.ONE,fs:[{b:e,e:t}]}])}if(Lt(t)){if(t.q.isZero){if(Lt(e)&&e.q.isZero)throw new dt("0^0 is undefined");return Et}if(t.q.isOne)return e}if(Lt(e)){const n=Vt(e.q,t);if(!n.fs.length)return Nt(n.coef);if(n.fs.some(e=>At(e.b)))return Ut([Nt(n.coef),...n.fs.map(e=>({k:"mul",c:yt.ONE,fs:[e]}))]);const s={k:"mul",c:n.coef,fs:n.fs};return n.coef.isOne&&1===n.fs.length&&Lt(n.fs[0].e)&&n.fs[0].e.q.isOne?n.fs[0].b:s}if(St.complex&&Lt(t)&&2n===t.q.d&&Yt(e)){const n=Xt(e);if(n&&Lt(n.im)&&!n.im.q.isZero){const e=e=>Ht(e,Nt(yt.of(2))),s=Ht(_t([e(n.re),e(n.im)]),Tt),i=Ht(Ut([_t([s,n.re]),Nt(yt.HALF)]),Tt),r=Ht(Ut([_t([s,sn(n.re)]),Nt(yt.HALF)]),Tt);return Ht(_t([i,Ut([Nt(yt.of(n.im.q.sign)),r,Jt])]),Nt(new yt(t.q.n)))}}if("mul"===e.k){if(Lt(t)&&t.q.isInteger)return Ut([Nt(e.c.pow(t.q.n)),...e.fs.map(e=>Kt(e.b,Ut([e.e,t])))]);if(!e.c.isOne&&e.c.sign>0)return Ut([Ht(Nt(e.c),t),Ht({k:"mul",c:yt.ONE,fs:e.fs},t)]);if(e.c.isOne&&1===e.fs.length){const[n]=e.fs;if(Lt(n.e)&&Lt(t)&&1n===n.e.q.n&&n.e.q.d%2n==1n)return Kt(n.b,Ut([n.e,t]))}}return{k:"mul",c:yt.ONE,fs:[{b:e,e:t}]}}function Kt(e,t){return Lt(t)&&t.q.isZero?Et:Lt(e)?Ht(e,t):Lt(t)&&t.q.isOne?e:{k:"mul",c:yt.ONE,fs:[{b:e,e:t}]}}const Jt=jt(Ge("i")),Qt=e=>St.complex&&mn(e).s.split(" ").includes("i");function Yt(e){return St.complex&&Qt(e)&&0===bn(mn(e)).size}function Gt(e,t){const n=[];for(const s of e)for(const e of t)n.push(Ut([s,e]));return yn(_t(n))}function Xt(e){const t=[],n=[];for(const s of yn(e)){const{coef:e,rest:i}=Wt(s),r=i?wn(i):[],o=r.filter(e=>At(e)),a=r.filter(e=>!At(e));if(a.some(e=>Qt(e)))return null;(o.length?n:t).push(Ut([Nt(e),...a]))}return{re:_t(t),im:_t(n)}}function en(e){const t=Xt(e);if(!t)return Ht(e,Nt(yt.MINUS_ONE));const n=_t([Ht(t.re,Nt(yt.of(2))),Ht(t.im,Nt(yt.of(2)))]);return Ut([_t([t.re,Ut([Nt(yt.MINUS_ONE),t.im,Jt])]),Ht(n,Nt(yt.MINUS_ONE))])}const tn={re:([e])=>Xt(e)?.re??null,im:([e])=>Xt(e)?.im??null,conj:([e])=>{const t=Xt(e);return t?_t([t.re,Ut([Nt(yt.MINUS_ONE),t.im,Jt])]):null},arg:([e])=>{const t=Xt(e);return t?ln("atan2",[t.im,t.re]):null},abs:([e])=>{const t=Xt(e);return!t||Lt(t.im)&&t.im.q.isZero?null:Ht(_t([Ht(t.re,Nt(yt.of(2))),Ht(t.im,Nt(yt.of(2)))]),Tt)}},nn={Re:"re",re:"re",Im:"im",im:"im",conj:"conj",overline:"conj",bar:"conj",arg:"arg"},sn=e=>Ut([Nt(yt.MINUS_ONE),e]),rn=(e,t)=>Ut([e,Ht(t,Nt(yt.MINUS_ONE))]),on=3000n,an={abs:([e])=>Lt(e)?Nt(e.q.abs()):"mul"!==e.k||e.c.isOne?null:Ut([Nt(e.c.abs()),ln("abs",[Wt(e).rest])]),floor:([e])=>Lt(e)?Nt(e.q.floor()):null,ceil:([e])=>Lt(e)?Nt(e.q.ceil()):null,"!":([e])=>{if(!Lt(e)||!e.q.isInteger||e.q.sign<0||e.q.n>on)return null;let t=1n;for(let n=2n;n<=e.q.n;n++)t*=n;return Nt(new yt(t))},mod:([e,t])=>Lt(e)&&Lt(t)&&!t.q.isZero?Nt(e.q.sub(t.q.mul(e.q.div(t.q).floor()))):null,max:e=>e.every(Lt)&&e.length?e.reduce((e,t)=>t.q.compare(e.q)>0?t:e):null,min:e=>e.every(Lt)&&e.length?e.reduce((e,t)=>t.q.compare(e.q)<0?t:e):null,gcd:e=>e.length&&e.every(e=>Lt(e)&&e.q.isInteger)?Nt(new yt(e.reduce((e,t)=>bt(e,t.q.n),0n))):null,log:([e,t])=>{if(!Lt(e)||!Lt(t)||e.q.sign<=0||t.q.sign<=0||e.q.isOne)return null;if(t.q.isOne)return It;const n=Math.log(t.q.toNumber())/Math.log(e.q.toNumber());if(!Number.isFinite(n))return null;for(let s=1;s<=12;s++){const i=Math.round(n*s);if(!(Math.abs(n*s-i)>1e-9||0===i)&&(Math.abs(i)<=256&&e.q.pow(BigInt(i)).equals(t.q.pow(BigInt(s)))))return Nt(new yt(BigInt(i),BigInt(s)))}return null},comb:([e,t])=>Lt(e)&&Lt(t)&&e.q.isInteger&&t.q.isInteger&&e.q.sign>=0&&t.q.sign>=0&&e.q.n<=on?Nt(function(e,t){if(t>e)return yt.ZERO;t>e-t&&(t=e-t);let n=1n;for(let s=1n;s<=t;s++)n=n*(e-t+s)/s;return new yt(n)}(e.q.n,t.q.n)):null,perm:([e,t])=>{if(!(Lt(e)&&Lt(t)&&e.q.isInteger&&t.q.isInteger&&e.q.sign>=0&&t.q.sign>=0&&e.q.n<=on))return null;if(t.q.n>e.q.n)return It;let n=1n;for(let s=0n;s<t.q.n;s++)n*=e.q.n-s;return Nt(new yt(n))}};function ln(e,t){if(St.complex&&tn[e]){const n=tn[e](t);if(n)return n}const n=an[e];if(n){const e=n(t);if(e)return e}return jt(nt(e,t.map(mn)))}const un=new Map;function cn(e){const t=St.complex?`ℂ ${e.s}`:e.s,n=un.get(t);if(n)return n;const s=function(e){if("num"===e.type){const t=wt(e.token);if(!t)throw new dt(`not an exact number: ${e.token}`);return Nt(t)}if("sym"===e.type)return"π"===e.token?jt(Ge("pi")):jt(e);const t=e.args.map(cn);switch(e.op){case"+":return _t(t);case"-":return((e,t)=>_t([e,sn(t)]))(t[0],t[1]);case"neg":return sn(t[0]);case"*":return Ut(t);case"/":return rn(t[0],t[1]);case"^":return Ht(t[0],t[1]);case"sqrt":return Ht(t[0],Tt);case"root":return Ht(t[1],Ht(t[0],Nt(yt.MINUS_ONE)));default:{const n=e.op.startsWith("\\:")?e.op.slice(2):null;return n&&St.complex&&nn[n]&&1===t.length?ln(nn[n],t):n&&We(n)&&Re(n).arity===t.length?ln(n,t):ln(e.op,t)}}}(e);return un.size>2e4&&un.clear(),un.set(t,s),s}const fn=e=>mn(cn(e)),hn=e=>Xe(String(e));function pn(e){return e.isInteger?hn(e.n):nt("/",[hn(e.n),hn(e.d)])}const dn=new WeakMap;function mn(e){let t=dn.get(e);return t||dn.set(e,t=function(e){switch(e.k){case"num":return pn(e.q);case"atom":return e.node;case"mul":return function(e,t){const n=[],s=[];for(const e of t)Lt(e.e)&&e.e.q.sign<0?s.push(gn(e.b,Nt(e.e.q.neg()))):n.push(gn(e.b,e.e));let i=1n!==e.n&&-1n!==e.n||!n.length?vn([hn(e.n),...n]):vn(n);-1n===e.n&&n.length&&(i=nt("neg",[i]));1n!==e.d&&s.unshift(hn(e.d));return s.length?nt("/",[i,vn(s)]):i}(e.c,e.fs);case"add":return function(e){let t=null;const n=e=>St.complex&&Qt(e.x)&&0===bn(mn(e.x)).size,s=[...e.terms.filter(e=>!n(e)),...e.terms.filter(n)],i=e.c,r=()=>{i.isZero||(t=t?i.sign<0?nt("-",[t,pn(i.neg())]):nt("+",[t,pn(i)]):pn(i))};let o=!1;for(const e of s)!o&&n(e)&&(r(),o=!0),t=t?e.coef.sign<0?nt("-",[t,mn(Rt(e.coef.neg(),e.x))]):nt("+",[t,mn(Rt(e.coef,e.x))]):mn(Rt(e.coef,e.x));o||r();return t}(e);default:throw new Error(`bad form ${e.k}`)}}(e)),t}function gn(e,t){const n=mn(e);if(Lt(t)){const e=t.q;if(e.isOne)return n;if(1n===e.n&&2n===e.d)return nt("sqrt",[n]);if(1n===e.n)return nt("root",[hn(e.d),n])}return nt("^",[n,mn(t)])}const vn=e=>e.reduce((e,t)=>e?nt("*",[e,t]):t,null);function bn(e,t=new Set){if("sym"===e.type)Ot(e.token)||t.add(e.token);else if(it(e))for(const n of e.args)bn(n,t);return t}function yn(e){if("add"!==e.k)return[e];const t=e.terms.map(e=>Rt(e.coef,e.x));return e.c.isZero||t.push(Nt(e.c)),t}function wn(e){if("num"===e.k)return[e];if("mul"!==e.k)return[e];const t=e.c.isOne?[]:[Nt(e.c)];for(const n of e.fs)t.push(Kt(n.b,n.e));return t}const xn="_",kn=new WeakMap;function qn(e,t){return[...t,...Re(e.op)?.arity===Ze?[String(e.args.length)]:[],e.op].join(" ")}function $n(e,t){let n=kn.get(e);n||kn.set(e,n=new Map);const s=n.get(t);if(s)return s;const i=function(e,t){const n={key:xn,slots:[e]};if(e.type!==Ke||t<=0)return[n];const s=e.args.map(e=>$n(e,t-1)),i=[n],r=new Array(s.length).fill(0);for(;;){const t=[],n=[];for(let e=0;e<s.length;e++){const i=s[e][r[e]];t.push(i.key);for(const e of i.slots)n.push(e)}if(i.push({key:qn(e,t),slots:n}),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,t);return n.set(t,i),i}function Sn(e){return e.type!==Ke?xn:qn(e,e.args.map(Sn))}function Mn(e,t=[]){if(e.type!==Ke)t.push(e);else for(const n of e.args)Mn(n,t);return t}const On=new Map,An=new Map;class Nn extends Error{constructor(e){super(e),this.name="RequirementError"}}function En(e,t,n=""){On.set(e,{name:e,fn:t,doc:n,arity:Math.max(0,t.length-1)})}function In(e,t,n=""){An.set(e,{name:e,fn:t,doc:n})}function Tn(e){return On.get(e)||null}function Ln(e){return An.get(e)||null}const jn=e=>e.type===Ue;function Cn(e,t){return e.type===Ke&&(e.op===t||e.args.some(e=>Cn(e,t)))}En("always",()=>!0,"matches anything"),En("never",()=>!1,"matches nothing"),En("isLeaf",e=>e.type!==Ke,"a bare operand, not an operation"),En("isCompound",e=>e.type===Ke,"an operation, not a bare operand"),En("isSymbol",e=>e.type===He,"a non-numeric operand such as x"),En("isOperation",(e,t)=>e.type===Ke&&e.op===t,"is this specific operation"),En("notOperation",(e,t)=>!(e.type===Ke&&e.op===t),"is anything except this operation"),En("isNumber",jn,"a numeric literal"),En("isInteger",e=>jn(e)&&Number.isInteger(e.value),"a whole number"),En("isPositive",e=>jn(e)&&e.value>0,"greater than zero"),En("isNegative",e=>jn(e)&&e.value<0,"less than zero"),En("isNonNegative",e=>jn(e)&&e.value>=0,"zero or greater"),En("isZero",e=>jn(e)&&0===e.value,"exactly 0"),En("isOne",e=>jn(e)&&1===e.value,"exactly 1"),En("isNonZero",e=>jn(e)&&0!==e.value,"a number that is provably not 0"),En("isNotZeroLiteral",e=>!(jn(e)&&0===e.value),"anything except a literal 0"),En("isPositiveInteger",e=>jn(e)&&Number.isInteger(e.value)&&e.value>0,"a whole number above 0"),En("isNegativeInteger",e=>jn(e)&&Number.isInteger(e.value)&&e.value<0,"a whole number below 0"),En("isEven",e=>jn(e)&&Number.isInteger(e.value)&&e.value%2==0,"a whole even number"),En("isOdd",e=>jn(e)&&Number.isInteger(e.value)&&1===Math.abs(e.value%2),"a whole odd number"),En("greaterThan",(e,t)=>jn(e)&&e.value>Number(t),"above a given value"),En("lessThan",(e,t)=>jn(e)&&e.value<Number(t),"below a given value"),En("isValue",(e,t)=>jn(e)&&e.value===Number(t),"equals a given number"),En("isNumeric",ct,"contains no symbols: a constant (it need not fold to a number: 1 sin)"),En("hasSymbol",e=>!ct(e),"mentions a symbol somewhere, so it is not just a number"),En("isVar",(e,t)=>e.type===He&&e.token===String(t),"is exactly this symbol"),En("contains",(e,t)=>ut(e).includes(String(t)),"mentions this operand somewhere"),En("isFree",(e,t)=>!ut(e).includes(String(t)),"never mentions this operand"),En("hasOperation",(e,t)=>Cn(e,String(t)),"uses this operation somewhere inside"),En("equals",(e,t)=>e.s===String(t),"is exactly this postfix expression");const zn=e=>e.type===Ke?null:e.token;function Zn(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 Nn(`bad requirement: ${JSON.stringify(e)}`)}In("freeOf",(e,t)=>{const n=zn(t);return null!==n&&!ut(e).includes(n)},"the first operand never mentions the second"),In("dependsOn",(e,t)=>{const n=zn(t);return null!==n&&ut(e).includes(n)},"the first operand does mention the second"),In("sameAs",(...e)=>e.every(t=>t.s===e[0].s),"these operands are structurally identical"),In("differs",(...e)=>new Set(e.map(e=>e.s)).size===e.length,"these operands are all different"),In("sameValue",(...e)=>e.every(e=>jn(e))&&e.every(t=>t.value===e[0].value),"these operands are the same number");const Bn="simplify";class Fn extends Error{constructor(e,t){super(t?`rule "${t}": ${e}`:e),this.name="RuleError",this.ruleId=t}}const Dn=/^[A-Za-z_][A-Za-z0-9_]*$/;function Pn(e,t){if(st(e))return{literal:e.value};const n=e.token;if(n.startsWith("=")){const e=n.slice(1);if(""===e)throw new Fn('"=" needs an operand after it',t);return{token:e}}if(!Dn.test(n))throw new Fn(`"${n}" is not a usable slot name; use letters, digits and _`,t);if(We(n))throw new Fn(`slot name "${n}" collides with an operator`,t);return{name:n}}function Rn(e){if(!it(e))return[e];const t=e.args.map(Rn),n=Re(e.op),s=[];for(const i of function(e){let t=[[]];for(const n of e){const e=[];for(const s of t)for(const t of n)e.push(s.concat([t]));if(t=e,t.length>64)return t.slice(0,64)}return t}(t))if(s.push(nt(e.op,i)),n.commutative&&2===i.length&&i[0].s!==i[1].s&&s.push(nt(e.op,[i[1],i[0]])),s.length>=64)break;return s}function Wn(e,t=[]){return"op"===e.kind?e.args.forEach(e=>Wn(e,t)):"const"===e.kind&&e.free&&t.push(e.node.token),t}function _n(e){if(!e||"object"!=typeof e)throw new Fn("rule must be a mapping");const t=e.id||e.name;if(!t)throw new Fn("rule needs an id");if(!e.pattern)throw new Fn("rule needs a pattern",t);if(void 0===e.output||null===e.output)throw new Fn("rule needs an output",t);let n;try{n=rt(String(e.pattern))}catch(e){if(e instanceof Qe)throw new Fn(`bad pattern: ${e.message}`,t);throw e}const s=Mn(n).map(e=>Pn(e,t)),i=new Set(s.filter(e=>e.name).map(e=>e.name)),r=function(e,t,n){const s=[],i=e.when||{};if("object"!=typeof i||Array.isArray(i))throw new Fn('"when" must map slot names to lists of requirements',n);for(const[e,r]of Object.entries(i)){if(!t.has(e))throw new Fn(`"when" mentions "${e}", which is not a slot in the pattern`,n);const i=Array.isArray(r)?r:[r];for(const t of i){const{name:i,args:r}=Zn(t),o=Tn(i);if(!o)throw new Fn(`unknown requirement "${i}"`,n);s.push({slot:e,name:i,args:r,fn:o.fn})}}return s}(e,i,t),o=function(e,t,n){const s=[],i=e.require||[];if(!Array.isArray(i))throw new Fn('"require" must be a list of relations',n);for(const e of i){const{name:i,args:r}=Zn(e),o=Ln(i);if(!o)throw new Fn(`unknown relation "${i}"`,n);if(r.length<2)throw new Fn(`relation "${i}" needs at least two operands`,n);for(const e of r)if("string"==typeof e&&!t.has(e)&&Dn.test(e))throw new Fn(`relation "${i}" mentions "${e}", which is not a slot in the pattern`,n);s.push({name:i,args:r,fn:o.fn})}return s}(e,i,t),a=function(e,t,n){let s;try{s=rt(e)}catch(t){throw new Fn(`bad output "${e}": ${t.message}`,n)}const i=e=>it(e)?{kind:"op",op:e.op,args:e.args.map(i)}:st(e)?{kind:"const",node:e}:t.has(e.token)?{kind:"slot",name:e.token}:e.token.startsWith("=")?{kind:"const",node:Ge(e.token.slice(1))}:{kind:"const",node:e,free:!0};return i(s)}(String(e.output),i,t),l=e.commutative?Rn(n):[n],u=[],c=new Set;for(const e of l){const n=Sn(e),s=Mn(e).map(e=>Pn(e,t)),i=n+"\0"+s.map(e=>e.name??(void 0!==e.literal?`#${e.literal}`:`=${e.token}`)).join(",");c.has(i)||(c.add(i),u.push({key:n,slots:s}))}const f={id:String(t),name:e.name?String(e.name):String(t),pattern:String(e.pattern),patternTree:n,output:String(e.output),outputTemplate:a,explain:e.explain?String(e.explain).trim():"",mode:e.mode?String(e.mode):Bn,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:at(n),bindings:u,freeSymbols:Wn(a),source:e};for(const e of u)e.rule=f;return f}function Vn(e){const t={};for(const n of e.when)(t[n.slot]||=[]).push(n.args.length?[n.name,...n.args]:n.name);const n={id:e.id};return e.name!==e.id&&(n.name=e.name),e.mode!==Bn&&(n.mode=e.mode),n.pattern=e.pattern,Object.keys(t).length&&(n.when=t),e.require.length&&(n.require=e.require.map(e=>[e.name,...e.args])),n.output=e.output,e.explain&&(n.explain=e.explain),e.fold&&(n.fold=!0),e.commutative&&(n.commutative=!0),e.priority&&(n.priority=e.priority),e.tags.length&&(n.tags=e.tags),e.enabled||(n.enabled=!1),n}class Un extends Error{constructor(e,t){super(null==t?e:`${e} (line ${t+1})`),this.name="YamlError",this.line=t}}class Hn{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 Kn=e=>"-"===e||e.startsWith("- ");function Jn(e){let t=null,n=0;for(let s=0;s<e.length;s++){const i=e[s];if(t)i===t?"'"===t&&"'"===e[s+1]?s++:t=null:'"'===t&&"\\"===i&&s++;else if('"'===i||"'"===i)t=i;else if("["===i||"{"===i)n++;else if("]"===i||"}"===i)n--;else if(":"===i&&0===n&&(s+1===e.length||" "===e[s+1])){const t=e.slice(0,s).trim();return""===t?null:{key:Qn(t),rest:e.slice(s+1).trim()}}}return null}function Qn(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 Yn(e){const t=new Hn(function(e){return String(e).split(/\r?\n/).map((e,t)=>{const n=e.search(/\S/);if(-1===n)return{raw:e,n:t,indent:0,text:"",blank:!0};const s=function(e){let t=null;for(let n=0;n<e.length;n++){const s=e[n];if(t)s===t?"'"===t&&"'"===e[n+1]?n++:t=null:'"'===t&&"\\"===s&&n++;else if('"'===s||"'"===s)t=s;else if("#"===s&&(0===n||/\s/.test(e[n-1])))return e.slice(0,n)}return e}(e.slice(n)).trimEnd();return{raw:e,n:t,indent:n,text:s,blank:""===s}})}(e));let n=t.peek();if(n&&"---"===n.text&&(t.next(),n=t.peek()),!n)return null;const s=Xn(t,n.indent),i=t.peek();if(i&&"..."!==i.text&&"---"!==i.text)throw new Un(`unexpected content "${i.text}"`,i.n);return s}const Gn=/^[|>][-+]?\d*$/;function Xn(e,t){const n=e.peek();return!n||n.indent<t?null:Kn(n.text)?es(e,n.indent):Jn(n.text)?function(e,t){const n={};for(;;){const s=e.peek();if(!s||s.indent!==t)break;const i=Jn(s.text);if(!i)break;e.next();const{key:r,rest:o}=i;if(""===o){const s=e.peek();s&&s.indent>t?n[r]=Xn(e,s.indent):s&&s.indent===t&&Kn(s.text)?n[r]=es(e,t):n[r]=null}else Gn.test(o)?n[r]=ts(e,o,t):n[r]=ns(o,s.n)}return n}(e,n.indent):(e.next(),Gn.test(n.text)?ts(e,n.text,n.indent-1):ns(n.text,n.n))}function es(e,t){const n=[];for(;;){const s=e.peek();if(!s||s.indent!==t||!Kn(s.text))break;if(e.next(),"-"===s.text){const s=e.peek();n.push(s&&s.indent>t?Xn(e,s.indent):null);continue}if(Gn.test(s.text.slice(2).trim())){n.push(ts(e,s.text.slice(2).trim(),t));continue}const i=s.text.slice(2),r=t+2+(i.length-i.trimStart().length);e.push({raw:s.raw,n:s.n,indent:r,text:i.trim(),blank:!1}),n.push(Xn(e,r))}return n}function ts(e,t,n){const s=t[0],i=(t.match(/[-+]/)||[""])[0],r=(t.match(/\d+/)||[null])[0];let o=r?n+Number(r):null;const a=[];for(;e.i<e.records.length;){const t=e.records[e.i];if(""===t.raw.trim()){a.push(""),e.i++;continue}const s=t.raw.search(/\S/);if(s<=n)break;if(null===o&&(o=s),s<o)break;a.push(t.raw.slice(o)),e.i++}for(;a.length&&""===a[a.length-1];)a.pop();let l;if("|"===s)l=a.join("\n");else{const e=[];for(const t of a)""===t?e.push("\n"):e.length&&"\n"!==e[e.length-1]?e[e.length-1]+=" "+t:e.push(t);l=e.join("").replace(/\n(?!$)/g,"\n")}return"-"===i?l:"+"===i?l+"\n":""===l?"":l+"\n"}function ns(e,t){const n=e.trim();return""===n||"~"===n||"null"===n||"Null"===n||"NULL"===n?null:"true"===n||"True"===n||"TRUE"===n||"false"!==n&&"False"!==n&&"FALSE"!==n&&("["===n[0]||"{"===n[0]?function(e,t){const n={text:e,i:0,line:t},s=is(n);if(ss(n),n.i<n.text.length)throw new Un(`unexpected "${n.text.slice(n.i)}" in flow value`,t);return s}(n,t):'"'===n[0]||"'"===n[0]?Qn(n):/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(n)?Number(n):n)}const ss=e=>{for(;e.i<e.text.length&&/\s/.test(e.text[e.i]);)e.i++};function is(e){ss(e);const t=e.text[e.i];return"["===t?function(e){e.i++;const t=[];for(;;){if(ss(e),e.i>=e.text.length)throw new Un("unterminated [",e.line);if("]"===e.text[e.i])return e.i++,t;if(t.push(is(e)),ss(e),","===e.text[e.i])e.i++;else if("]"!==e.text[e.i])throw new Un(`expected , or ] near "${e.text.slice(e.i)}"`,e.line)}}(e):"{"===t?function(e){e.i++;const t={};for(;;){if(ss(e),e.i>=e.text.length)throw new Un("unterminated {",e.line);if("}"===e.text[e.i])return e.i++,t;const n=String(is(e));if(ss(e),":"!==e.text[e.i])throw new Un(`expected : after "${n}"`,e.line);if(e.i++,t[n]=is(e),ss(e),","===e.text[e.i])e.i++;else if("}"!==e.text[e.i])throw new Un(`expected , or } near "${e.text.slice(e.i)}"`,e.line)}}(e):ns(function(e){const t=e.text[e.i];if('"'===t||"'"===t){const n=e.i;for(e.i++;e.i<e.text.length;)if("\\"===e.text[e.i]&&'"'===t)e.i+=2;else if(e.text[e.i]===t){if("'"!==t||"'"!==e.text[e.i+1])return e.i++,e.text.slice(n,e.i);e.i+=2}else e.i++;throw new Un("unterminated quoted string",e.line)}const n=e.i;for(;e.i<e.text.length;){const t=e.text[e.i];if(","===t||"]"===t||"}"===t)break;if(":"===t){const t=e.text[e.i+1];if(void 0===t||/[\s,\]}]/.test(t))break}e.i++}return e.text.slice(n,e.i).trim()}(e),e.line)}const rs=/^(true|false|null|yes|no|on|off|~)$/i;function os(e){if(null==e)return"null";if("boolean"==typeof e)return e?"true":"false";if("number"==typeof e){if(!Number.isFinite(e))throw new Un(`cannot serialize ${e}`);return String(e)}const t=String(e);return function(e){return!!(""===e||/^\s|\s$/.test(e)||/[\u0000-\u001f\u007f]/.test(e)||/^[-?:,[\]{}#&*!|>'"%@`]/.test(e)||/: |\s#/.test(e)||rs.test(e)||/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(e))}(t)?JSON.stringify(t):t}const as=e=>null==e||"object"!=typeof e;function ls(e){return Array.isArray(e)?`[${e.map(ls).join(", ")}]`:e&&"object"==typeof e?`{${Object.entries(e).map(([e,t])=>`${os(e)}: ${ls(t)}`).join(", ")}}`:os(e)}function us(e){return Array.isArray(e)?!!e.every(e=>as(e)||Array.isArray(e)&&e.every(as))&&ls(e).length<=72:!(!e||"object"!=typeof e)&&(Object.values(e).every(e=>as(e)||Array.isArray(e)&&e.every(as))&&ls(e).length<=72)}function cs(e){const t=[];return fs(e,0,t),t.length?t.join("\n")+"\n":""}function fs(e,t,n){const s=" ".repeat(t);if(Array.isArray(e)){if(0===e.length)return void n.push(s+"[]");for(const s of e)hs(s,t,n)}else{if(e&&"object"==typeof e){const i=Object.entries(e).filter(([,e])=>void 0!==e);if(0===i.length)return void n.push(s+"{}");for(const[e,s]of i)ps(e,s,t,n);return}!function(e,t,n){if("string"==typeof e&&e.includes("\n")){n.push(t+"|-");for(const s of e.replace(/\n+$/,"").split("\n"))n.push(t+" "+s);return}n.push(t+os(e))}(e,s,n)}}function hs(e,t,n){const s=" ".repeat(t);if(null!==e&&"object"==typeof e&&!us(e)){const i=[];if(fs(e,t+2,i),0===i.length)return void n.push(s+"-");n.push(s+"- "+i[0].slice(t+2));for(let e=1;e<i.length;e++)n.push(i[e]);return}if(null===e||"object"!=typeof e)if("string"==typeof e&&e.includes("\n")){n.push(s+"- |-");for(const s of e.replace(/\n+$/,"").split("\n"))n.push(" ".repeat(t+4)+s)}else n.push(s+"- "+os(e));else n.push(s+"- "+ls(e))}function ps(e,t,n,s){const i=" ".repeat(n),r=os(e);if("string"==typeof t&&t.includes("\n")){s.push(`${i}${r}: |-`);for(const e of t.replace(/\n+$/,"").split("\n"))s.push(" ".repeat(n+2)+e)}else{if(null!==t&&"object"==typeof t)return us(t)?void s.push(`${i}${r}: ${ls(t)}`):(s.push(`${i}${r}:`),void fs(t,Array.isArray(t)?n:n+2,s));s.push(`${i}${r}: ${os(t)}`)}}class ds{constructor(e=[]){this.index=new Map,this.rules=[],this.maxDepth=0,this.name="",this.views=new Map;for(const t of e)this.add(t)}add(e){const t=e&&e.bindings?e:_n(e);if(this.rules.some(e=>e.id===t.id))throw new Fn(`duplicate rule id "${t.id}"`);return this.rules.push(t),t.enabled&&this.link(t),t.depth>this.maxDepth&&(this.maxDepth=t.depth),this.views.clear(),t}view(e){if(!e)return this;let t=this.views.get(e);return t||(t=new ds(this.rules.filter(t=>t.mode===e)),t.name=this.name,this.views.set(e,t)),t}modes(){return[...new Set(this.rules.map(e=>e.mode))].sort((e,t)=>e===Bn?-1:t===Bn?1:e.localeCompare(t))}link(e){for(const t of e.bindings){let e=this.index.get(t.key);e||this.index.set(t.key,e=[]),e.push(t),e.sort((e,t)=>t.rule.priority-e.rule.priority||t.rule.depth-e.rule.depth)}}remove(e){const t=this.rules.findIndex(t=>t.id===e);return-1!==t&&(this.rules.splice(t,1),this.reindex(),!0)}setEnabled(e,t){const n=this.get(e);return!!n&&(n.enabled=!!t,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(t=>t.id===e)||null}candidates(e){return this.index.get(e)||null}get size(){return this.rules.length}static fromYaml(e,{strict:t=!0}={}){const n=Yn(e);return ds.fromSpecs(n,{strict:t})}static fromSpecs(e,{strict:t=!0}={}){let n=e,s="";if(e&&!Array.isArray(e)&&"object"==typeof e&&(n=e.rules,s=e.name?String(e.name):""),!Array.isArray(n))throw new Fn('expected a list of rules, or a mapping with a "rules" list');const i=new ds;i.name=s;const r=[];for(let e=0;e<n.length;e++)try{i.add(n[e])}catch(t){r.push(`#${e+1}: ${t.message}`)}if(r.length&&t)throw new Fn(`${r.length} rule(s) failed to compile:\n ${r.join("\n ")}`);return i.errors=r,i}toSpecs(){return this.rules.map(Vn)}toYaml(){const e=this.toSpecs();return this.name?cs({name:this.name,rules:e}):cs(e)}keyReport(){return[...this.index.entries()].map(([e,t])=>({key:e,rules:t.map(e=>e.rule.id)})).sort((e,t)=>e.key.localeCompare(t.key))}}function ms(e,t){const n=Object.create(null),s=e.slots;for(let e=0;e<s.length;e++){const i=s[e],r=t[e];if(void 0!==i.literal){if(!st(r)||r.value!==i.literal)return null;continue}if(void 0!==i.token){if(r.s!==i.token)return null;continue}const o=n[i.name];if(void 0!==o){if(o.s!==r.s)return null}else n[i.name]=r}return n}function gs(e,t){for(const n of e.when){const e=t[n.slot];if(void 0===e)return!1;if(!n.fn(e,...n.args))return!1}for(const n of e.require){const e=n.args.map(e=>void 0!==t[e]?t[e]:e);if(!n.fn(...e))return!1}return!0}function vs(e,t){return t.rule.priority-e.rule.priority||t.rule.depth-e.rule.depth}function bs(e,t){const n=[];if(0===t.maxDepth)return n;for(const{key:s,slots:i}of function(e,t){const n=$n(e,t),s=[];for(const e of n)e.key!==xn&&s.push(e);return s}(e,t.maxDepth)){const e=t.candidates(s);if(e)for(const t of e){const e=ms(t,i);e&&(gs(t.rule,e)&&n.push({rule:t.rule,binding:t,key:s,bound:e}))}}return n.sort(vs)}function ys(e,t,{order:n="post"}={}){const s=[];for(const{node:i,path:r}of ft(e,n))for(const e of bs(i,t))s.push({...e,node:i,path:r});return s}function ws(e,t){switch(e.kind){case"slot":{const n=t[e.name];if(!n)throw new Error(`output references unbound slot "${e.name}"`);return n}case"const":return e.node;case"op":return nt(e.op,e.args.map(e=>ws(e,t)));default:throw new Error(`bad output template: ${JSON.stringify(e)}`)}}function xs(e){if(!it(e))return e;const t=e.args.map(xs),n=t.some((t,n)=>t!==e.args[n])?nt(e.op,t):e,s=Re(n.op);if(!s||!s.fold||!n.args.every(st))return n;if(qs.has(n.op)){const e=function(e,t){const[n,s]=t.map(Ss);if(!n||t.length>1&&!s)return;let i;switch(e){case"neg":i={n:-n.n,scale:n.scale};break;case"+":{const[e,t,r]=Ms(n,s);i={n:e+t,scale:r};break}case"-":{const[e,t,r]=Ms(n,s);i={n:e-t,scale:r};break}case"*":i={n:n.n*s.n,scale:n.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((n.n<0n?-n.n:n.n).toString().length*Number(e)>$s)return null;const t={n:n.n**e,scale:n.scale*Number(e)};if(i=s.n<0n?function({n:e,scale:t}){if(0n===e)return null;let n=e<0n?-e:e,s=0,i=0;for(;n%2n==0n;)n/=2n,s++;for(;n%5n==0n;)n/=5n,i++;if(1n!==n)return null;const r=Math.max(s,i),o=10n**BigInt(t)*2n**BigInt(r-s)*5n**BigInt(r-i);return{n:e<0n?-o:o,scale:r}}(t):t,!i)return null;break}default:return}const r=function({n:e,scale:t}){const n=e<0n;let s=(n?-e:e).toString();t>0&&(s=s.padStart(t+1,"0"),s=`${s.slice(0,-t)}.${s.slice(-t)}`.replace(/\.?0+$/,""));return"0"===s?"0":(n?"-":"")+s}(i);return r.length>$s?null:r}(n.op,n.args.map(e=>e.token));if(void 0!==e)return null===e?n:Xe(e)}const i=s.fold(...n.args.map(e=>e.value));return null!=i&&Number.isFinite(i)?Ye(i):n}function ks(e,t){const n=function(e){const t=ws(e.rule.outputTemplate,e.bound);return e.rule.fold?xs(t):t}(t);return{expr:pt(e,t.path,n),before:t.node,after:n,rule:t.rule,path:t.path,explanation:(s=t.rule,i=t.bound,r=n,s.explain?s.explain.replace(/\{(\w+)\}/g,(e,t)=>{if("result"===t)return r?r.s:e;const n=i[t];return n?n.s:e}):"")};var s,i,r}const qs=new Set(["+","-","*","neg","^"]),$s=2e3;function Ss(e){const t=/^(-?)(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/i.exec(e);if(!t)return;const n=t[3]??"";let s=BigInt(t[2]+n),i=n.length-Number(t[4]??0);return i<0&&(s*=10n**BigInt(-i),i=0),{n:t[1]?-s:s,scale:i}}const Ms=(e,t)=>{const n=Math.max(e.scale,t.scale);return[e.n*10n**BigInt(n-e.scale),t.n*10n**BigInt(n-t.scale),n]};const Os=4e5,As=()=>new dt("a number too large to approximate"),Ns=e=>e<0n?-e:e;class Es{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,t){return e*t/this.S}div(e,t){if(0n===t)throw new dt("division by zero");return e*this.S/t}sqrt(e){if(e<0n)throw new dt("the square root of a negative number is not real");return xt(e*this.S,2)}series(e,t){let n=0n,s=e;for(let e=1;0n!==s;e++)if(n+=s,s=t(s,e),e>1e5)throw new dt("a series did not converge");return n}atanhInv(e){const t=BigInt(e),n=t*t;let s=this.S/t,i=0n;for(let e=1n;0n!==s;e+=2n)i+=s/e,s/=n;return i}atanInv(e){const t=BigInt(e),n=t*t;let s=this.S/t,i=0n;for(let e=1n,t=1n;0n!==s;e+=2n,t=-t)i+=t*s/e,s/=n;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,t){return this.cache.has(e)||this.cache.set(e,t()),this.cache.get(e)}exp(e){const t=(e+(e>=0n?this.ln2/2n:-this.ln2/2n))/this.ln2;if(t>BigInt(Os))throw As();if(t<-BigInt(Os))return 0n;const n=e-t*this.ln2,s=this.series(this.S,(e,t)=>e*n/this.S/BigInt(t));return t>=0n?s<<t:s>>-t}ln(e){if(e<=0n)throw new dt("the log of a number that is not positive is not real");let t=0n,n=e;for(;n>=this.S;)n>>=1n,t++;for(;n<this.S/2n;)n<<=1n,t--;const s=this.div(n-this.S,n+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+t*this.ln2}sin(e){const t=2n*this.pi;let n=e%t;n>this.pi&&(n-=t),n<-this.pi&&(n+=t);const s=this.mul(n,n);return this.series(n,(e,t)=>-e*s/this.S/BigInt(2*t*(2*t+1)))}cos(e){return this.sin(e+this.pi/2n)}atan(e){if(Ns(e)>this.S){const t=this.pi/2n;return(e>0n?t:-t)-this.atan(this.div(this.S,e))}let t=e;for(let e=0;e<2;e++)t=this.div(t,this.S+this.sqrt(this.S+this.mul(t,t)));const n=this.mul(t,t);let s=t,i=0n;for(let e=1n,t=1n;0n!==s;e+=2n,t=-t)i+=t*s/e,s=this.mul(s,n);return 4n*i}asin(e){if(Ns(e)>this.S)throw new dt("arcsin of a number beyond ±1 is not real");return Ns(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 Is(e,t,n){if(n>0n)return e.atan(e.div(t,n));if(n<0n)return e.atan(e.div(t,n))+(t>=0n?e.pi:-e.pi);if(0n===t)throw new dt("the argument of 0 is undefined");return t>0n?e.pi/2n:-e.pi/2n}const Ts={add:(e,t)=>[e[0]+t[0],e[1]+t[1]],sub:(e,t)=>[e[0]-t[0],e[1]-t[1]],mul:(e,t,n)=>[e.mul(t[0],n[0])-e.mul(t[1],n[1]),e.mul(t[0],n[1])+e.mul(t[1],n[0])],div(e,t,n){const s=e.mul(n[0],n[0])+e.mul(n[1],n[1]);if(0n===s)throw new dt("division by zero");return[e.div(e.mul(t[0],n[0])+e.mul(t[1],n[1]),s),e.div(e.mul(t[1],n[0])-e.mul(t[0],n[1]),s)]},abs:(e,t)=>e.sqrt(e.mul(t[0],t[0])+e.mul(t[1],t[1])),exp(e,t){const n=e.exp(t[0]);return[e.mul(n,e.cos(t[1])),e.mul(n,e.sin(t[1]))]},ln(e,t){const n=Ts.abs(e,t);if(0n===n)throw new dt("the log of 0 is undefined");return[e.ln(n),Is(e,t[1],t[0])]},pow(e,t,n,s){if(0n===t[0]&&0n===t[1])return[0n,0n];if(s&&s.isInteger){let n=s.n<0n?-s.n:s.n,i=[e.S,0n],r=t;for(;n>0n;)1n&n&&(i=Ts.mul(e,i,r)),r=Ts.mul(e,r,r),n>>=1n;return s.n<0n?Ts.div(e,[e.S,0n],i):i}return Ts.exp(e,Ts.mul(e,n,Ts.ln(e,t)))},sinh:(e,t)=>(e.exp(t)-e.exp(-t))/2n,cosh:(e,t)=>(e.exp(t)+e.exp(-t))/2n},Ls={sin:(e,[t,n])=>[e.mul(e.sin(t),Ts.cosh(e,n)),e.mul(e.cos(t),Ts.sinh(e,n))],cos:(e,[t,n])=>[e.mul(e.cos(t),Ts.cosh(e,n)),-e.mul(e.sin(t),Ts.sinh(e,n))],tan:(e,t)=>Ts.div(e,Ls.sin(e,t),Ls.cos(e,t)),ln:(e,t)=>Ts.ln(e,t),sqrt:(e,t)=>Ts.exp(e,Ts.mul(e,[e.S/2n,0n],Ts.ln(e,t))),sinh:(e,[t,n])=>[e.mul(Ts.sinh(e,t),e.cos(n)),e.mul(Ts.cosh(e,t),e.sin(n))],cosh:(e,[t,n])=>[e.mul(Ts.cosh(e,t),e.cos(n)),e.mul(Ts.sinh(e,t),e.sin(n))]},js=e=>({q:e}),Cs=([e,t])=>0n===t?{f:e}:{z:[e,t]};function zs(e,t,n){const s=e=>((e,t)=>t.z??[Zs(e,t),0n])(n,t[e]);switch(e.op){case"+":return Cs(Ts.add(s(0),s(1)));case"-":return Cs(Ts.sub(s(0),s(1)));case"neg":return Cs([-s(0)[0],-s(0)[1]]);case"*":return Cs(Ts.mul(n,s(0),s(1)));case"/":return Cs(Ts.div(n,s(0),s(1)));case"^":return Cs(Ts.pow(n,s(0),s(1),t[1].q));case"sqrt":return Cs(Ls.sqrt(n,s(0)));case"root":return Cs(Ts.pow(n,s(1),Ts.div(n,[n.S,0n],s(0)),t[0].q?.inv()));case"abs":return{f:Ts.abs(n,s(0))};case"arg":return{f:Is(n,s(0)[1],s(0)[0])};case"re":return{f:s(0)[0]};case"im":return{f:s(0)[1]};case"conj":return Cs([s(0)[0],-s(0)[1]]);case"log":return Cs(Ts.div(n,Ts.ln(n,s(1)),Ts.ln(n,s(0))));default:{const i=Ls[e.op];if(!i||1!==t.length)throw new dt(`no complex value for ${e.op}`);return Cs(i(n,s(0)))}}}function Zs(e,t){return t.q?e.fromQ(t.q):t.f}const Bs={sin:(e,t)=>e.sin(t),cos:(e,t)=>e.cos(t),tan:(e,t)=>e.div(e.sin(t),e.cos(t)),sec:(e,t)=>e.div(e.S,e.cos(t)),csc:(e,t)=>e.div(e.S,e.sin(t)),cot:(e,t)=>e.div(e.cos(t),e.sin(t)),arcsin:(e,t)=>e.asin(t),arccos:(e,t)=>e.pi/2n-e.asin(t),arctan:(e,t)=>e.atan(t),arcsec:(e,t)=>{if(Ns(t)<e.S)throw new dt("arcsec of a number between -1 and 1 is not real");return e.pi/2n-e.asin(e.div(e.S,t))},arccsc:(e,t)=>{if(Ns(t)<e.S)throw new dt("arccsc of a number between -1 and 1 is not real");return e.asin(e.div(e.S,t))},arccot:(e,t)=>e.pi/2n-e.atan(t),sinh:(e,t)=>(e.exp(t)-e.exp(-t))/2n,cosh:(e,t)=>(e.exp(t)+e.exp(-t))/2n,tanh:(e,t)=>{const n=e.exp(t),s=e.exp(-t);return e.div(n-s,n+s)},arcsinh:(e,t)=>e.ln(t+e.sqrt(e.mul(t,t)+e.S)),arccosh:(e,t)=>{if(t<e.S)throw new dt("arccosh of a number below 1 is not real");return e.ln(t+e.sqrt(e.mul(t,t)-e.S))},arctanh:(e,t)=>{if(Ns(t)>=e.S)throw new dt("arctanh of a number beyond ±1 is not real");return e.ln(e.div(e.S+t,e.S-t))/2n},ln:(e,t)=>e.ln(t),loglog:(e,t)=>e.ln(e.ln(t)),logloglog:(e,t)=>e.ln(e.ln(e.ln(t))),expm1:(e,t)=>e.exp(t)-e.S};function Fs(e,t,n){if("num"===e.type)return js(wt(e.token));if("sym"===e.type){if("pi"===e.token||"π"===e.token)return{f:t.pi};if("e"===e.token)return{f:t.e};if("i"===e.token&&St.complex)return{z:[0n,t.S]};if(n&&e.token in n){const t=n[e.token],s="number"==typeof t||"string"==typeof t||"bigint"==typeof t?wt(String(t)):null;if(!s)throw new dt(`the value of ${e.token} is not a number`);return js(s)}throw new dt(`${e.token} has no value`)}St.complex&&e.op.startsWith("\\:")&&nn[e.op.slice(2)]&&(e=nt(nn[e.op.slice(2)],e.args));const s=e.args.map(e=>Fs(e,t,n));if(s.some(e=>e.z)||["re","im","conj","arg"].includes(e.op)||function(e,t){if(!St.complex)return!1;const n=e=>e.q?e.q.sign<0:void 0!==e.f&&e.f<0n;return"sqrt"===e.op||"ln"===e.op||"log"===e.op?n(t["log"===e.op?1:0])||"log"===e.op&&n(t[0]):"^"===e.op?n(t[0])&&!(t[1].q&&t[1].q.d%2n==1n):"root"===e.op&&n(t[1])&&!(t[0].q&&t[0].q.isInteger&&t[0].q.n%2n==1n)}(e,s))return zs(e,s,t);const i=s.every(e=>e.q),r=e=>Zs(t,s[e]);switch(e.op){case"+":return i?js(s[0].q.add(s[1].q)):{f:r(0)+r(1)};case"-":return i?js(s[0].q.sub(s[1].q)):{f:r(0)-r(1)};case"neg":return s[0].q?js(s[0].q.neg()):{f:-s[0].f};case"*":return i?js(s[0].q.mul(s[1].q)):{f:t.mul(r(0),r(1))};case"/":return i?js(s[0].q.div(s[1].q)):{f:t.div(r(0),r(1))};case"^":return Ps(t,s[0],s[1]);case"sqrt":return Ps(t,s[0],js(yt.HALF));case"root":return Ps(t,s[1],s[0].q?js(s[0].q.inv()):{f:t.div(t.S,s[0].f)});case"abs":return s[0].q?js(s[0].q.abs()):{f:Ns(s[0].f)};case"floor":return js(s[0].q?s[0].q.floor():new yt(Ds(s[0].f,t.S)));case"ceil":return js(s[0].q?s[0].q.ceil():new yt(-Ds(-s[0].f,t.S)));case"log":return{f:t.div(t.ln(r(1)),t.ln(r(0)))};case"atan2":return{f:Is(t,r(0),r(1))};case"max":case"min":if(!s.length)throw new dt(`${e.op} of nothing`);return i?js(s.map(e=>e.q).reduce((t,n)=>("max"===e.op?n.sub(t).sign>0:n.sub(t).sign<0)?n:t)):{f:s.map((e,t)=>r(t)).reduce((t,n)=>"max"===e.op?n>t?n:t:n<t?n:t)};case"sum":return i?js(s.reduce((e,t)=>e.add(t.q),yt.ZERO)):{f:s.reduce((e,t,n)=>e+r(n),0n)};case"prod":return i?js(s.reduce((e,t)=>e.mul(t.q),yt.ONE)):{f:s.reduce((e,n,s)=>t.mul(e,r(s)),t.S)};case"mean":if(!s.length)throw new dt("mean of nothing");return i?js(s.reduce((e,t)=>e.add(t.q),yt.ZERO).div(new yt(BigInt(s.length)))):{f:s.reduce((e,t,n)=>e+r(n),0n)/BigInt(s.length)};case"mod":{if(i){if(s[1].q.isZero)throw new dt("mod 0 is undefined");return js(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 dt("mod 0 is undefined");return{f:r(0)-t.mul(e,Ds(t.div(r(0),e),t.S)*t.S)}}case"round":{if(!s[1].q?.isInteger)throw new dt("round needs a whole number of places");const e=10n**Ns(s[1].q.n),n=s[0].q??new yt(r(0),t.S),i=s[1].q.sign>=0,o=(i?n.mul(new yt(e)):n.div(new yt(e))).add(yt.HALF).floor();return js(i?o.div(new yt(e)):o.mul(new yt(e)))}case"!":{if(!s[0].q?.isInteger||s[0].q.sign<0)throw new dt("factorial is only worked out for whole numbers");let e=1n;for(let t=2n;t<=s[0].q.n;t++)if(e*=t,0n==(255n&t)&&vt(e)>Os)throw As();return js(new yt(e))}default:{const n=Bs[e.op];if(!n||1!==s.length)throw new dt(`no numeric value for ${e.op}`);return{f:n(t,r(0))}}}}const Ds=(e,t)=>{const n=e/t;return e<0n&&n*t!==e?n-1n:n};function Ps(e,t,n){if(n.q&&n.q.isInteger){if(t.q)return js(t.q.pow(n.q.n));let s=n.q.n;const i=s<0n;i&&(s=-s);let r=e.S,o=t.f;for(;s>0n;){if(1n&s&&(r=e.mul(r,o)),o=e.mul(o,o),vt(r)>Os+4*e.P||vt(o)>8e5){if(i)return{f:0n};throw As()}s>>=1n}return{f:i?e.div(e.S,r):r}}const s=Zs(e,t);if(0n===s){if(n.q?n.q.sign>0:n.f>0n)return js(yt.ZERO);throw new dt("0 to a power that is not positive is undefined")}if(s<0n){if(n.q&&n.q.d%2n==1n){const t=Ps(e,{f:-s},n).f;return{f:n.q.n%2n==0n?t:-t}}throw new dt("a negative number to a fractional power is not real")}if(n.q&&1n===Ns(n.q.n)&&n.q.d<=64n){const t=xt(s*e.S**(n.q.d-1n),Number(n.q.d));return{f:n.q.n<0n?e.div(e.S,t):t}}return{f:e.exp(e.mul(Zs(e,n),e.ln(s)))}}function Rs(e,t,n){const s=e<0n?"-":"",i=Ns(e);if(0n===i)return{sign:"",digits:"0",point:1};const r=i.toString(),o=r.length-t.P;let a=r.slice(0,n);r.length>n&&r[n]>="5"&&(a=(BigInt(a)+1n).toString());let l=o;return a.length>n&&(a=a.slice(0,n),l++),{sign:s,digits:a.replace(/0+$/,"")||"0",point:l}}function Ws({sign:e,digits:t,point:n}){if("0"===t)return"0";if(n>21||n<-6){return`${e}${t.length>1?`${t[0]}.${t.slice(1)}`:t}e${n-1}`}return n<=0?`${e}0.${"0".repeat(-n)}${t}`:n>=t.length?`${e}${t}${"0".repeat(n-t.length)}`:`${e}${t.slice(0,n)}.${t.slice(n)}`}function _s(e){let t=0n,n=0n,s=e.d;for(;s%2n==0n;)s/=2n,t++;for(;s%5n==0n;)s/=5n,n++;const i=t>n?t:n;let r=Ns(e.n)*10n**i/e.d;if(0n===r)return 1;for(;r%10n==0n;)r/=10n;return r.toString().length}function Vs(e){let t=e.d;for(;t%2n==0n;)t/=2n;for(;t%5n==0n;)t/=5n;return 1n===t}function Us(e){const t=/^(-?[\d.]+)e(-?\d+)$/.exec(e);return t?nt("*",[Xe(t[1]),nt("^",[Xe("10"),Xe(t[2])])]):Xe(e)}function Hs(e,{digits:t=15,scope:n}={}){if(!Number.isInteger(t)||t<1||t>1e5)throw new dt("digits must be a whole number from 1 to 100000");let s=t+25,i=null;for(let r=0;r<4;r++){const o=new Es(s),a=Fs(e,o,n);if(a.z){const e=Js(a.z,o,t);if(e.retry&&r<3){s+=e.retry;continue}return void 0===e.real?e:Ks(e.real,o,t,null)}if(a.q&&a.q.isInteger&&Ns(a.q.n).toString().length<=t)return{text:a.q.n.toString(),node:Xe(a.q.n.toString()),number:Number(a.q.n),re:Number(a.q.n),im:0,exact:!0};const l=Zs(o,a);if(0n===l&&(!a.q||!a.q.isZero)&&r<3){i=null,s*=4;continue}const u=Rs(l,o,t);if(i&&u.point<-10&&i.point-u.point>=(s-i.P)/2)return{text:"0",node:Xe("0"),number:0,re:0,im:0,exact:!1};if(!(u.point<-10&&r<3)||i&&i.point===u.point)return Ks(l,o,t,a.q);i={point:u.point,P:s},s+=10-u.point}throw new dt("could not approximate")}function Ks(e,t,n,s){const i=Ws(Rs(e,t,n));return{text:i,node:Us(i),number:Number(i),re:Number(i),im:0,exact:Boolean(s)&&Vs(s)&&_s(s)<=n}}function Js([e,t],n,s){const i=10n**BigInt(Math.max(0,n.P-s-12)),r=e=>Ns(e)>i;if(!r(t))return{real:e};const o=Rs(t,n,s);if(o.point<-10&&r(t))return{retry:10-o.point};const a=Ws(o),l="1"===a?"i":"-1"===a?"-i":`${a}i`,u="1"===a?Ge("i"):nt("*",[Us(a.replace(/^-/,"")),Ge("i")]);if(!r(e))return{text:l,node:a.startsWith("-")?nt("neg",[u]):u,number:NaN,re:0,im:Number(a),exact:!1};const c=Ws(Rs(e,n,s)),f=a.startsWith("-"),h="1"===a.replace(/^-/,"")?Ge("i"):nt("*",[Us(a.replace(/^-/,"")),Ge("i")]);return{text:`${c} ${f?"-":"+"} ${l.replace(/^-/,"")}`,node:nt(f?"-":"+",[Us(c),h]),number:NaN,re:Number(c),im:Number(a),exact:!1}}function Qs(e,t={}){const n=e=>(e=>0===bn(e).size)(e)?"num"===e.type&&/^-?\d+$/.test(e.token)?e:Hs(e,t).node:it(e)?nt(e.op,e.args.map(n)):e;return n(e)}const Ys={variable:null},Gs=(e,t)=>null!==t&&bn(e).has(t);function Xs(e){if("num"===e.type)return wt(e.token);if(it(e)&&"/"===e.op&&e.args.every(e=>"num"===e.type)){const t=wt(e.args[0].token),n=wt(e.args[1].token);return t&&n&&!n.isZero?t.div(n):null}return null}const ei=e=>0===bn(e).size;function ti(e,t,n){const s=function(e){const t=cn(e);return"num"===t.k?t.q.isZero?t.q:null:"atom"===t.k&&"sym"===t.node.type&&"pi"===t.node.token?wt("1"):"mul"===t.k&&1===t.fs.length&&"atom"===t.fs[0].b.k&&"pi"===t.fs[0].b.node.token&&"num"===t.fs[0].e.k&&t.fs[0].e.q.isOne?t.c:null}(e);if(!s)return!1;const[i,r="1"]=String(t).split("/");return n(s.compare(wt(i).div(wt(r))))}function ni(e){if(!ei(e))return NaN;try{const{number:t}=Hs(e,{digits:30});return Math.sign(t)}catch{return NaN}}function si(){Tn("hasVariable")||(En("hasVariable",e=>Gs(e,Ys.variable),"mentions the variable being solved for"),En("freeOfVariable",e=>null!==Ys.variable&&!Gs(e,Ys.variable),"does not mention the variable being solved for"),En("isRational",e=>null!==Xs(e),"an exact number: 3, -2, 1/2"),En("isWhole",e=>Xs(e)?.isInteger??!1,"a whole number (any size)"),En("isEvenWhole",e=>{const t=Xs(e);return Boolean(t?.isInteger&&t.n%2n==0n)},"an even whole number"),En("isOddWhole",e=>{const t=Xs(e);return Boolean(t?.isInteger&&t.n%2n!=0n)},"an odd whole number"),En("isPositiveRational",e=>(Xs(e)?.sign??0)>0,"an exact number above 0"),En("isNegativeRational",e=>(Xs(e)?.sign??0)<0,"an exact number below 0"),En("isConstant",ei,"has no unknowns (numbers, π and e only)"),En("notOne",e=>{const t=Xs(e);return!t||!t.isOne},"anything except the number 1"),En("notMinusOne",e=>{const t=Xs(e);return!t||!t.equals(wt("-1"))},"anything except the number -1"),En("hasMinusSign",e=>function(e){const t=cn(e);return"num"===t.k?t.q.sign<0:"mul"===t.k&&t.c.sign<0}(e),"written with a leading minus: -x, -2x, -π/6"),En("piMultipleAtLeast",(e,t)=>ti(e,t,e=>e>=0),"a multiple of π, at least k·π"),En("piMultipleAbove",(e,t)=>ti(e,t,e=>e>0),"a multiple of π, above k·π"),En("piMultipleBelow",(e,t)=>ti(e,t,e=>e<0),"a multiple of π, below k·π"),En("piMultipleAtMost",(e,t)=>ti(e,t,e=>e<=0),"a multiple of π, at most k·π"),En("isPositiveConstant",e=>ni(e)>0,"no unknowns, and above 0 (e, π, √2, 3)"),En("isNegativeConstant",e=>ni(e)<0,"no unknowns, and below 0"),En("hasImaginaryPart",e=>{if(!St.complex)return!1;const t=Xt(cn(e));return Boolean(t)&&!("num"===t.im.k&&t.im.q.isZero)},"complex mode: has a nonzero imaginary part (unknowns count as real)"),En("isSymbolNode",e=>"sym"===e.type&&!$t.has(e.token),"a single unknown such as x"))}function ii(e){const t=new Map;for(const n of e){const e=n.id??n.name;if(!e)throw new Error(`a rule needs an id (pattern ${n.pattern})`);t.set(String(e),{...t.get(String(e))??{},...n})}const n=[...t.values()].map(e=>{const t={...e};try{void 0!==t.pattern&&(t.pattern=function(e){const t=rt(e),n=e=>"num"===e.type||("sym"===e.type?e.token.startsWith("="):e.args.every(n)),s=e=>"sym"===e.type?Ge(e.token.slice(1)):"num"===e.type?e:nt(e.op,e.args.map(s)),i=e=>"sym"===e.type?Ge(`=${e.token}`):"num"===e.type?e:nt(e.op,e.args.map(i)),r=e=>"op"!==e.type?e:n(e)?i(fn(s(e))):nt(e.op,e.args.map(r));return r(t).s}(String(t.pattern)))}catch(e){throw new Error(`rule "${t.id}": bad pattern "${t.pattern}": ${e.message}`)}return"hidden"===t.step&&(t.tags=[...t.tags??[],"hidden"]),t});return ds.fromSpecs(n,{strict:!0})}function ri(e,t,n,s){return e.explain?e.explain.replace(/\{(\w+)\}/g,(e,i)=>"result"===i?n?s(n):e:t[i]?s(t[i]):e).trim():""}const oi=e=>it(e)&&("+"===e.op||"-"===e.op),ai=e=>it(e)&&("*"===e.op||"/"===e.op);function*li(e,t,{order:n="pre"}={}){for(const s of ys(e,t,{order:n})){const t=ws(s.rule.outputTemplate,s.bound);yield{rule:s.rule,bound:s.bound,path:s.path,before:s.node,after:t,next:()=>fn(pt(e,s.path,t))}}for(const{node:s,path:i}of ft(e,n)){const n=oi(s);if(!n&&!ai(s))continue;const r=n?yn(cn(s)):wn(cn(s));if(r.length<3)continue;const o=n?_t:Ut;for(let n=0;n<r.length;n++)for(let s=n+1;s<r.length;s++){const a=mn(o([r[n],r[s]]));for(const l of bs(a,t)){const t=ws(l.rule.outputTemplate,l.bound),u=r.filter((e,t)=>t!==n&&t!==s);yield{rule:l.rule,bound:l.bound,path:i,before:a,after:t,next:()=>fn(pt(e,i,mn(o([cn(t),...u]))))}}}}}function ui(e,t,{format:n,order:s="pre",maxSteps:i=200,variable:r=null}={}){const o=Ys.variable;Ys.variable=r;try{let r=fn(e);const o=new Set([r.s]),a=[];for(let e=0;e<i;e++){let e=null;for(const n of li(r,t,{order:s})){const t=n.next();if(t.s!==r.s&&!o.has(t.s)){e={c:n,next:t};break}}if(!e)break;const{c:i,next:l}=e;a.push({id:i.rule.id,name:i.rule.name,tags:i.rule.tags,from:r.s,to:l.s,path:i.path,before:i.before.s,after:i.after.s,explanation:ri(i.rule,i.bound,fn(i.after),n)}),r=l,o.add(r.s)}return{node:r,steps:a}}finally{Ys.variable=o}}const ci=(e,t)=>e.length>=t.length&&t.every((t,n)=>e[n]===t),fi=(e,t)=>{for(const n of e)if(t(n))return n;return null};function hi(e,t,{diff:n}){let s=null;for(;;){const i=fi(ys(e,n,{order:"pre"}),e=>"d-variable"===e.rule.id&&e.path.length>t.length&&ci(e.path,t));if(!i)break;s=ht(e,i.path).args[1],e=ks(e,i).expr}const i=t.length?t.slice(0,-1):t,r=gi(ht(e,i));return r.s!==ht(e,i).s&&(e=i.length?pt(e,i,r):r),{expr:e,variable:s}}function pi(e){if(!it(e))return e;const t=e.args.map(pi),n=e.op.startsWith("\\:")?e.op.slice(2):null;return n&&We(n)&&Re(n).arity===t.length?nt(n,t):t.every((t,n)=>t===e.args[n])?e:nt(e.op,t)}const di=e=>"op"!==e.type&&"1"===e.s,mi=e=>"op"!==e.type&&"0"===e.s;function gi(e){if(!it(e))return e;const t=e.args.map(gi),[n,s]=t;if("*"===e.op&&2===t.length){if(di(s))return n;if(di(n))return s}if("^"===e.op&&2===t.length&&di(s))return n;if("+"===e.op&&2===t.length){if(mi(s))return n;if(mi(n))return s}return"-"===e.op&&2===t.length&&mi(s)?n:t.every((t,n)=>t===e.args[n])?e:nt(e.op,t)}function vi(e,t,{fold:n=null,format:s,maxSteps:i=200,order:r="pre"}={}){let o=e;const a=new Set([o.s]),l=[];for(let e=0;e<i;e++){let e=null;for(const s of ys(o,t,{order:r})){const t=ks(o,s);let i=t.expr,r=null;if(n&&({expr:i,variable:r}=hi(i,s.path,n)),i.s!==o.s&&!a.has(i.s)){e={m:s,a:t,expr:i,variable:r};break}}if(!e)break;const{m:i,a:u,expr:c,variable:f}=e;let h=i.path;for(;;)try{ht(c,h);break}catch{h=h.slice(0,-1)}const p=ht(c,h);let d=ri(i.rule,i.bound,fn(p),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.`),l.push({id:i.rule.id,name:i.rule.name,tags:i.rule.tags,from:o.s,to:c.s,path:h,before:u.before.s,after:p.s,explanation:d}),o=c,a.add(o.s)}return{node:o,steps:l}}const bi=new Set(["int","der","lim"]),yi=e=>it(e)&&("+"===e.op||"-"===e.op),wi=e=>it(e)&&"*"===e.op;function xi(e,t=1,n=[]){return it(e)&&"+"===e.op?(xi(e.args[0],t,n),xi(e.args[1],t,n),n):it(e)&&"-"===e.op&&2===e.args.length?(xi(e.args[0],t,n),xi(e.args[1],-t,n),n):it(e)&&"neg"===e.op?(xi(e.args[0],-t,n),n):(n.push({sign:t,node:e}),n)}const ki=(e,t=[])=>wi(e)?(ki(e.args[0],t),ki(e.args[1],t),t):(t.push(e),t),qi=e=>e.reduce((e,t)=>null===e?t.sign<0?nt("neg",[t.node]):t.node:nt(t.sign<0?"-":"+",[e,t.node]),null),$i=e=>{try{return zt(cn(e))}catch{return e.s}},Si=e=>$i(e.sign<0?nt("neg",[e.node]):e.node);function Mi(e,t,n,s=n){const i=e.map((e,t)=>({x:e,i:t,k:n(e)})),r=[];let o=null;for(const e of t){const t=i.findIndex(t=>t.k===s(e));t>=0?(r.push({x:i[t].x,from:e}),i.splice(t,1)):null===o&&(o=r.length,r.push(null))}const a=i.map(e=>({x:e.x,from:null}));return null===o?[...r,...a]:[...r.slice(0,o),...a,...r.slice(o+1)]}function Oi(e,t,{tidy:n=!1}={}){if(!t||e.s===t.s)return t&&e.s===t.s?t:e;if(yi(e)&&yi(t)){const s=Mi(xi(e),xi(t),Si),i=xi(t).filter(e=>!s.some(t=>t.from===e));return qi(s.map(({x:e,from:t})=>({sign:e.sign,node:Oi(e.node,(t??(1===i.length?i[0]:null))?.node,{tidy:n})})))}if(yi(e)&&it(t)&&bi.has(t.op)&&yi(t.args[0])){const n=e=>it(e.node)&&e.node.op===t.op?Si({sign:e.sign,node:e.node.args[0]}):Si(e),s=Mi(xi(e),xi(t.args[0]),n,Si);return qi(s.map(({x:e})=>e))}if(wi(e)&&wi(t)){if(n)return e;const s=Mi(ki(e),ki(t),$i);return s.map(({x:e,from:t})=>Oi(e,t)).reduce((e,t)=>null===e?t:nt("*",[e,t]),null)}if(it(e)&&it(t)&&e.op===t.op&&e.args.length===t.args.length){const s=e.args.map((e,s)=>Oi(e,t.args[s],{tidy:n}));return s.every((t,n)=>t===e.args[n])?e:nt(e.op,s)}return e}const Ai=new Set(["normal","normal.collect","normal.expand-collect","simplify.cancel","simplify.expand","cancel","expand","together"]),Ni=e=>Ai.has(e.id)||(e.tags??[]).includes("tidy");function Ei(e,t){if(!e.length)return e;let n=t??rt(e[0].from);return e.map(e=>{let t,s=n??rt(e.from);try{$i(rt(e.from))!==$i(n)&&(s=rt(e.from)),t=e.to===e.from?s:Oi(rt(e.to),s,{tidy:Ni(e)})}catch(t){if(t instanceof ReferenceError||t instanceof TypeError)throw t;return n=null,e}if(t.s===s.s&&e.to!==e.from&&Ni(e))return null;n=t;let i=e.path;return e.before&&e.before!==e.from&&(i=function(e,t){const n=$i(rt(t)),s=(e,i)=>{if(e.s===t||$i(e)===n)return i;if(!it(e))return null;for(let t=0;t<e.args.length;t++){const n=s(e.args[t],i.concat(t));if(n)return n}return null};return s(e,[])}(s,e.before)??null),{...e,from:s.s,to:t.s,path:i}}).filter(Boolean)}const Ii={full:[],normal:["hidden","detail"],brief:["hidden","detail","minor","tidy","arithmetic","value"]},Ti=(e,t)=>"all"===t||"*"===t||Array.isArray(t)&&t.some(t=>t===e.id||e.tags?.includes(t));function Li(e,t,{parse:n,replaceAt:s}){const i=(e,t,n=[])=>{if(e.s===t)return n;if("op"!==e.type)return null;for(let s=0;s<e.args.length;s++){const r=i(e.args[s],t,n.concat(s));if(r)return r}return null},r=(e,t)=>t.reduce((e,t)=>e.args[t],e);let o=t;const a=[];for(const t of e){let e=i(o,t.from);if(!e){try{o=n(t.from)}catch{a.push(t);continue}e=[]}const l=o;if("solve.reject"===t.id){const t=e.slice(0,-1);e.length&&"|"===r(o,t).op&&(o=s(o,t,r(o,t).args[1-e[e.length-1]]))}else if(t.to!==t.from){let i;try{i=n(t.to)}catch{a.push(t);continue}o=e.length?s(o,e,i):i}a.push({...t,from:l.s,to:o.s,path:e.length?[...e,...t.path??[]]:t.path})}return a}const ji=Nt(yt.ONE),Ci=(e,t)=>"atom"===e.k&&"sym"===e.node.type&&e.node.token===t;function zi(e){switch(e.k){case"num":default:return e;case"atom":return"op"===e.node.type?ln(e.node.op,e.node.args.map(e=>zi(cn(e)))):e;case"add":return _t(yn(e).map(zi));case"mul":{let t=[Nt(e.c)];for(const n of e.fs){const e=zi(n.b);if("add"===e.k&&Lt(n.e)&&n.e.q.isInteger&&n.e.q.sign>0&&n.e.q.n<=BigInt(60))for(let s=0n;s<n.e.q.n;s++)t=Zi(t,yn(e));else t=Zi(t,[Kt(e,n.e)])}return _t(t)}}}function Zi(e,t){const n=[];for(const s of e)for(const e of t)n.push(Ut([s,e]));return yn(_t(n))}function Bi(e,t){const n=new Map;for(const s of yn(zi(e))){const{coef:e,rest:i}=Wt(s);let r=0;const o=[Nt(e)];for(const e of i?wn(i):[]){const{b:n,e:s}="mul"===e.k&&1===e.fs.length&&e.c.isOne?e.fs[0]:{b:e,e:ji};if(Ci(n,t)){if(!Lt(s)||!s.q.isInteger||s.q.sign<0)return null;r+=Number(s.q.n)}else{if(Fi(n,t)||Fi(s,t))return null;o.push(e)}}n.set(r,_t([n.get(r)??Nt(yt.ZERO),Ut(o)]))}for(const[e,t]of n)Lt(t)&&t.q.isZero&&n.delete(e);return n}const Fi=(e,t)=>bn(mn(e)).has(t);function Di(e){if(!e)return null;const t=Math.max(0,...e.keys());if(t>256)return null;const n=[];for(let s=0;s<=t;s++){const t=e.get(s)??Nt(yt.ZERO);if(!Lt(t))return null;n.push(t.q)}return n}function Pi(e,t){const n=cn(Ge(t));return _t(e.map((e,t)=>Ut([Nt(e),Ht(n,Nt(yt.of(t)))])))}const Ri=e=>{const t=e.slice();for(;t.length>1&&t[t.length-1].isZero;)t.pop();return t},Wi=(e,t)=>e.reduceRight((e,n)=>e.mul(t).add(n),yt.ZERO);function _i(e,t){const n=e.length-1,s=new Array(n);let i=yt.ZERO;for(let r=n;r>=1;r--)i=e[r].add(i.mul(t)),s[r-1]=i;return s}function Vi(e){if(0n===(e=(e=>e<0n?-e:e)(e)))return null;if(e>10n**14n)return null;const t=[];let n=e;for(let e=2n;e*e<=n;e+=2n===e?1n:2n){if(n%e)continue;let s=0;for(;n%e===0n;)n/=e,s++;t.push([e,s])}n>1n&&t.push([n,1]);let s=[1n];for(const[e,n]of t){const t=[];for(const i of s)for(let s=0,r=1n;s<=n;s++,r*=e)t.push(i*r);if(s=t,s.length>2e4)return null}return s.sort((e,t)=>e<t?-1:e>t?1:0)}function Ui(e){let t=Ri(e);const n=[];for(;t.length>1&&t[0].isZero;)n.push(yt.ZERO),t=t.slice(1);if(t.length<=1)return{roots:n,rest:t};const s=t.reduce((e,t)=>e*t.d/bt(e,t.d),1n),i=t.map(e=>e.n*s/e.d),r=Vi(i[0]),o=Vi(i[i.length-1]);if(!r||!o)return{roots:n,rest:t};const a=new Map;for(const e of r)for(const t of o)for(const n of[1n,-1n]){const s=new yt(n*e,t);a.set(s.toString(),s)}const l=[...a.values()].sort((e,t)=>e.compare(t));for(const e of l)for(;t.length>1&&Wi(t,e).isZero;)n.push(e),t=_i(t,e);return{roots:n.sort((e,t)=>e.compare(t)),rest:t}}function Hi(e,t){const n=Ri(t);let s=Ri(e);const i=n[n.length-1];if(i.isZero)throw new dt("division by the zero polynomial");const r=new Array(Math.max(1,s.length-n.length+1)).fill(yt.ZERO);for(;s.length>=n.length&&(1!==s.length||!s[0].isZero);){const e=s.length-n.length,t=s[s.length-1].div(i);if(r[e]=t,s=Ri(s.map((s,i)=>i>=e&&i-e<n.length?s.sub(t.mul(n[i-e])):s)),s.length-1<e+n.length-1&&s[s.length-1].isZero)break;if(s.length<n.length)break}return{q:Ri(r),r:s}}function Ki(e){if("num"===e.k)return{coef:e.q,factors:[],notes:[]};if("atom"===e.k)return{coef:yt.ONE,factors:[{base:e,exp:ji}],notes:[]};if("mul"===e.k){let t=e.c;const n=[],s=[];for(const i of e.fs)if("add"===i.b.k&&Lt(i.e)&&i.e.q.isInteger){const e=Ki(i.b);t=t.mul(e.coef.pow(i.e.q.n));for(const t of e.factors)n.push({base:t.base,exp:Ut([t.exp,i.e])});s.push(...e.notes)}else n.push({base:i.b,exp:i.e});return Ji(t,n,s)}return Yi(e)}function Ji(e,t,n){const s=new Map;for(const e of t){const t=zt(e.base),n=s.get(t);n?n.exp=_t([n.exp,e.exp]):s.set(t,{...e})}return{coef:e,factors:[...s.values()].filter(e=>!(Lt(e.exp)&&e.exp.q.isZero)),notes:n}}const Qi=e=>Wt(yn(e)[0]).coef.sign;function Yi(e){const t=yn(e),n=[],s=t.map(e=>{const{coef:t,rest:n}=Wt(e);return{coef:t,fs:n?wn(n).map(Gi):[]}}),i=s.reduce((e,t)=>({n:bt(e.n,t.coef.n),d:e.d*t.coef.d/bt(e.d,t.coef.d)}),{n:0n,d:1n});let r=new yt(i.n||1n,i.d);Qi(e)<0&&(r=r.neg());const o=[];for(const e of s[0].fs){if(!Lt(e.e)){const t=zt(e.b),n=zt(e.e);s.slice(1).every(e=>e.fs.some(e=>zt(e.b)===t&&zt(e.e)===n))&&o.push({base:e.b,exp:e.e});continue}if(e.e.q.sign<=0)continue;let t=e.e.q;const n=zt(e.b);let i=!0;for(const e of s.slice(1)){const s=e.fs.find(e=>zt(e.b)===n&&Lt(e.e)&&e.e.q.sign>0);if(!s){i=!1;break}s.e.q.compare(t)<0&&(t=s.e.q)}i&&o.push({base:e.b,exp:Nt(t)})}let a=e;if(!r.isOne||o.length){const e=Ut([Nt(r),...o.map(e=>Kt(e.base,e.exp))]);a=_t(t.map(t=>Ut([t,Ht(e,Nt(yt.MINUS_ONE))]))),n.push({id:"factor.common",values:{common:e}})}const l="add"===a.k&&zt(a)!==zt(e),u="add"!==a.k?Ki(a):l?Yi(a):function(e,t){const n=[...Xi(e)];for(const s of n){const i=Di(Bi(e,s));if(!i||i.length<3)continue;if(1!==n.length)break;const{roots:r,rest:o}=Ui(i);if(!r.length)break;const a=[];let l=o[o.length-1]??yt.ONE;const u=o.map(e=>e.div(l)),c=[...r].sort((e,t)=>e.abs().compare(t.abs())||t.sign-e.sign);for(const e of c){const n=Pi([new yt(-e.n),new yt(e.d)],s);a.push({base:n,exp:ji}),l=l.div(new yt(e.d)),t.push({id:"factor.root",values:{root:Nt(e),factor:n}})}if(u.length>1){const e=u.reduce((e,t)=>e*t.d/bt(e,t.d),1n),t=u.map(t=>t.mul(new yt(e))),n=t.reduce((e,t)=>bt(e,t.n),0n)||1n;l=l.mul(new yt(n,e)),a.push({base:Pi(t.map(e=>e.div(new yt(n))),s),exp:ji})}return Ji(l,a,[])}const s=yn(e);if(2===s.length){const[e,n]=s;for(const s of[2,3]){const i=er(e,s),r=er(sn(n),s),o=3===s?er(n,s):null;if(i&&r&&2===s){t.push({id:"factor.squares",values:{a:i,b:r}});const e=Ki(_t([i,sn(r)])),n=Ki(_t([i,r]));return Ji(e.coef.mul(n.coef),[...e.factors,...n.factors],[...e.notes,...n.notes])}if(3===s&&i&&(r||o)){const e=r??o,n=r?-1:1;t.push({id:n<0?"factor.cubes-difference":"factor.cubes-sum",values:{a:i,b:e}});const s=_t(n<0?[i,sn(e)]:[i,e]),a=_t([Ht(i,Nt(yt.of(2))),n<0?Ut([i,e]):sn(Ut([i,e])),Ht(e,Nt(yt.of(2)))]),l=Ki(s);return Ji(l.coef,[...l.factors,{base:a,exp:ji}],l.notes)}}}return{coef:yt.ONE,factors:[{base:e,exp:ji}],notes:[]}}(a,n);if(l&&n.length){const e=u.notes.findIndex(e=>"factor.common"===e.id);e>=0&&(n[0].values.common=Ut([n[0].values.common,u.notes.splice(e,1)[0].values.common]))}return Ji(r.mul(u.coef),[...o,...u.factors],[...n,...u.notes.filter(e=>!n.includes(e))])}const Gi=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length?{b:e.fs[0].b,e:e.fs[0].e}:{b:e,e:ji},Xi=e=>bn(mn(e));function er(e,t){const{coef:n,rest:s}=Wt(e);if(n.sign<0)return null;const i=function(e,t){const n=e=>{if(e<0n)return null;let n=0n,s=1n;for(;s**BigInt(t)<=e;)s*=2n;for(;n<s-1n;){const i=(n+s)/2n;i**BigInt(t)<=e?n=i:s=i}return n**BigInt(t)===e?n:null},s=n(e.n),i=n(e.d);return null!==s&&null!==i?new yt(s,i):null}(n,t);if(!i)return null;const r=[Nt(i)];for(const e of s?wn(s).map(Gi):[]){if(!Lt(e.e))return null;const n=e.e.q.div(yt.of(t));if(!n.isInteger)return null;r.push(Kt(e.b,Nt(n)))}return Ut(r)}function tr({coef:e,factors:t}){const n=[],s=[];for(const e of t){const t=Lt(e.exp)&&e.exp.q.sign<0,i=t?Nt(e.exp.q.neg()):e.exp,r=mn(Kt(e.base,i));(t?s:n).push(r)}const i=e=>e.reduce((e,t)=>e?nt("*",[e,t]):t,null),r=e.n<0n?-e.n:e.n;let o=n.length?i(1n===r?n:[mn(Nt(new yt(r))),...n]):mn(Nt(new yt(r)));return e.n<0n&&(o=nt("neg",[o])),1n!==e.d&&s.unshift(mn(Nt(new yt(e.d)))),s.length?nt("/",[o,i(s)]):o}function nr(e){if("mul"!==e.k||!e.fs.some(e=>"add"===e.b.k&&Lt(e.e)&&e.e.q.isInteger))return function(e){if("mul"!==e.k)return{num:e,den:ji};const t=[Nt(new yt(e.c.n))],n=[Nt(new yt(e.c.d))];for(const s of e.fs)Lt(s.e)&&s.e.q.sign<0?n.push(Kt(s.b,Nt(s.e.q.neg()))):t.push(Kt(s.b,s.e));return{num:Ut(t),den:Ut(n)}}(e);const t=[Nt(new yt(e.c.n))],n=[Nt(new yt(e.c.d))];for(const s of e.fs){const e=Lt(s.e)&&s.e.q.sign<0,i=e?Nt(s.e.q.neg()):s.e,r="add"===s.b.k&&Lt(s.e)&&s.e.q.isInteger?sr(s.b):null;!r||Lt(r.den)&&r.den.q.isOne?(e?n:t).push(Kt(s.b,i)):((e?n:t).push(Kt(r.num,i)),(e?t:n).push(Kt(r.den,i)))}return{num:Ut(t),den:Ut(n)}}function sr(e){if("add"!==e.k)return nr(e);const t=yn(e).map(nr),n=new Map;let s=1n;for(const e of t){const{coef:t,rest:i}=Wt(e.den);s=s*t.n/bt(s,t.n);for(const e of i?wn(i).map(Gi):[]){const t=zt(e.b),s=n.get(t);(!s||Lt(e.e)&&Lt(s.e)&&e.e.q.compare(s.e.q)>0)&&n.set(t,e)}}const i=Ut([Nt(new yt(s)),...[...n.values()].map(e=>Kt(e.b,e.e))]);if(Lt(i)&&i.q.isOne)return{num:e,den:ji};return{num:zi(_t(t.map(e=>Ut([e.num,i,Ht(e.den,Nt(yt.MINUS_ONE))])))),den:i}}function ir(e){const{num:t,den:n}=sr(e);if(Lt(n)&&n.q.isOne)return null;const s=Ki(n),i=e=>{const t=new Set(e.factors.map(e=>zt(e.base))),n=s.factors.filter(e=>t.has(zt(e.base))),i=[...e.factors,...s.factors.map(e=>({base:e.base,exp:sn(e.exp)}))];return{...Ji(e.coef.div(s.coef),i,[...e.notes,...s.notes]),canceled:n.map(e=>e.base)}},r=i(Ki(t)),o="add"===t.k?zi(t):t;if(zt(o)===zt(t))return r;const a=i(Ki(o));return lt(tr(a))<lt(tr(r))?a:r}const rr=(e,t)=>nt("=",[e,t]),or=fn(nt("+",[Ge("x"),nt("neg",[Ge("x")])])),ar=e=>it(e)&&"="===e.op;function lr(e,t,n,s={}){const i=[],r=(t,n,s,r,o,a={})=>i.push(e.step(t,n,s,r,o,a));r.raw=e=>i.push(e);const o=ar(t)?t:rr(t,or),a=rr(fn(o.args[0]),fn(o.args[1]));a.s!==o.s&&r("normal","Work out each side",["tidy","arithmetic"],o,a);const l=[],u=[],c=new Set;l.numeric=c,mr(e,a,n,s,r,l,u,0);const f=[],h=new Set,p=t=>bn(t).size&&e.simplify?e.simplify(t,{steps:!1}).result:ui(t,e.set.view("simplify"),{format:e.format}).node,d=new Map;for(const e of l){const t=c.has(e)?e:p(e),s=t.s;if(h.has(s))continue;h.add(s);const i=c.has(e)?null:hr(o,n,t);i?r("solve.reject","Check the answer",["check"],rr(Ge(n),t),rr(Ge(n),t),{value:t,reason:i}):(l.periodOf?.has(e)&&d.set(t,l.periodOf.get(e)),f.push(t))}if(f.sort(cr),s.interval){const t=function(e,t,n,[s,i],r,o,a){const l=fn(e.node(s)),u=fn(e.node(i)),c=fr(l),f=fr(u);if(!c||!f||Math.abs(c.im)>1e-12||Math.abs(f.im)>1e-12)throw new dt("the interval is two numbers, lo and hi");if(c.re>f.re)throw new dt("the interval starts after it ends");const h=e=>e>=c.re-1e-9&&e<=f.re+1e-9,p=[],d=new Set,m=e=>{d.has(e.s)||(d.add(e.s),p.push(e))};let g=null;for(const e of t){const t=fr(e);if(!t||Math.abs(t.im)>1e-12)continue;const s=n.get(e);if(void 0===s){h(t.re)&&m(e);continue}if(null===s){g=[o],h(t.re)&&m(e);continue}const i=fr(s).re,l=Math.ceil((c.re-t.re)/i-1e-9),u=Math.floor((f.re-t.re)/i+1e-9);if(u-l+1>ur)throw new dt(`more than ${ur} answers in that interval`);for(let t=l;t<=u;t++){const n=0===t?e:r(mn(_t([cn(e),Ut([Nt(yt.of(t)),cn(s)])])));hr(o,a,n)||m(n)}}return p.sort(cr),{values:p,lo:l,hi:u,uneven:g}}(e,f,d,s.interval,e=>p(e),o,n);return t.uneven&&u.push(...t.uneven),{solutions:t.values,base:f,unsolved:u,steps:i,always:u.some(e=>e.always),periodic:!1,period:null,interval:[t.lo,t.hi]}}const m=l.periods??[],g=f.length&&m.length&&m.every(e=>e&&e.s===m[0].s)?m[0]:null;return{solutions:f,unsolved:u,steps:i,always:u.some(e=>e.always),periodic:m.length>0&&f.length>0,period:g}}const ur=200;function cr(e,t){const n=fr(e),s=fr(t);return null===n||null===s?e.s<t.s?-1:1:(Math.abs(n.im)>0)-(Math.abs(s.im)>0)||n.re-s.re||n.im-s.im}function fr(e){if(bn(e).size)return null;try{const{re:t,im:n}=Hs(e,{digits:20});return{re:t,im:n}}catch{return null}}function hr(e,t,n){const[s,i]=e.args,r=new Set([...bn(s),...bn(i),...bn(n)]);if(r.delete(t),r.size)return null;const o=e=>pr(e,t,n);try{const e=Hs(o(s),{digits:40}),t=Hs(o(i),{digits:40}),n=Math.max(1,Math.hypot(e.re,e.im),Math.hypot(t.re,t.im));return Math.hypot(e.re-t.re,e.im-t.im)>1e-12*n?"it does not make the two sides equal":null}catch(e){return`the original equation has no value there (${e.message})`}}function pr(e,t,n){return"sym"===e.type?e.token===t?n:e:it(e)?nt(e.op,e.args.map(e=>pr(e,t,n))):e}const dr=24;function mr(e,t,n,s,i,r,o,a){if(a>dr)return Mr(e,t,n,s,i,r,o);const l=function(e){const t=[],n=e=>{if(it(e)&&"|"===e.op)return void e.args.forEach(n);if(!ar(e))return void t.push(e);const s=e.args[1],i=ft(s,"pre").find(({node:e})=>it(e)&&"pm"===e.op);if(!i)return void t.push(e);const r=i.node.args[0],o=fn(pt(s,i.path,r)),a=fn(pt(s,i.path,nt("neg",[r])));n(rr(e.args[0],o)),a.s!==o.s&&n(rr(e.args[0],a))};return n(e),t}(t);if(l.length>1){i("solve.split","Two cases",["split","minor"],t,l.reduce((e,t)=>e?nt("|",[e,t]):t,null));for(const t of l)mr(e,t,n,s,i,r,o,a+1);return}if(1===l.length&&l[0].s!==t.s)return mr(e,l[0],n,s,i,r,o,a+1);const[u,c]=t.args;if("sym"===u.type&&u.token===n&&!Fi(cn(c),n))return void r.push(c);const f=_t([cn(u),sn(cn(c))]);if(!Fi(f,n))return Lt(f)&&f.q.isZero?(i("solve.always","Always true",["check"],t,t,{v:n}),void o.push(Object.assign(Object.create(t),{always:!0}))):void i("solve.never","No solution",["check"],t,t,{v:n});const h=yn(f).filter(e=>Fi(e,n)),p=yn(f).filter(e=>!Fi(e,n)),d=_t(h),m=sn(_t(p));if(St.complex){const l=Bi(f,n);if(l&&[...l.values()].every(e=>!Fi(e,n))&&Math.max(...l.keys())>=2){const u=rr(mn(f),or);return u.s!==t.s&&i("solve.one-side","Everything on one side",["move","minor"],t,u,{v:n}),xr(e,f,l,n,s,i,r,o,a,u)}}if(1===h.length)return gr(e,t,d,m,n,s,i,r,o,a);const g=rr(mn(f),or),v=Bi(f,n);if(v&&[...v.values()].every(e=>!Fi(e,n))&&Math.max(...v.keys())>=2)return g.s!==t.s&&i("solve.one-side","Everything on one side",["move","minor"],t,g,{v:n}),xr(e,f,v,n,s,i,r,o,a,g);if(v&&1===Math.max(...v.keys())&&[...v.values()].every(e=>!Fi(e,n))){const l=v.get(1),u=Ut([l,cn(Ge(n))]),c=sn(v.get(0)??Nt(yt.ZERO)),f=rr(mn(u),mn(c));return i("solve.collect","Collect the terms",["move","minor"],t,f,{v:n,a:mn(l)}),gr(e,f,u,c,n,s,i,r,o,a)}const b=Ki(f),y=b.factors.filter(e=>(Fi(e.base,n)||Fi(e.exp,n))&&!(Lt(e.exp)&&e.exp.q.sign<0));if(y.length>=2||1===y.length&&b.factors.length>1){const l=rr(tr(b),or);g.s!==t.s&&i("solve.one-side","Everything on one side",["move","minor"],t,g,{v:n}),l.s!==g.s&&i("solve.factor","Factor",["factor"],g,l,{});const u=y.filter(e=>vr(Kt(e.base,e.exp)));if(u.length){const t=y.filter(e=>!u.includes(e)),c=rr(t.length?tr({coef:yt.ONE,factors:t}):mn(Nt(yt.ONE)),or);return i("solve.never-zero","A factor that is never zero",["move"],l,c,{f:mn(Ut(u.map(e=>Kt(e.base,e.exp))))}),t.length?1===t.length?mr(e,rr(mn(t[0].base),or),n,s,i,r,o,a+1):mr(e,c,n,s,i,r,o,a+1):void i("solve.never","No solution",["check"],c,c,{v:n})}const c=y.map(e=>rr(mn(e.base),or));c.length>1&&i("solve.zero-product","A product is zero when a factor is",["split"],l,c.reduce((e,t)=>e?nt("|",[e,t]):t,null),{});for(const t of c)mr(e,t,n,s,i,r,o,a+1);return}const w=sr(f);if(Fi(w.den,n)){const l=rr(mn(w.num),or);return i("solve.clear-denominator","Clear the denominator",["move"],t,l,{den:mn(w.den)}),mr(e,l,n,s,i,r,o,a+1)}const x=h.filter(e=>!wr(e,n));if(1===x.length&&/\b(sqrt|root|abs)\b/.test(mn(x[0]).s))return gr(e,t,x[0],sn(_t(yn(f).filter(e=>e!==x[0]))),n,s,i,r,o,a);const k=function(e,t){let n=null,s=null,i=null;for(const r of yn(e)){const e=wn(r).map(mn),o=e.filter(e=>Fi(cn(e),t));if(1!==o.length||!it(o[0])||!["sin","cos"].includes(o[0].op))return null;const a=o[0].args[0];if(i&&a.s!==i.s)return null;i=a;const l=Ut(e.filter(e=>e!==o[0]).map(cn));"sin"===o[0].op?n=n?_t([n,l]):l:s=s?_t([s,l]):l}return!n||!s||Lt(n)&&n.q.isZero?null:{a:n,b:s,u:i}}(f,n);if(k){const l=rr(nt("tan",[k.u]),mn(sn(rn(k.b,k.a))));return g.s!==t.s&&i("solve.one-side","Everything on one side",["move","minor"],t,g,{v:n}),i("solve.sin-cos","Divide by the cosine",["trig"],g,l,{u:k.u}),mr(e,l,n,s,i,r,o,a+1)}const q=function(e,t){const n=mn(e),s={sin:new Set,cos:new Set};let i=null,r=!0;const o=(e,n)=>{if(it(e)){if(("sin"===e.op||"cos"===e.op)&&bn(e).has(t)){i&&e.args[0].s!==i.s&&(r=!1),i=e.args[0];const t=n&&"^"===n.op&&n.args[0]===e?mn(cn(n.args[1])):null;return void s[e.op].add(t&&Lt(cn(t))&&cn(t).q.isInteger&&cn(t).q.n%2n==0n?"even":"odd")}["tan","sec","csc","cot"].includes(e.op)&&bn(e).has(t)&&(r=!1);for(const t of e.args)o(t,e)}};if(o(n,null),!(r&&i&&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 l="cos"===a?"sin":"cos",u=e=>{if(!it(e))return e;if("^"===e.op&&it(e.args[0])&&e.args[0].op===a&&e.args[0].args[0].s===i.s){const t=cn(e.args[1]).q.div(yt.of(2));return nt("^",[nt("-",[mn(Nt(yt.ONE)),nt("^",[nt(l,[i]),mn(Nt(yt.of(2)))])]),mn(Nt(t))])}return nt(e.op,e.args.map(u))};return{E:zi(cn(u(n))),u:i,from:a,to:l}}(f,n);if(q)return g.s!==t.s&&i("solve.one-side","Everything on one side",["move","minor"],t,g,{v:n}),i("solve.pythagorean","Use sin² + cos² = 1",["trig"],g,rr(mn(q.E),or),{u:q.u,from:Ge(q.from),to:Ge(q.to),fromName:Ge("sin"===q.from?"sine":"cosine"),toName:Ge("sin"===q.to?"sine":"cosine")}),mr(e,rr(mn(q.E),or),n,s,i,r,o,a+1);const $=function(e,t){const n=mn(e),s=new Map;for(const{node:e}of ft(n,"pre"))if(it(e)&&bn(e).has(t))if("^"!==e.op||bn(e.args[0]).has(t))(["ln","sqrt","abs"].includes(e.op)&&e.args[0].s===t||["sin","cos","tan"].includes(e.op)&&bn(e.args[0]).has(t))&&s.set(e.s,e);else{const n=cn(e.args[1]),{coef:i,rest:r}=Wt(n);if(r&&i.isInteger&&mn(r).s===t){const n=mn(Ht(cn(e.args[0]),cn(Ge(t))));s.set(n.s,n)}}const i="u"===t?"w":"u";for(const e of s.values()){const s=Sr(n,e,t,i);if(!s||bn(s).has(t))continue;const r=cn(s),o=Bi(r,i);if(o&&Math.max(...o.keys())>=1)return{kernel:cn(e),poly:r,symbol:i}}return null}(f,n);if($){const t=$.symbol;i("solve.substitute","Substitute",["substitute"],g,rr(mn($.poly),or),{u:Ge(t),kernel:mn($.kernel)});const l=[];mr(e,rr(mn($.poly),or),t,s,i,l,o,a+1);for(const u of l){const l=rr(mn($.kernel),u);i("solve.back","Substitute back",["substitute"],rr(Ge(t),u),l,{u:Ge(t),kernel:mn($.kernel)}),mr(e,l,n,s,i,r,o,a+1)}return}return Mr(e,g,n,s,i,r,o)}function gr(e,t,n,s,i,r,o,a,l,u){let c=rr(mn(n),mn(s));c.s!==t.s&&o("solve.move","Move the terms",["move","minor"],t,c,{v:i});const{coef:f,rest:h}=Wt(n),p=h?wn(h):[],d=Ut([Nt(f),...p.filter(e=>!Fi(e,i))]);if(!Lt(d)||!d.q.isOne){const e=Ut(p.filter(e=>Fi(e,i))),t=rr(mn(e),mn(rn(s,d))),n=Lt(d)&&!d.q.isInteger&&(1n===d.q.n||-1n===d.q.n);o(n?"solve.multiply":"solve.divide",n?"Multiply both sides":"Divide both sides",["move","minor"],c,t,{by:mn(n?Nt(d.q.inv()):d),v:i}),c=t}if("sym"===c.args[0].type&&c.args[0].token===i)return void a.push(c.args[1]);const m=cn(c.args[1]);if(Lt(m)&&m.q.isZero){const t=cn(c.args[0]),n=wn(t).filter(e=>Fi(e,i)&&!br(e)&&!vr(e)),s=wn(t).filter(e=>Fi(e,i)&&!br(e)&&vr(e));if(s.length&&n.length){const t=rr(mn(Ut(n)),or);return o("solve.never-zero","A factor that is never zero",["move"],c,t,{f:mn(Ut(s))}),mr(e,t,i,r,o,a,l,u+1)}if(s.length&&!wn(t).some(e=>Fi(e,i)&&br(e)))return void o("solve.never","No solution",["check"],c,c,{v:i});if(!n.length&&wn(t).some(e=>Fi(e,i)))return void o("solve.never","No solution",["check"],c,c,{});if(n.length>1||n.length<wn(t).filter(e=>Fi(e,i)).length){const t=n.map(e=>rr(mn(yr(e)),or));o("solve.zero-product","A product is zero when a factor is",["split"],c,t.reduce((e,t)=>e?nt("|",[e,t]):t,null),{});for(const n of t)mr(e,n,i,r,o,a,l,u+1);return}}const g=ui(c,e.set.view("isolate"),{format:e.format,maxSteps:1,variable:i});if(g.steps.length){const t=function(e,t,n,s){const i=(e.tags??[]).find(e=>"period-2pi"===e||"period-pi"===e);if(!i)return;s.periods??=[];const r=t.args[0].args?.[0];let o=null;try{const e=r?Bi(zi(cn(r)),n):null,t=e&&[...e.keys()].every(e=>0===e||1===e)?e.get(1):null;t&&!Fi(t,n)&&Lt(t)&&!t.q.isZero&&(o=mn(Ut([Nt(new yt("period-2pi"===i?2n:1n,1n).div(t.q.abs())),cn(Ge("pi"))])))}catch{}return s.periods.push(o),o}(g.steps[0],c,i,a);!function(e,t){for(const n of t)e.raw(n)}(o,g.steps);const n=a.length;if(mr(e,g.node,i,r,o,a,l,u+1),void 0!==t){a.periodOf??=new Map;for(const e of a.slice(n))a.periodOf.has(e)||a.periodOf.set(e,t)}return}const v=wn(cn(c.args[0])).filter(e=>Fi(e,i)&&br(e));if(v.length&&(!Lt(m)||!m.q.isZero)){const t=Ht(Ut(v),Nt(yt.MINUS_ONE)),n=rr(mn(Ut([cn(c.args[0]),t])),mn(zi(Ut([m,t]))));return o("solve.clear-denominator","Clear the denominator",["move"],c,n,{den:mn(t)}),mr(e,n,i,r,o,a,l,u+1)}const b=cn(c.args[0]),y=zi(b),w=zt(y)!==zt(b)?Bi(y,i):null;if(w&&[...w.values()].every(e=>!Fi(e,i))&&yn(y).length>1){const t=rr(mn(y),c.args[1]);return o("solve.expand","Multiply out",["expand"],c,t,{v:i}),mr(e,t,i,r,o,a,l,u+1)}return Mr(e,c,i,r,o,a,l)}function vr(e){const t=mn(e);if(!it(t)||"^"!==t.op)return!1;const n=cn(t.args[0]);return"sym"===n.type&&("e"===n.token||"=e"===n.token)||Lt(n)&&n.q.sign>0||"e"===mn(n).s}const br=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&Lt(e.fs[0].e)&&e.fs[0].e.q.sign<0,yr=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&Lt(e.fs[0].e)&&e.fs[0].e.q.sign>0?e.fs[0].b:e,wr=(e,t)=>{const n=Bi(e,t);return Boolean(n)&&[...n.values()].every(e=>!Fi(e,t))};function xr(e,t,n,s,i,r,o,a,l,u){const c=Math.max(...n.keys()),f=Di(n);if(St.complex&&c>=3&&c<=64&&f&&f.every((e,t)=>0===t||t===c||e.isZero)&&!f[0].isZero){const t=f[0].neg().div(f[c]),n=Ht(Nt(t.abs()),Nt(new yt(1n,BigInt(c)))),i=[];for(let s=0;s<c;s++){const r=Ut([Nt(new yt(BigInt((t.sign<0?1:0)+2*s),BigInt(c))),cn(Ge("pi"))]),o=nt("*",[mn(n),nt("+",[nt("cos",[mn(r)]),nt("*",[Ge("i"),nt("sin",[mn(r)])])])]);i.push(ui(o,e.set.view("simplify"),{format:e.format}).node)}return r("solve.roots","All n roots",["complex"],u,i.map(e=>rr(Ge(s),e)).reduce((e,t)=>e?nt("|",[e,t]):t),{v:s,n:String(c),last:String(c-1),r:mn(Nt(t))}),void o.push(...i)}if(qr(n)===c/2&&c>=4)return $r(e,n,c/2,s,i,r,o,a,l,u);if(f){const{roots:n}=Ui(f);if(n.length){const n=Ki(t),c=rr(tr(n),or);if(n.factors.length>1||n.factors.some(e=>!(Lt(e.exp)&&e.exp.q.isOne))){r("solve.factor","Factor",["factor"],u,c,{});const t=n.factors.filter(e=>Fi(e.base,s)).map(e=>rr(mn(e.base),or));t.length>1&&r("solve.zero-product","A product is zero when a factor is",["split"],c,t.reduce((e,t)=>e?nt("|",[e,t]):t,null),{});for(const n of t)mr(e,n,s,i,r,o,a,l+1);return}}}const h=qr(n);if(h>=2&&c>2&&c/h<=4)return $r(e,n,h,s,i,r,o,a,l,u);if(2===c){const e=n.get(2),t=n.get(1)??Nt(yt.ZERO),i=n.get(0)??Nt(yt.ZERO),a=_t([Ht(t,Nt(yt.of(2))),Ut([Nt(yt.of(-4)),e,i])]);if(Lt(a)&&a.q.sign<0&&!St.complex)return void r("solve.no-real","No real solutions",["quadratic"],u,u,{D:mn(a)});const l=Ut([Nt(yt.of(2)),e]),c=Ht(a,Nt(yt.HALF)),f=mn(rn(_t([sn(t),c]),l)),h=mn(rn(_t([sn(t),sn(c)]),l)),p=f.s===h.s?rr(Ge(s),f):nt("|",[rr(Ge(s),f),rr(Ge(s),h)]);return r(St.complex&&Lt(a)&&a.q.sign<0?"solve.quadratic-complex":"solve.quadratic","The quadratic formula",["quadratic"],u,p,{a:mn(e),b:mn(t),c:mn(i),D:mn(a),root:mn(c),v:s}),o.push(f),void(h.s!==f.s&&o.push(h))}return Mr(e,u,s,i,r,o,a)}const kr=(e,t)=>t?kr(t,e%t):e,qr=e=>[...e.keys()].filter(e=>e>0).reduce((e,t)=>kr(e,t),0);function $r(e,t,n,s,i,r,o,a,l,u){const c="u"===s?"w":"u",f=Ht(cn(Ge(s)),Nt(yt.of(n))),h=_t([...t.entries()].map(([e,t])=>Ut([t,Ht(cn(Ge(c)),Nt(yt.of(e/n)))])));r("solve.substitute","Substitute",["substitute"],u,rr(mn(h),or),{u:Ge(c),kernel:mn(f)});const p=[];mr(e,rr(mn(h),or),c,i,r,p,a,l+1);for(const t of p){const n=rr(mn(f),t);r("solve.back","Substitute back",["substitute"],rr(Ge(c),t),n,{u:Ge(c),kernel:mn(f)}),mr(e,n,s,i,r,o,a,l+1)}}function Sr(e,t,n,s){if(e.s===t.s)return Ge(s);if(!it(e))return e;if("^"===e.op&&"^"===t.op&&e.args[0].s===t.args[0].s){const t=cn(e.args[1]),{coef:i,rest:r}=Wt(t);if(r&&mn(r).s===n&&i.isInteger)return nt("^",[Ge(s),mn(Nt(i))])}return nt(e.op,e.args.map(e=>Sr(e,t,n,s)))}function Mr(e,t,n,s,i,r,o){if(s.approximate){const e="number"==typeof s.approximate?s.approximate:15,o=cn(nt("-",[t.args[0],t.args[1]])),a=St.complex?Di(Bi(o,n)):null,l=a&&a.length>2?function(e,t){const n=e.length-1,s=e[n],i=e.map(e=>e/s),r=(e,t)=>{let s=1,r=0;for(let o=n-1;o>=0;o--)[s,r]=[s*e-r*t+i[o],s*t+r*e];return[s,r]};let o=Array.from({length:n},(e,t)=>[1.3*Math.cos(2*Math.PI*t/n+.4),1.3*Math.sin(2*Math.PI*t/n+.4)]);for(let e=0;e<500;e++){let e=0;if(o=o.map(([t,s],i)=>{let[a,l]=r(t,s);for(let e=0;e<n;e++){if(e===i)continue;const n=t-o[e][0],r=s-o[e][1],u=n*n+r*r;[a,l]=[(a*n+l*r)/u,(l*n-a*r)/u]}return e=Math.max(e,Math.hypot(a,l)),[t-a,s-l]}),e<1e-15)break}const a=e=>Math.abs(e)<1e-12?0:Number(e.toPrecision(t));return o.map(([e,t])=>[a(e),a(t)]).sort((e,t)=>(0!==e[1])-(0!==t[1])||e[0]-t[0]||e[1]-t[1]).map(([e,t])=>{const n=Or(e);if(0===t)return n;const s=nt("*",[Or(Math.abs(t)),Ge("i")]);return 0===e?t<0?nt("neg",[s]):s:nt(t<0?"-":"+",[n,s])})}(a.map(e=>e.toNumber()),Math.min(e,14)):function(e,t,n){const s=cn(nt("-",[e.args[0],e.args[1]])),i=mn(s),r=e=>{try{return Hs(pr(i,t,Ar(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 t=a[e],s=a[e+1],i=r(t);const l=r(s);if(Number.isNaN(i)||Number.isNaN(l))continue;if(0===i){o.push(Ar(t));continue}if(i*l>0)continue;for(let e=0;e<200&&s-t>1e-16*Math.abs(t);e++){const e=(t+s)/2,n=r(e);if(Number.isNaN(n))break;i*n<=0?s=e:(t=e,i=n)}const u=(t+s)/2;Math.abs(r(u))<1e-6&&o.push(Ar(Number(u.toPrecision(Math.min(n,15)))))}return o}(t,n,e);for(const e of l)r.numeric?.add(e);return i("solve.numeric","Numeric solutions",["numeric"],t,l.length?l.map(e=>rr(Ge(n),e)).reduce((e,t)=>e?nt("|",[e,t]):t):t,{v:n,count:String(l.length)}),void r.push(...l)}i("solve.unsolved","No exact method",["unsolved"],t,t,{v:n}),o.push(t)}const Or=e=>Xe(String(e).includes("e")?e.toFixed(20):String(e)),Ar=e=>Xe(Number.isInteger(e)?String(e):e.toFixed(17)),Nr=["first","second","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth"];const Er=()=>Xe("1"),Ir={"<":e=>e<0,">":e=>e>0,"≤":e=>e<=0,"≥":e=>e>=0},Tr=new Set(["sin","cos","tan","csc","sec","cot"]);function Lr(e,t,n,s={}){const i=[],r=[],o=[];let a=t;for(;it(a.args[0])&&Ir[a.args[0].op];)o.unshift({op:a.op,right:a.args[1]}),a=a.args[0];const l=[a.args[0],a.args[1],...o.map(e=>e.right)];[a.op,...o.map(e=>e.op)].forEach((e,t)=>r.push({h:fn(nt("-",[l[t],l[t+1]])),op:e}));const u=new Set(r.flatMap(e=>[...bn(e.h)]));if(u.delete(n),u.size)throw new dt(`an inequality in ${n} with other unknowns (${[...u].join(", ")}) can't be charted`);const c=s.interval?s.interval.map(t=>fn(e.node(t))):null;if(!c&&r.some(e=>ft(e.h,"pre").some(({node:e})=>it(e)&&Tr.has(e.op)&&bn(e).has(n))))return{pieces:null,steps:i,unsolved:!0};const f=[];for(const{h:e}of r){f.push(e);for(const{node:t}of ft(e,"pre"))it(t)&&bn(t).has(n)&&("/"===t.op&&f.push(t.args[1]),"sqrt"!==t.op&&"ln"!==t.op||f.push(t.args[0]),"root"===t.op&&f.push(t.args[1]),"log"===t.op&&f.push(t.args[1],t.args[0],nt("-",[t.args[0],Er()])),["arcsin","arccos","arctanh","arcsec","arccsc"].includes(t.op)&&f.push(nt("-",[t.args[0],Er()]),nt("+",[t.args[0],Er()])),"arccosh"===t.op&&f.push(nt("-",[t.args[0],Er()])),"^"===t.op&&Lt(cn(t.args[1]))&&cn(t.args[1]).q.sign<0&&f.push(t.args[0]),"^"===t.op&&Lt(cn(t.args[1]))&&!cn(t.args[1]).q.isInteger&&f.push(t.args[0]))}const h=new Map;for(const t of f){const s=lr(e,rr(t,or),n,{...c?{interval:c}:{}});if(s.unsolved.length&&!s.always)return{pieces:null,steps:i,unsolved:!0};if(!s.always)for(const e of s.solutions){const t=fr(e);!t||Math.abs(t.im)>1e-12||h.set(e.s,{node:e,x:t.re})}}let p=[...h.values()].sort((e,t)=>e.x-t.x).filter((e,t,n)=>0===t||Math.abs(e.x-n[t-1].x)>1e-12),d=null;if(c){const[e,t]=c.map(e=>({node:e,x:fr(e)?.re}));if(!Number.isFinite(e.x)||!Number.isFinite(t.x)||e.x>t.x)throw new dt("the interval is two numbers, lo then hi");d={lo:e,hi:t},p=p.filter(n=>n.x>e.x+1e-12&&n.x<t.x-1e-12)}const m=e=>r.every(({h:t,op:s})=>{try{const i=Hs(pr(t,n,Xe(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)&&Ir[s](Math.abs(i.re)<1e-30?0:i.re)}catch{return!1}}),g=e=>r.every(({h:t,op:s})=>{try{const i=Hs(fn(pr(t,n,e.node)),{digits:30});return!(!Number.isFinite(i.re)||Math.abs(i.im)>1e-12)&&Ir[s](Math.abs(i.re)<1e-15?0:i.re)}catch{return!1}});if(d)return function(e,t,n,s,i,{lo:r,hi:o},a,l){const u=[r,...i,o],c=u.map(l),f=u.slice(1).map((e,t)=>a((u[t].x+e.x)/2)),h=[];let p=null;for(let e=0;e<u.length;e++){const t=u[e];if(c[e]&&!p?p={lo:t.node,loClosed:!0}:!c[e]&&p&&(h.push({...p,hi:t.node,hiClosed:!1}),p=null),e===u.length-1)break;f[e]?p??={lo:t.node,loClosed:!1}:p&&(h.push({...p,hi:t.node,hiClosed:c[e]}),p=null)}p&&h.push({...p,hi:o.node,hiClosed:c[u.length-1]});for(const e of h)e.lo.s===e.hi.s&&(e.loClosed=!0,e.hiClosed=!0);const d=i.length?i.map(t=>e.format(t.node)).join(", "):"none";return s.push(e.step("solve.sign-chart","A sign chart",["inequality"],t,t,{points:Ge(d),v:n})),{pieces:h,steps:s,interval:[r.node,o.node]}}(e,t,n,i,p,d,m,g);const v=p.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=p.map(g),x=[];let k=null;const q=(e,t)=>{x.push({...k,hi:e,hiClosed:t}),k=null};for(let e=0;e<=p.length;e++){const t=0===e?null:p[e-1].node;if(y[e]?k??={lo:t,loClosed:!1}:k&&q(t,e>0&&w[e-1]),e===p.length)break;const n=p[e];if(w[e]){if(k)continue;y[e+1]?k={lo:n.node,loClosed:!0}:x.push({lo:n.node,hi:n.node,loClosed:!0,hiClosed:!0})}else k&&q(n.node,!1)}k&&q(null,!1);const $=p.length?p.map(t=>e.format(t.node)).join(", "):"none";return i.push(e.step("solve.sign-chart","A sign chart",["inequality"],t,t,{points:Ge($),v:n})),{pieces:x,steps:i}}const jr={tan:"cos",sec:"cos",csc:"sin",cot:"sin"};class Cr extends Error{}const zr=e=>({fin:e}),Zr={bnd:!0},Br=e=>({inf:e}),Fr=Ge("∞");function Dr(e){try{const t=Hs(e,{digits:15});return Math.abs(t.im??0)>1e-12?NaN:t.re??t.number}catch{return NaN}}function Pr(e){if(!St.complex)return Number.isFinite(Dr(e));try{const t=Hs(e,{digits:15});return Number.isFinite(t.re??t.number)&&Number.isFinite(t.im??0)}catch{return!1}}function Rr(e,t,n){if(!Number.isFinite(n))return!1;try{const s=Hs(pr(e,t,Xe(_r(n))),{digits:15});return Math.abs(s.im??0)>1e-12}catch(e){return/not real/.test(e.message)}}function Wr(e,t,n){return Number.isFinite(n)?Dr(pr(e,t,Xe(_r(n)))):NaN}function _r(e){const t=Math.min(40,Math.max(0,16-Math.floor(Math.log10(Math.abs(e)||1))));return e.toFixed(t)}function Vr(e,t,n,s){const i=Ur(n,s).map(n=>Wr(e,t,n)).filter(Number.isFinite);if(i.length<3)return NaN;const[r,o,a]=i.slice(-3),l=Math.max(1,Math.abs(a));return Math.abs(a-o)<1e-4*l&&Math.abs(o-r)<.01*l?a:NaN}function Ur(e,t){if(e.inf)return[100,1e3,1e4,1e5,1e6].map(t=>t*e.inf);const n=Dr(e.fin);return[.001,1e-4,1e-5,1e-6,1e-7].map(e=>n+t*e*Math.max(1,Math.abs(n)))}function Hr(e,t,n,s){const i=Ur(n,s).map(n=>Wr(e,t,n)).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}function Kr(e,t,n,s,i=0){const r=[];if(!i&&!s.inf){const[e,i]=[Vr(t,n,s,-1),Vr(t,n,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 Cr(`from the left it goes to ${+e.toPrecision(6)}, from the right to ${+i.toPrecision(6)}`)}if(!s.inf&&!St.complex)for(const e of i?[i]:[-1,1])if(Ur(s,e).every(e=>Rr(t,n,e)))throw new Cr(`it has no real values ${e<0?"to the left":"to the right"} of ${+Dr(s.fin).toPrecision(6)}`);const o=new Qr(e,n,s,i,r);let a;try{if(a=o.of(fn(function(e,t){const{v:n,a:s,side:i}=e,r=s.inf?s.inf:i;if(!r)return t;let o=t;const a=t=>{if(!it(t))return t;const i=t.args.map(a),l=i.some((e,n)=>e!==t.args[n])?nt(t.op,i):t;if("abs"!==l.op||!bn(l.args[0]).has(n))return l;const u=Hr(l.args[0],n,s,r);if(!u)return l;const c=u>0?l.args[0]:fn(nt("neg",[l.args[0]])),f=fn(Jr(o,l,c));return e.step("limit.abs","Absolute value",o,f,{inside:l.args[0],abs:l,to:c,sign:u>0?"positive":"negative",where:s.inf?"that far out":"on this side"}),o=f,c};return a(t),o}(o,t)),0),a.bnd)throw new Cr("it keeps swinging between bounds")}catch(e){if(e instanceof Cr){const e=(s.inf?[s.inf]:i?[i]:[-1,1]).map(e=>Vr(t,n,s,e));if(e.every(Number.isFinite)&&e.every(t=>Math.abs(t-e[0])<1e-6*Math.max(1,Math.abs(t))))throw new dt(`numbers near the point settle on ${+e[0].toPrecision(6)}: not answered`)}throw e}return function(e,t,n,s,i){const r=s?[s]:n.inf?[-1]:[-1,1];for(const s of r){const r=Ur(n,s).map(n=>Wr(e,t,n)).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 dt(`numbers near the point don't go to ${i.inf>0?"∞":"-∞"}: not answered`)}else{const e=Dr(i.fin);if(!Number.isFinite(e))continue;const t=r.map(t=>Math.abs(t-e)),n=Math.abs(r[r.length-1]-r[r.length-2]),s=t.every((e,n)=>0===n||e<t[n-1])&&t[t.length-1]<.5*t[0]&&t[t.length-1]<10*n;if(t[t.length-1]>.01*Math.max(1,Math.abs(e))&&!s)throw new dt(`numbers near the point go to ${o.toPrecision(6)}, not ${e.toPrecision(6)}: not answered`)}}}(t,n,s,i,a),{value:a,steps:r}}function Jr(e,t,n){return e.s===t.s?n:it(e)?nt(e.op,e.args.map(e=>Jr(e,t,n))):e}class Qr{constructor(e,t,n,s,i){Object.assign(this,{cas:e,v:t,a:n,side:s,steps:i}),this.point=n.inf?n.inf>0?Fr:Ge("-∞"):n.fin}step(e,t,n,s,i={}){this.steps.push(this.cas.step(e,t,["limit"],n,s,{v:Ge(this.v),a:this.point,...i}))}of(e,t){if(t>8)throw new dt("this limit went too deep");const{v:n,a:s}=this;if(!bn(e).has(n))return zr(e);if("sym"===e.type)return s.inf?Br(s.inf):zr(s.fin);if(s.inf){const i=Di(Bi(cn(e),n));if(i&&i.length>1){const r=i.length-1,o=i[r].sign*(r%2&&s.inf<0?-1:1);return 0===t&&this.step("limit.leading","The leading term",e,fn(nt("*",[mn(Nt(i[r])),nt("^",[Ge(n),Xe(String(r))])])),{f:e,lead:fn(nt("*",[mn(Nt(i[r])),nt("^",[Ge(n),Xe(String(r))])]))}),Br(o)}}if(!s.inf&&0===t){const t=pr(e,n,s.fin);let i=null;if(Pr(t)&&!this.pole(t)&&!Yr(t))try{i=fn(t)}catch{}if(i&&Pr(i)){const t=this.cas.simplify(i,{steps:!1}).result;return this.step("limit.substitute","Put the point in",e,t,{f:e}),zr(t)}}if(!it(e))return zr(e);switch(e.op){case"+":case"-":return this.sum(e,t);case"neg":return Xr(this.of(e.args[0],t+1));case"*":return this.product(e,t);case"/":return this.quotient(e,e.args[0],e.args[1],t);case"^":return this.power(e,t);default:return this.func(e,t)}}signOf(e){const t=Math.sign(Dr(e));if(!t)throw new dt(`the sign of ${this.cas.format(e)} is not known`);return t}pole(e){return Gr(e).some(e=>it(e)&&jr[e.op]&&this.isExactZero(nt(jr[e.op],[e.args[0]])))}isExactZero(e){try{const t=this.cas.simplify(fn(e),{steps:!1}).result;return st(t)&&0===Number(t.value)}catch{return!1}}sum(e,t){const[n,s]=e.args;let i,r;try{i=this.of(n,t+1),r=this.of(s,t+1)}catch(n){if(!(n instanceof Cr))throw n;const s=sr(cn(e)),i=fn(nt("/",[mn(s.num),mn(s.den)]));if(i.s===e.s)throw n;return this.step("limit.combine","One fraction",e,i,{f:e}),this.of(i,t+1)}const o="-"===e.op?Xr(r):r;if(i.bnd||o.bnd)return i.inf||o.inf?i.inf?i:o:Zr;if(i.fin&&o.fin)return zr(fn(nt("+",[i.fin,o.fin])));if(i.inf&&o.inf&&i.inf!==o.inf){const i="-"===e.op?s:nt("neg",[s]);if([n,s].some(e=>it(e)&&"sqrt"===e.op)||it(s)&&"neg"===s.op&&it(s.args[0])&&"sqrt"===s.args[0].op){const s=fn(nt("/",[nt("-",[nt("^",[n,Xe("2")]),nt("^",[i,Xe("2")])]),nt("+",[n,i])]));return this.step("limit.conjugate","∞ − ∞: the conjugate",e,s,{f:e}),this.of(s,t+1)}const r=sr(cn(e)),o=fn(nt("/",[mn(r.num),mn(r.den)]));if(o.s===e.s)throw new dt("∞ − ∞ that does not become one fraction");return this.step("limit.combine","∞ − ∞: one fraction",e,o,{f:e}),this.of(o,t+1)}return i.inf?i:o}product(e,t){const[n,s]=e.args,i=this.of(n,t+1),r=this.of(s,t+1),o=e=>e.fin&&Math.abs(Dr(e.fin))<1e-300;if(i.bnd||r.bnd){const t=i.bnd?r:i;if(o(t))return this.step("limit.squeeze","The squeeze theorem",e,Xe("0"),{f:e,bounded:i.bnd?n:s}),zr(Xe("0"));if(t.inf)throw new Cr("a growing factor times one that keeps swinging");return Zr}if(i.fin&&r.fin)return zr(fn(nt("*",[i.fin,r.fin])));if(o(i)&&r.inf||i.inf&&o(r)){const[r,a]=o(i)?[n,s]:[s,n],l=e=>e.s.split(" ").length,[u,c]=[fn(nt("/",[Xe("1"),r])),fn(nt("/",[Xe("1"),a]))],f=l(u)<=l(c)?nt("/",[a,u]):nt("/",[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],t+1)}const a=e=>e.inf?e.inf:this.signOf(e.fin);return Br(a(i)*a(r))}quotient(e,t,n,s){const{v:i,a:r}=this;if(r.inf){const t=this.rational(e,s);if(t)return t}const o=this.of(t,s+1),a=this.of(n,s+1),l=e=>e.fin&&Math.abs(Dr(e.fin))<1e-300;if(o.bnd&&a.inf)return this.step("limit.squeeze","The squeeze theorem",e,Xe("0"),{f:e,bounded:t}),zr(Xe("0"));if(o.bnd&&a.fin&&!l(a))return Zr;if(a.bnd)throw new dt("a quotient over something that keeps swinging is not worked out here");if(o.inf&&a.inf&&r.inf){const i=this.dividePower(e,t,n,s);if(i)return i}if(a.fin&&!l(a))return o.fin?zr(this.cas.simplify(fn(nt("/",[o.fin,a.fin])),{steps:!1}).result):Br(o.inf*this.signOf(a.fin));if(a.inf&&o.fin)return zr(Xe("0"));if(l(a)&&!l(o))return this.blowUp(e);const u=l(o)?"0/0":"∞/∞",c=this.rational(e,s);if(c)return c;const f=fn(this.cas.differentiate(t,i)),h=fn(this.cas.differentiate(n,i)),p=fn(nt("/",[f,h]));return this.step("limit.lhopital","L'Hôpital's rule",e,p,{f:e,form:Ge(u)}),this.of(p,s+1)}dividePower(e,t,n,s){const{v:i,a:r}=this;if(!Gr(e).some(e=>it(e)&&(["sqrt","root","sin","cos"].includes(e.op)||"^"===e.op&&!bn(e.args[1]).size&&!Number.isInteger(Dr(e.args[1]))))||this.divided?.has(e.s))return null;const[o,a]=[1e4*r.inf,1e6*r.inf],l=Math.log(Math.abs(Wr(n,i,a)/Wr(n,i,o)))/Math.log(100),u=Math.round(2*l)/2;if(!Number.isFinite(l)||Math.abs(l-u)>.05||u<=0||r.inf<0&&!Number.isInteger(u))return null;const c=nt("^",[Ge(i),Xe(String(u))]),f=e=>{if(it(e)&&("+"===e.op||"-"===e.op))return nt(e.op,e.args.map(f));if(it(e)&&"neg"===e.op)return nt("neg",[f(e.args[0])]);if(it(e)&&"sqrt"===e.op){const t=nt("sqrt",[fn(nt("/",[e.args[0],nt("^",[Ge(i),Xe(String(2*u))])]))]);return r.inf<0&&u%2?nt("neg",[t]):t}return fn(nt("/",[e,c]))},h=nt("/",[fn(f(t)),fn(f(n))]);return(this.divided??=new Set).add(e.s),this.step("limit.divide-power","Divide by the highest power",e,h,{f:e,power:c}),this.quotient(h,h.args[0],h.args[1],s+1)}rational(e,t){const{v:n,a:s}=this,{num:i,den:r}=sr(cn(e)),o=Di(Bi(i,n)),a=Di(Bi(r,n));if(!o||!a||a.length<2)return null;if(s.inf){const[t,i]=[o.length-1,a.length-1],r=fn(nt("/",[nt("*",[mn(Nt(o[t])),nt("^",[Ge(n),Xe(String(t))])]),nt("*",[mn(Nt(a[i])),nt("^",[Ge(n),Xe(String(i))])])]));if(r.s!==e.s&&this.step("limit.leading","The leading terms",e,r,{f:e,lead:r}),t<i)return zr(Xe("0"));if(t===i)return zr(mn(Nt(o[t].div(a[i]))));const l=o[t].div(a[i]).sign*((t-i)%2&&s.inf<0?-1:1);return Br(l)}const l=this.cas.cancel(e,{steps:!1}).result;if(l.s===e.s)return null;this.step("limit.cancel","Cancel the common factor",e,l,{f:e});const u=pr(l,n,s.fin);return Number.isFinite(Dr(u))?zr(this.cas.simplify(fn(u),{steps:!1}).result):this.blowUp(l)}blowUp(e){const{v:t,a:n,side:s}=this,i=(s?[s]:[-1,1]).map(s=>Hr(e,t,n,s));if(i.includes(0))throw new dt("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?Fr:Ge("-∞"),right:i[1]>0?Fr:Ge("-∞")}),new Cr(`from the left it goes to ${i[0]>0?"∞":"-∞"}, from the right to ${i[1]>0?"∞":"-∞"}`);return Br(i[0])}power(e,t){const{v:n}=this,[s,i]=e.args,r=this.of(s,t+1);let o;const a=this.steps.length;try{o=this.of(i,t+1)}catch(n){if(!(n instanceof Cr)||!r.fin||Math.abs(Dr(r.fin)-1)>1e-12)throw n;return this.steps.length=a,this.expLog(e,s,i,"1^∞",t)}if(r.bnd||o.bnd)throw new dt("a power of something that keeps swinging is not worked out here");const l=e=>e.fin?Dr(e.fin):e.inf*(1/0),u=l(r),c=l(o);if(r.fin&&o.fin){if(Math.abs(u)<1e-300&&c<0)return this.blowUp(e);if(!(Math.abs(u)<1e-300&&Math.abs(c)<1e-300))return zr(this.cas.simplify(fn(nt("^",[r.fin,o.fin])),{steps:!1}).result)}const f=!bn(s).has(n),h=!bn(i).has(n),p=r.fin&&Math.abs(u)<1e-300,d=r.fin&&Math.abs(u-1)<1e-12;if(r.fin&&o.inf&&(!d||f)){if(d)return zr(Xe("1"));if(p){if(o.inf<0){if(f)throw new Cr("0 to a negative power has no value");return Br(1)}return zr(Xe("0"))}if(u>1)return o.inf>0?Br(1):zr(Xe("0"));if(u>0)return o.inf>0?zr(Xe("0")):Br(1);throw new Cr("a negative number to a growing power swings between signs")}if(r.inf<0&&!h)throw new dt("a power of something going to -∞ is not worked out here");if(r.inf&&(h||o.fin&&Math.abs(c)>1e-300||o.inf)){if(c>0)return Br(r.inf>0?1:h&&Number.isInteger(c)&&c%2?-1:1);if(c<0)return zr(Xe("0"))}if(h&&p&&c>0)return zr(Xe("0"));const m=d?"1^∞":p?"0^0":r.inf&&o.fin?"∞^0":null;if(!m)throw new dt("a power of this shape is not worked out here");return this.expLog(e,s,i,m,t)}expLog(e,t,n,s,i){const r=fn(nt("*",[n,nt("ln",[t])]));this.step("limit.exp-log","Take logs",e,nt("^",[Ge("e"),r]),{f:e,form:Ge(s)});const o=this.of(r,i+1);if(o.bnd)throw new dt("a power of something that keeps swinging is not worked out here");return o.inf?o.inf>0?Br(1):zr(Xe("0")):zr(this.cas.simplify(fn(nt("^",[Ge("e"),o.fin])),{steps:!1}).result)}func(e,t){const n=e.op,s=e.args;if(1!==s.length){if("log"===n&&!bn(s[0]).has(this.v)){const e=this.of(s[1],t+1);if(e.fin){const t=fn(nt("log",[s[0],e.fin]));if(Number.isFinite(Dr(t)))return zr(this.cas.simplify(t,{steps:!1}).result)}return this.of(fn(nt("/",[nt("ln",[s[1]]),nt("ln",[s[0]])])),t+1)}throw new dt(`a limit of ${n} is not worked out here`)}let i;try{i=this.of(s[0],t+1)}catch(e){if(e instanceof Cr&&("sin"===n||"cos"===n))return Zr;throw e}if(i.bnd){if("sin"===n||"cos"===n||"arctan"===n||"abs"===n)return Zr;throw new dt(`${n} of something that keeps swinging is not worked out here`)}if(i.fin){if(jr[n]&&this.isExactZero(nt(jr[n],[i.fin])))return this.blowUp(e);const t=fn(nt(n,[i.fin]));if(Pr(t))return zr(this.cas.simplify(t,{steps:!1}).result);if("ln"===n&&Math.abs(Dr(i.fin))<1e-300)return Br(-1);if(["tan","sec","csc","cot"].includes(n))return this.blowUp(e);throw new dt(`${n} has no value at the limit of its argument`)}const r=i.inf;switch(n){case"sqrt":case"ln":case"cosh":if(r<0&&"cosh"!==n)throw new Cr(`${n} has no value as its argument goes to -∞`);return Br(1);case"abs":return Br(1);case"sinh":return Br(r);case"tanh":return zr(Xe(String(r)));case"arctan":return zr(fn(nt("/",[r>0?Ge("pi"):nt("neg",[Ge("pi")]),Xe("2")])));case"arccot":return zr(r>0?Xe("0"):Ge("pi"));case"arcsec":case"arccsc":return zr("arcsec"===n?fn(nt("/",[Ge("pi"),Xe("2")])):Xe("0"));case"sin":case"cos":return Zr;case"tan":case"sec":case"csc":case"cot":throw new Cr(`${n} keeps swinging as its argument grows`);default:throw new dt(`a limit of ${n} at ∞ is not worked out here`)}}}const Yr=e=>Gr(e).some(e=>it(e)&&("/"===e.op&&Math.abs(Dr(e.args[1]))<1e-300||"^"===e.op&&Dr(e.args[1])<0&&Math.abs(Dr(e.args[0]))<1e-300)),Gr=(e,t=[])=>(t.push(e),it(e)&&e.args.forEach(e=>Gr(e,t)),t),Xr=e=>e.bnd?e:e.inf?Br(-e.inf):zr(fn(nt("neg",[e.fin])));function eo(e){if(!it(e)||"lim"!==e.op)return null;const[t,n,s,i]=e.args;if(it(n)&&"→"===n.op)return{f:t,v:n.args[0].token,to:n.args[1],side:0};if("sym"===n?.type&&s){const e="r"===i?.token?1:"l"===i?.token?-1:0;return{f:t,v:n.token,to:s,side:e}}return null}function to(e){return"sym"!==e.type||"∞"!==e.token&&"oo"!==e.token&&"infinity"!==e.token?"sym"===e.type&&"-∞"===e.token||it(e)&&"neg"===e.op&&"sym"===e.args[0].type&&"∞"===e.args[0].token?Br(-1):zr(fn(e)):Br(1)}const no=e=>e.inf?e.inf>0?Fr:Ge("-∞"):e.fin,so=new Set(["sin","cos","tan","sec","csc","cot"]),io=()=>Xe("2");function ro(e,t){if(!oo(t))return[];let n,s;try{const e=lo(t);n=new Map;s=sr(cn(uo(e,n)))}catch{return[]}const i=[],r=ao(t);for(const t of["sin","cos","none"])try{const o=[zi(s.num),zi(s.den)],a="none"===t?o[0]:co(s.num,n,t),l="none"===t?o[1]:co(s.den,n,t);if(!a||!l)continue;const u=mn(a).s!==mn(o[0]).s||mn(l).s!==mn(o[1]).s,c=[{p:po(a,l),how:u?"pythagorean":r?"expand-double":"sin-cos"}],f=[fo(a,n),fo(l,n)];f[0]&&f[1]&&c.push({p:po(f[0],f[1]),how:"double-angle"});for(const t of c)i.push({node:go(e,mo(t.p,n)),how:t.how})}catch{}return i}const oo=e=>it(e)&&(so.has(e.op)||e.args.some(oo)),ao=e=>it(e)&&(("sin"===e.op||"cos"===e.op)&&it(e.args[0])&&"*"===e.args[0].op&&st(e.args[0].args[0])&&2===Number(e.args[0].args[0].value)||e.args.some(ao));function lo(e){if(!it(e))return e;const t=e.args.map(lo),[n]=t,s=e=>nt("sin",[e]),i=e=>nt("cos",[e]),r=e=>it(e)&&"*"===e.op&&st(e.args[0])&&2===Number(e.args[0].value)?2===e.args.length?e.args[1]:nt("*",e.args.slice(1)):null;switch(e.op){case"tan":return nt("/",[s(n),i(n)]);case"sec":return nt("/",[Xe("1"),i(n)]);case"csc":return nt("/",[Xe("1"),s(n)]);case"cot":return nt("/",[i(n),s(n)]);case"sin":{const e=r(n);return e?nt("*",[nt("*",[io(),s(e)]),i(e)]):s(n)}case"cos":{const e=r(n);return e?nt("-",[nt("^",[i(e),io()]),nt("^",[s(e),io()])]):i(n)}default:return nt(e.op,t)}}function uo(e,t){if(!it(e))return e;if(("sin"===e.op||"cos"===e.op)&&!oo(e.args[0])){const n=e.args[0];t.has(n.s)||t.set(n.s,{u:n,s:`$s${t.size}`,c:`$c${t.size}`});const s=t.get(n.s);return Ge("sin"===e.op?s.s:s.c)}return nt(e.op,e.args.map(e=>uo(e,t)))}function co(e,t,n){let s=zi(e);for(const{s:e,c:i}of t.values()){const[t,r]="sin"===n?[e,i]:[i,e],o=Bi(s,t);if(!o)return null;const a=[];for(const[e,n]of o){const s=Math.floor(e/2),i=[n];e%2&&i.push(cn(Ge(t))),s&&i.push(cn(nt("^",[nt("-",[Xe("1"),nt("^",[Ge(r),io()])]),Xe(String(s))]))),a.push(Ut(i))}if(s=zi(_t(a)),yn(s).length>200)return null}return s}function fo(e,t){let n=zi(e);for(const{u:e,s:s,c:i}of t.values()){const t=nt("sin",[nt("*",[io(),e])]),r=nt("cos",[nt("*",[io(),e])]),o=[];for(const e of yn(n)){const n=mn(e),a=ho(n,s),l=ho(n,i);if(a+l===0){o.push(e);continue}if(a+l!==2)return null;const u=pr(pr(n,s,Xe("1")),i,Xe("1")),c=nt("/",1===a?[t,io()]:2===a?[nt("-",[Xe("1"),r]),io()]:[nt("+",[Xe("1"),r]),io()]);o.push(cn(nt("*",[u,c])))}n=zi(_t(o))}return n}function ho(e,t){const n=Bi(cn(e),t);return n?Math.max(0,...n.keys()):0}function po(e,t){const n=cn(nt("/",[mn(e),mn(t)])),s=ir(n);return s?tr(s):mn(n)}function mo(e,t){let n=e;for(const{u:e,s:s,c:i}of t.values())n=pr(pr(n,s,nt("sin",[e])),i,nt("cos",[e]));return fn(n)}function go(e,t){const n=e=>{if(!it(e))return e;const t=e.args.map(n);if("/"===e.op&&st(t[0])){const e=t[1],[n,s]=it(e)&&"^"===e.op&&st(e.args[1])?[e.args[0],e.args[1]]:[e,null],i=it(n)&&{cos:"sec",sin:"csc"}[n.op];if(i){const e=nt(i,n.args),r=s?nt("^",[e,s]):e;return 1===Number(t[0].value)?r:nt("*",[t[0],r])}}return nt(e.op,t)},s=ui(fn(n(t)),e.set.view("simplify"),{format:e.format}).node;try{const{num:e,den:t}=sr(cn(s)),n=fn(nt("/",[mn(e),mn(t)]));return n.s.split(" ").length<s.s.split(" ").length?n:s}catch{return s}}const vo=(e,t)=>nt("int",[e,"string"==typeof t?Ge(t):t]);function bo(e,t,n,s=0){if(s>6)throw new dt("integration went too deep");const i=[],r=e.set.view("integrate"),o=ui(t,e.set.view("simplify"),{format:e.format});i.push(...yo(o.steps,e=>fn(vo(e,n))));let a=fn(vo(o.node,n));for(let t=0;t<40;t++){const t=ui(a,r,{format:e.format});i.push(...t.steps),a=t.node;const n=ft(a,"pre").find(({node:e})=>{return it(t=e)&&"int"===t.op&&2===t.args.length;var t});if(!n)return{node:a,steps:i};const o=wo(e,n.node,s);if(!o)throw new dt(`no rule for ∫ ${e.format(n.node.args[0])} d${n.node.args[1].token}`);const l=a;i.push(...yo(o.steps,e=>fn(pt(l,n.path,e)))),a=fn(pt(a,n.path,o.node))}throw new dt("integration did not finish")}function yo(e,t){return e.map(e=>{const n=t(rt(e.from)).s,s=t(rt(e.to)).s;return n===e.from&&s===e.to?e:{...e,from:n,to:s,path:null}})}function wo(e,t,n){const[s,i]=t.args,r=i.token,o=cn(s),a=function(e,t){const{num:n,den:s}=sr(e),i=Ki(n),r=Ki(s),o=i.coef.div(r.coef);if(o.isOne||!Fi(e,t))return null;const a=Ut([...i.factors.map(e=>Kt(e.base,e.exp)),...r.factors.map(e=>Kt(e.base,sn(e.exp)))]);return{c:o,rest:a}}(o,r);if(a){const n=nt("*",[mn(Nt(a.c)),vo(mn(a.rest),i)]);return{node:n,steps:[e.step("integrate.constant","Take the number out",["split","minor"],t,n,{c:mn(Nt(a.c))})]}}const l=ir(o),u=l&&tr(l);if(u&&lt(u)<lt(s)&&bn(u).has(r)){const n=vo(u,i);return{node:n,steps:[e.step("integrate.cancel","One fraction",["cancel"],t,n,{})]}}const c=Oo(e,t,o,r,!0);if(c)return c;const f=zi(o);if(mn(f).s!==s.s&&"add"===f.k){const n=vo(mn(f),i);return{node:n,steps:[e.step("integrate.expand","Multiply out",["expand"],t,n,{})]}}const h=function(e,t){const n=new Map;for(const{node:s}of ft(e,"pre")){if(!it(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||!bn(s).has(t))continue;const e=Bi(cn(s),t);if(!e||1!==Math.max(...e.keys()))continue;const i=e.get(1);Fi(i,t)||Lt(i)&&i.q.isZero||n.set(s.s,{node:s,a:i})}}for(const s of n.values()){if(!bn(Io(e,s.node,Ge("§"))).has(t))return s}return null}(s,r);if(h){const i="u"===r?"t":"u",o=Io(s,h.node,Ge(i));if(!bn(o).has(r)){const s=bo(e,fn(o),i,n+1),a=fn(pr(s.node,i,h.node)),l=mn(rn(cn(a),h.a)),u=e=>mn(rn(cn(e),h.a));return{node:l,steps:[e.step("integrate.substitute","Substitute",["substitute"],t,u(fn(vo(fn(o),i))),{u:Ge(i),inside:h.node,a:mn(h.a),v:r,du:xo(e,h.a,r)}),...yo(s.steps,u),e.step("integrate.back","Substitute back",["substitute"],u(s.node),l,{u:Ge(i),inside:h.node})]}}}const p=Oo(e,t,o,r);if(p)return p;const d=Mo(e,t,r);if(d)return d;const m=function(e,t,n,s){if(s>=3)return null;const[i,r]=t.args,o="u"===n?"t":"u",a=new Set;for(const{node:r}of ft(i,"pre")){if(r===i||!it(r)||r.s===i.s||a.has(r.s)||!bn(r).has(n)||["der","int"].includes(r.op))continue;let l,u,c;a.add(r.s);try{l=fn(e.differentiate(r,n))}catch{continue}if(st(l)&&0===Number(l.value))continue;try{u=Io(fn(nt("/",[i,l])),r,Ge(o))}catch{continue}if(bn(u).has(n))continue;try{c=bo(e,fn(u),o,s+1)}catch{continue}const f=fn(pr(c.node,o,r));return{node:f,steps:[e.step("integrate.u-substitution","Substitute",["substitute"],t,fn(vo(u,o)),{u:Ge(o),inside:r,du:l,v:n}),...c.steps,e.step("integrate.back","Substitute back",["substitute"],c.node,f,{u:Ge(o),inside:r})]}}return null}(e,t,r,n);return m||function(e,t,n,s,i){if(i>=6)return null;const r=wn(n),o=r.filter(e=>To(e,s)||!Fi(e,s)),a=r.filter(e=>!o.includes(e));if(1!==a.length)return null;const l=Ut(o),u=a[0],c=mn(u),f=it(c)?c.op:"",h=["ln","arctan","arcsin","arccos","arcsec","arccsc","arccot"];if(!Fi(l,s)&&!h.includes(f))return null;let p,d,m;h.includes(f)?(p=u,d=l):(p=l,d=u);try{m=bo(e,mn(d),s,i+1)}catch{return null}const g=cn(e.differentiate(mn(p),s)),v=Ut([p,cn(m.node)]),b=vo(mn(Ut([g,cn(m.node)])),Ge(s)),y=fn(nt("-",[mn(v),b]));return{node:y,steps:[e.step("integrate.parts","Integration by parts",["parts"],t,y,{u:mn(p),dv:mn(d),V:m.node,du:mn(g),v:s})]}}(e,t,o,r,n)}const xo=(e,t,n)=>Lt(t)&&t.q.isOne?`d${n}`:Lt(t)&&t.q.neg().isOne?`-d${n}`:`${e.format(mn(t))} d${n}`,ko=e=>mn(Nt(e)),qo=e=>Xe(String(e));function $o(e,t){if(!e||!bn(e).has(t))return null;const n=Bi(cn(e),t);if(!n||1!==Math.max(...n.keys()))return null;const s=n.get(1);return!Lt(s)||s.q.isZero?null:{a:s.q,node:e}}function So(e){return it(e)&&"^"===e.op&&st(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 Mo(e,t,n){const[s,i]=t.args,r=wn(cn(s)).map(mn).map(So),o=(e,...t)=>it(e.base)&&t.includes(e.base.op),a=(s,i,r,o={})=>({node:r,steps:[e.step(s,i,["rewrite"],t,r,{v:n,...o})]});if(2===r.length&&r.every(e=>1===e.n)){const e=r.find(e=>it(e.base)&&"^"===e.base.op&&"sym"===e.base.args[0].type&&"e"===e.base.args[0].token),t=r.find(e=>o(e,"sin","cos")),s=e&&$o(e.base.args[1],n),i=t&&$o(t.base.args[0],n);if(s&&i){const[n,r]=[s.a,i.a],o=n.mul(n).add(r.mul(r)),[l,u]=[nt("sin",[i.node]),nt("cos",[i.node])],c="sin"===t.base.op?nt("-",[nt("*",[ko(n),l]),nt("*",[ko(r),u])]):nt("+",[nt("*",[ko(n),u]),nt("*",[ko(r),l])]);return a("integrate.parts-twice","By parts twice",fn(nt("/",[nt("*",[e.base,c]),ko(o)])),{e:e.base,t:t.base})}}if(2===r.length&&r.every(e=>1===e.n&&o(e,"sin","cos")&&$o(e.base.args[0],n))&&r[0].base.args[0].s!==r[1].base.args[0].s){const[e,t]="sin"===r[0].base.op?r:[r[1],r[0]],[n,s]=[e.base.args[0],t.base.args[0]],o=(e,t)=>nt(e,[nt(t,[n,s])]);let l;l="sin"===e.base.op&&"cos"===t.base.op?nt("+",[o("sin","+"),o("sin","-")]):"cos"===e.base.op?nt("+",[o("cos","-"),o("cos","+")]):nt("-",[o("cos","-"),o("cos","+")]);return a("integrate.product-to-sum","Product to sum",fn(vo(nt("/",[l,qo(2)]),i)))}const l=r.find(e=>o(e,"sin")),u=r.find(e=>o(e,"cos")),c=!l||!u||l.base.args[0].s===u.base.args[0].s;if((l||u)&&c&&r.every(e=>e===l||e===u)&&[l,u].every(e=>!e||e.n>=0))for(const[t,s]of[[u,"sin"],[l,"cos"]]){if(!t||t.n<3||t.n%2==0)continue;const o=t.base.args[0],l=(t.n-1)/2,u=r.filter(e=>e!==t).map(e=>nt("^",[e.base,qo(e.n)])),c=[...u,nt("^",[nt("-",[qo(1),nt("^",[nt(s,[o]),qo(2)])]),qo(l)]),nt(t.base.op,[o])].reduce((e,t)=>nt("*",[e,t])),f=fn(vo(c,i)),h=a("integrate.odd-power","An odd power",f,{f:t.base,other:nt(s,[o])});if("sym"!==o.type||o.token!==n)return h;const p="u"===n?"t":"u",d=u.length?r.find(e=>e!==t).n:0;if(2*l+d>100)throw new dt(`a power this high (${t.n+d}) is not integrated here`);const m="sin"===t.base.op?-1:1,g=nt(s,[o]),v=nt("*",[nt("^",[nt("-",[qo(1),nt("^",[Ge(p),qo(2)])]),qo(l)]),nt("^",[Ge(p),qo(d)])]),b=fn(vo(m<0?nt("neg",[v]):v,Ge(p))),y=Bi(zi(cn(v)),p);if(!y)return h;const w=[...y].map(([e,t])=>nt("*",[mn(t),nt("/",[nt("^",[g,qo(e+1)]),qo(e+1)])])).reduce((e,t)=>nt("+",[e,t])),x=fn(m<0?nt("neg",[w]):w);return{node:x,steps:[...h.steps,e.step("integrate.u-substitution","Substitute",["substitute"],f,b,{u:Ge(p),inside:g,du:m<0?nt("neg",[t.base]):t.base,v:n}),e.step("integrate.back","Back to "+n,["substitute"],b,x,{u:Ge(p),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===n){const{base:e,n:t}=r[0],n=e.args[0],s="sec"===e.op?nt("tan",[n]):nt("cot",[n]),o=nt("/",[nt("*",[nt("^",[e,qo(t-2)]),s]),qo(t-1)]),l=nt("*",[nt("/",[qo(t-2),qo(t-1)]),vo(nt("^",[e,qo(t-2)]),i)]);return a("integrate.reduction","Reduction formula",fn(nt("+",["sec"===e.op?o:nt("neg",[o]),l])),{f:e,n:qo(t)})}const f=e=>{if(!it(e)||"sqrt"!==e.op)return null;const t=Bi(cn(e.args[0]),n);if(!t||2!==t.size||!t.has(2)||!t.has(0))return null;const[s,i]=[t.get(2),t.get(0)];return!Lt(s)||!Lt(i)||s.q.sign>=0||i.q.sign<=0?null:{k:s.q.neg(),c:i.q,root:e}},h=Ge(n),p=e=>nt("sqrt",[ko(e)]),d=f(s),m=it(s)&&"/"===s.op&&st(s.args[0])&&1===s.args[0].value?f(s.args[1]):null;if(d||m){const{k:e,c:t,root:n}=d??m,s=nt("arcsin",[nt("*",[h,p(e.div(t))])]);return a("integrate.trig-substitution","A trig substitution",fn(d?nt("+",[nt("/",[nt("*",[h,n]),qo(2)]),nt("*",[nt("/",[ko(t),nt("*",[qo(2),p(e)])]),s])]):nt("/",[s,p(e)])),{x:h,a:fn(p(t.div(e)))})}return null}function Oo(e,t,n,s,i=!1){const{num:r,den:o}=sr(n);if(!Fi(o,s))return null;const a=Di(Bi(r,s)),l=Di(Bi(o,s));if(!a||!l||l.length<2)return null;const u=cn(Ge(s)),c=e=>Pi(e,s);if(a.length>=l.length){const{q:n,r:i}=Hi(a,l),r=vo(mn(_t([c(n),rn(c(i),c(l))])),Ge(s));return{node:r,steps:[e.step("integrate.divide","Divide the polynomials",["divide"],t,r,{})]}}if(i)return null;const{roots:f,rest:h}=Ui(l),p=new Set(f.map(String)).size===f.length,d=3===h.length&&h[1].mul(h[1]).sub(yt.of(4).mul(h[0]).mul(h[2])).sign<0;if(!p||1!==h.length&&!d||!f.length&&!d)return null;const m=(e=>e.length<=1?[yt.ZERO]:e.slice(1).map((e,t)=>e.mul(yt.of(t+1))))(l),g=f.map(e=>Wi(a,e).div(Wi(m,e))),v=f.map((e,t)=>rn(Nt(g[t]),_t([u,Nt(e.neg())])));if(!d){const n=vo(mn(_t(v)),Ge(s));return{node:n,steps:[e.step("integrate.partial-fractions","Partial fractions",["partial-fractions"],t,n,{})]}}let b=a;f.forEach((e,t)=>{b=Eo(b,No(Hi(l,[e.neg(),yt.of(1)]).q,g[t]))});const y=f.reduce((e,t)=>Ao(e,[t.neg(),yt.of(1)]),[yt.of(1)]),{q:w}=Hi(b,y),[x,k]=[w[0]??yt.ZERO,w[1]??yt.ZERO],[q,$,S]=Hi(l,y).q,M=yt.of(4).mul(S).mul(q).sub($.mul($)),O=Pi([q,$,S],s),A=k.div(yt.of(2).mul(S)),N=x.sub(k.mul($).div(yt.of(2).mul(S))),E=nt("sqrt",[ko(M)]),I=nt("*",[ko(A),nt("ln",[nt("abs",[mn(O)])])]),T=nt("*",[nt("/",[nt("*",[qo(2),ko(N)]),E]),nt("arctan",[nt("/",[mn(Pi([$,S.mul(yt.of(2))],s)),E])])]),L=v.length?vo(mn(_t(v)),Ge(s)):qo(0),j=fn(nt("+",[nt("+",[L,I]),T]));return{node:j,steps:[e.step("integrate.complete-square","Complete the square",["partial-fractions"],t,j,{Q:mn(O)})]}}const Ao=(e,t)=>{const n=Array.from({length:e.length+t.length-1},()=>yt.ZERO);return e.forEach((e,s)=>t.forEach((t,i)=>{n[s+i]=n[s+i].add(e.mul(t))})),n},No=(e,t)=>e.map(e=>e.mul(t)),Eo=(e,t)=>Array.from({length:Math.max(e.length,t.length)},(n,s)=>(e[s]??yt.ZERO).sub(t[s]??yt.ZERO));function Io(e,t,n){return e.s===t.s?n:it(e)?nt(e.op,e.args.map(e=>Io(e,t,n))):e}const To=(e,t)=>{const n=Bi(e,t);return Boolean(n)&&[...n.values()].every(e=>!Fi(e,t))&&Math.max(...n.keys())>=1};function Lo(e,t,n,s,i,r){if([s,i].some(e=>to(e).inf))return function(e,t,n,s,i,r){const o=[s,i].map(e=>to(e)),a=e=>e.inf?e.inf*(1/0):Hs(e.fin,{digits:20}).number,[l,u]=o.map(a).sort((e,t)=>e-t);for(const t of r?jo(r,n):[]){let s=[];try{s=e.solve(nt("=",[t,Xe("0")]),n,{steps:!1}).solutions}catch{continue}for(const t of s){const s=Hs(t,{digits:20});if(Number.isFinite(s.number)&&!s.im&&s.number>l&&s.number<u)throw new dt(`the integrand has no value at ${n} = ${e.format(t)}, between the limits: split the integral there`)}}const c=(s,i,r)=>{if(!i.inf)try{const e=fn(pr(t,n,s));if(Number.isFinite(Hs(e,{digits:15}).number))return e}catch{}const o=e.limit(t,n,s,{steps:!1,side:i.inf?void 0:r});if(!o.exists)throw new dt(`the integral diverges: as ${n} → ${e.format(s)}, ${e.format(t)} has no limit (${o.reason})`);if(o.infinite)throw new dt(`the integral diverges: as ${n} → ${e.format(s)}, ${e.format(t)} goes to ${o.text}`);return o.result},f=a(o[0])<a(o[1]),[h,p]=[c(s,o[0],f?"right":"left"),c(i,o[1],f?"left":"right")],d=fn(nt("-",[p,h])),m=nt("-",[p,h]);return{value:d,shown:m,step:e.step("integrate.improper","Limits at the ends",["evaluate"],t,m,{a:s,b:i,F:t,v:n})}}(e,t,n,s,i,r);if(r&&!bn(s).size&&!bn(i).size){const o=Hs(s,{digits:20}).number,a=Hs(i,{digits:20}).number,l=[...bn(r)].filter(e=>e!==n);if(!l.length){const[s,i]=o<=a?[o,a]:[a,o];for(const o of jo(r,n)){let r=[];try{r=e.solve(nt("=",[o,Xe("0")]),n,{steps:!1}).solutions}catch{continue}for(const o of r){const r=Hs(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 dt(`the integrand has no value at ${n} = ${e.format(o)}, between the limits, so F(b) - F(a) would be wrong`);let a=NaN;try{a=Hs(fn(pr(t,n,o)),{digits:15}).number}catch{}if(!Number.isFinite(a))throw new dt(`the integral diverges at ${n} = ${e.format(o)}: F has no value at that limit`)}}}for(let e=0;!l.length&&e<=64;e++){const t=o+(a-o)*(e+.5)/65;try{const e=Hs(pr(r,n,Xe(t.toFixed(15))),{digits:15}).number;if(!Number.isFinite(e))throw new dt("not finite")}catch(e){throw new dt(`the integrand has no value at ${n} = ${t.toPrecision(6)}, between the limits, so F(b) - F(a) would be wrong`)}}}const o=e=>fn(pr(t,n,e)),a=fn(nt("-",[o(i),o(s)])),l=nt("-",[o(i),o(s)]);return{value:a,shown:l,step:e.step("integrate.evaluate","Between the limits",["evaluate"],t,l,{a:s,b:i,F:t,v:n})}}function jo(e,t){const n=[],s={tan:"cos",sec:"cos",csc:"sin",cot:"sin"};return ft(e,"pre").forEach(({node:e})=>{if(!it(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&&it(e.args[1])&&"neg"===e.args[1].op?i=e.args[0]:s[e.op]&&(i=nt(s[e.op],[e.args[0]])),i&&bn(i).has(t)&&!n.some(e=>e.s===i.s)&&n.push(i)}),n}const Co={"=":1,"≠":1,"<":1,">":1,"≤":1,"≥":1,"+":2,"-":2,"±":2,"*":3,"/":3,neg:4,pm:4,"^":5},zo={pi:"π","≤":"≤","≥":"≥"};function Zo(e){return Ro(e).text}function Bo(e,t,n=!1){return e.prec<t||n&&e.prec===t?`(${e.text})`:e.text}const Fo=e=>"op"===e.type?e.op:null,Do=e=>e.text.startsWith("-"),Po={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]};function Ro(e){if("num"===e.type)return{text:e.token,prec:e.token.startsWith("-")?4:9};if("sym"===e.type)return{text:zo[e.token]??e.token,prec:9};const t=e.args.map(Ro),n=Co[e.op];switch(e.op){case"+":case"-":case"±":{const s="+"===e.op&&["+","-"].includes(Fo(e.args[1])),i=Do(t[1])?`(${t[1].text})`:s?t[1].text:Bo(t[1],n,!0);return{text:`${Bo(t[0],n)} ${"±"===e.op?"±":e.op} ${i}`,prec:n}}case"*":{const s=Bo(t[0],n),i=Do(t[1])?`(${t[1].text})`:"*"===Fo(e.args[1])?t[1].text:Bo(t[1],n,!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:n}}case"/":return{text:`${Bo(t[0],n)}/${Bo(t[1],n,!0)}`,prec:n};case"^":return{text:`${Bo(t[0],n+1)}^${Bo(t[1],n)}`,prec:n};case"neg":return{text:`-${Bo(t[0],3)}`,prec:4};case"pm":return{text:`±${Bo(t[0],4)}`,prec:4};case"!":return{text:`${Bo(t[0],9)}!`,prec:6};case"abs":return{text:`|${t[0].text}|`,prec:9};case"root":return{text:`root(${t[0].text}, ${t[1].text})`,prec:9};case"der":return"op"===e.args[1].type&&"="===e.args[1].op?{text:`d/d${t[1].text.split(" = ")[0]} (${t[0].text}) at ${t[1].text}`,prec:1}:{text:`d/d${t[1].text} (${t[0].text})`,prec:6};case"int":return{text:4===t.length?`∫ from ${t[2].text} to ${t[3].text} of ${t[0].text} d${t[1].text}`:`∫ ${t[0].text} d${t[1].text}`,prec:1};case"|":return{text:`${t[0].text} or ${t[1].text}`,prec:0};case"_":return{text:`${Bo(t[0],9)}_${t[1].prec>=9&&!/\s/.test(t[1].text)?t[1].text:`(${t[1].text})`}`,prec:9};case"()":case"[]":case"{}":case"(]":case"[)":return{text:`${Po[e.op][0]}${t.map(e=>e.text).join(", ")}${Po[e.op][1]}`,prec:9};case"&":return{text:`${t[0].text} and ${t[1].text}`,prec:0};default:return void 0!==n?{text:`${Bo(t[0],n)} ${e.op} ${Bo(t[1],n,!0)}`,prec:n}:{text:`${e.op.replace(/^\\:?/,"")}(${t.map(e=>e.text).join(", ")})`,prec:9}}}const Wo=['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'],_o=['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'],Vo=new Set(["<",">","≤","≥"]),Uo=new Set(["sin","cos","tan","sec","csc","cot"]),Ho=new Set(["arcsin","arccos","arctan","arcsec","arccsc","arccot"]),Ko={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."},Jo=["normal","rewrite","simplify","expand","factor","cancel","diff","differentiate","integrate","solve","solveSystem","substitute","approximate","equivalent","limit"];class Qo{constructor(e,t,n,s,i){this.set=e,this.messages=t,this.format=n,this.read=s,this.complex=i;for(const e of Jo){const t=Qo.prototype[e];this[e]=(...e)=>Mt(i,()=>t.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 ot(e);if("string"!=typeof e)throw new dt("expected an expression");if(this.read){const t=this.read(e);return Array.isArray(t)?ot(t):"string"==typeof t?rt(t):t}return rt(e)}atPoints(e){if(!e||!it(e)||!e.s.includes("= der"))return e;const t=e.args.map(e=>this.atPoints(e)),[n,s]=t;if("der"===e.op&&it(s)&&"="===s.op&&"sym"===s.args[0].type){const e=s.args[0].token;return this.substitute(this.diff(n,e).result,{[e]:s.args[1].s}).result}return nt(e.op,t)}step(e,t,n,s,i,r={},o=e){return function(e,t,n,s,i,r,o,a,l=[]){const u=(r??"").replace(/\{(\w+)\}/g,(e,t)=>{const n=o?.[t];return void 0===n?e:"string"==typeof n?n:a(n)});return{id:e,name:t,tags:n,from:s.s,to:i.s,path:l,before:s.s,after:i.s,explanation:u}}(e,t,n,s,i,this.messages[o]??this.messages[e]??"",r,this.format)}select(e,t,n=null){const s=function(e){if(!1===e)return null;if(void 0===e||!0===e)return{show:"all",hide:Ii.normal,explain:!0,detail:"normal"};if("string"==typeof e){if(!Ii[e])throw new Error(`steps: "${e}" is not one of ${Object.keys(Ii).join(", ")}`);return{show:"all",hide:Ii[e],explain:!0,detail:e}}const t=e.detail??"normal";if(!Ii[t])throw new Error(`steps.detail: "${t}" is not one of ${Object.keys(Ii).join(", ")}`);return{show:e.show??"all",hide:[...Ii[t],...e.hide??[]],explain:e.explain??!0,detail:t}}(t);return"full"===s?.detail&&(s.split=e=>this.splitTidy(e)),Ei(function(e,t){if(!t)return[];e="full"===t.detail?t.split?e.flatMap(t.split):e:function(e){const t=[];for(const n of e){const e=t[t.length-1];if(!("d-variable"===n.id&&e&&/^(\S+) \1 der$/.test(n.before??"")&&` ${e.after??""} `.includes(` ${n.before} `))){t.push(n);continue}const s={...e,to:n.to};if(e.after&&(s.after=` ${e.after} `.replace(` ${n.before} `," 1 ").replace(/ 1 \*(?= )/g,"").trim()),e.explanation){const t=n.before.split(" ")[0],i=` The derivative of ${t} is 1.`;s.explanation=e.explanation.endsWith(`the derivative of ${t}.`)?`${e.explanation.slice(0,-1)}, which is 1.`:e.explanation.endsWith(i)||e.explanation.endsWith(`the derivative of ${t}, which is 1.`)?e.explanation:`${e.explanation}${i}`}t[t.length-1]=s}return t}(e);const n=[];let s=null;for(const i of e){if(!Ti(i,t.show)||Ti(i,t.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===t.explain||!1!==t.explain&&Ti(i,t.explain)||delete e.explanation,n.push(e)}if(s&&n.length){const t=n[n.length-1];t.to=e[e.length-1].to,t.also=[...t.also??[],...s.ids]}return n}(e,s),n)}splitTidy(e){if(["solve.move","solve.divide","solve.multiply"].includes(e.id))return this.splitBothSides(e);if("normal"!==e.id)return[e];let t,n;try{t=rt(e.from),n=xs(t)}catch{return[e]}return n.s===t.s||n.s===e.to?[e]:[this.step("normal.numbers","Work out the numbers",["arithmetic"],t,n),{...this.step("normal.collect","Collect like terms",["tidy"],n,rt(e.to),{},ft(n,"pre").some(({node:e})=>it(e)&&"*"===e.op&&e.args.some(e=>it(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 t,n;try{t=rt(e.from),n=rt(e.to)}catch{return[e]}const s=e.path??[],i=(e,t)=>t.reduce((e,t)=>e?.args?.[t],e),r=i(t,s),o=i(n,s);if(!r||!o||"="!==r.op||"="!==o.op)return[e];const a=e=>s.length?pt(t,s,e):e,[l,u]=r.args,[c,f]=o.args,h=[];let p=t;const d=(e,t,n,i)=>{const r=a(t);h.push({...this.step(e,"The same on both sides",["move"],p,r,{t:i}),path:s}),p=a(n),h.push({...this.step("solve.each-side","Work out each side",["arithmetic"],r,p),path:s})};if("solve.move"===e.id){const t=cn(nt("-",[l,c]));if(zt(t)!==zt(cn(nt("-",[u,f])))||Lt(t)&&t.q.isZero)return[e];const n=yn(t).sort((e,t)=>Number(bn(t).size>0)-Number(bn(e).size>0));let s=l,i=u;n.forEach((e,t)=>{const r=Lt(e)?e.q.sign>0:!mn(e).s.endsWith(" neg"),a=mn(r?e:sn(e)),l=nt("=",[nt(r?"-":"+",[s,a]),nt(r?"-":"+",[i,a])]),u=t===n.length-1?o:nt("=",[fn(l.args[0]),fn(l.args[1])]);d(r?"solve.both-subtract":"solve.both-add",l,u,a),[s,i]=u.args})}else{const t=cn(nt("/",[l,c])),n=e=>{const t=cn(e);return Lt(t)&&t.q.isZero};if(!(!(!n(u)||!n(f))||!n(f)&&zt(t)===zt(cn(nt("/",[u,f]))))||bn(t).size||Lt(t)&&t.q.isZero)return[e];const s=Lt(t)&&!t.q.isInteger&&(1n===t.q.n||-1n===t.q.n),i=mn(s?rn(cn(Ge("1")),t):t);d(s?"solve.both-multiply":"solve.both-divide",nt("=",[nt(s?"*":"/",[l,i]),nt(s?"*":"/",[u,i])]),o,i)}return h.length&&h.at(-1).to===e.to?h:[e]}result(e,t,n,s={},i=null){let r=e;if(n.approximate&&r){r=Qs(r,{digits:"number"==typeof n.approximate?n.approximate:15})}return{result:r,text:r?this.format(r):"",steps:this.select(t,n.steps,i),...s}}variable(e,t){if(t&&!/^\\?[A-Za-z\u0370-\u03FF][A-Za-z0-9_\u0370-\u03FF′]*$/.test(t))throw new dt(`"${t}" is not a variable name; for a derivative at a point write der(f, x = a)`);if(t)return t;const n=[...bn(e)];return 1===n.length?n[0]:n.includes("x")?"x":n[0]??"x"}tidyStep(e,t){return e.s===t.s?[]:[this.step("normal","Work out and collect",["tidy","arithmetic"],e,t)]}normal(e){return fn(this.node(e))}rewrite(e,t,n={}){const s=this.node(e),i=this.set.view(t);if(!i.size)throw new dt(`no rules in mode "${t}" (modes: ${this.set.modes().join(", ")})`);const r=ui(s,i,{format:this.format,order:n.order,variable:n.variable});return this.result(r.node,[...this.tidyStep(s,fn(s)),...r.steps],n,{},s)}simplify(e,t={}){const n=this.node(e),s=[...this.tidyStep(n,fn(n))],i=ui(n,this.set.view("simplify"),{format:this.format});s.push(...i.steps);let r=i.node;const o=cn(r),a=[],l=0===bn(r).size,u=l?null:ir(o);u&&a.push({node:tr(u),id:"simplify.cancel",name:"Cancel"});const c=ui(mn(zi(o)),this.set.view("simplify"),{format:this.format});a.push({node:c.node,id:"simplify.expand",name:"Multiply out"}),"add"!==o.k||l||a.push({node:tr(Ki(o)),id:"simplify.factor",name:"Factor"});const f=e=>ft(e,"pre").some(({node:e})=>it(e)&&Uo.has(e.op)&&ft(e.args[0],"pre").some(({node:e})=>it(e)&&Ho.has(e.op)));for(const e of ro(this,r))a.push({node:e.node,id:"simplify.trig",wording:`simplify.trig.${e.how}`,name:"Trigonometric identities",prefer:f(r)&&!f(e.node)});let h=!1;for(const e of a)h&&"simplify.trig"===e.id&&!e.prefer||(e.prefer&&(h=!0),(lt(e.node)<lt(r)||e.prefer)&&(s.push(this.step(e.id,e.name,["shorter"],r,e.node,{},e.wording)),r=e.node));return this.result(r,s,t,{},n)}expand(e,t={}){const n=this.node(e),s=mn(zi(cn(n)));return this.result(s,n.s===s.s?[]:[this.step("expand","Multiply out",["expand"],n,s)],t,{},n)}factor(e,t={}){const n=this.node(e),s=Ki(cn(n)),i=tr(s),r=[],o=s.notes.find(e=>"factor.common"===e.id);return i.s!==fn(n).s&&r.push(this.step(o?"factor.common":"factor","Factor",["factor"],n,i,o?{common:mn(o.values.common)}:{})),this.result(i,r,t,{},n)}cancel(e,t={}){const n=this.node(e),s=cn(n),i=ir(s);if(!i)return this.result(fn(n),this.tidyStep(n,fn(n)),t,{},n);const r=tr(i),o=sr(s),a=nt("/",[mn(o.num),mn(o.den)]),l=[];return"/"===n.op&&a.s===fn(n).s||l.push(this.step("together","One fraction",["together"],n,a)),r.s!==a.s&&l.push(this.step("cancel","Cancel",["cancel"],a,r,{canceled:i.canceled.length?i.canceled.map(e=>this.format(mn(e))).join(", "):"numbers"})),this.result(r,l,t,{},n)}diff(e,t,n={}){const s=this.node(e),i=this.variable(s,t),r="string"==typeof n.steps?n.steps:n.steps?.detail,o=pi(s),a={diff:this.set.view("differentiate"),simp:this.set.view("simplify")};let l=o;const u=[];for(let e=0;e<(n.order??1);e++){const e=vi(nt("der",[l,Ge(i)]),a.diff,{fold:"full"===r?null:a,format:this.format}),t=vi(e.node,a.simp,{format:this.format,order:"post",maxSteps:40}),n=fn(t.node),s=ui(n,a.simp,{format:this.format});u.push(...e.steps,...t.steps,...this.tidyStep(t.node,n),...s.steps),l=s.node}const c=cn(l),f=bn(l).size?ir(c):null,h=[f&&{node:tr(f),id:"simplify.cancel",name:"Cancel"},{node:mn(zi(c)),id:"simplify.expand",name:"Multiply out"}].find(e=>e&&lt(e.node)<lt(l));return h&&(u.push(this.step(h.id,h.name,["shorter"],l,h.node)),l=h.node),this.result(l,u,n,{variable:i},nt("der",[s,Ge(i)]))}differentiate(e,t){const n=ui(nt("der",[e,Ge(t)]),this.set.view("differentiate"),{format:this.format,order:"pre"});return ui(n.node,this.set.view("simplify"),{format:this.format}).node}integrate(e,t,n={}){t&&"object"==typeof t&&(n=t,t=void 0);let s=this.node(e);const i=s,r=e=>void 0===e?null:this.node("number"==typeof e?String(e):e);let o=r(n.from),a=r(n.to);if(it(s)&&"int"===s.op){const[e,n,i,r]=s.args;t=n.token,i&&r&&(o=i,a=r),s=e}const l=this.variable(s,t),u=bo(this,s,l),c=ui(u.node,this.set.view("simplify"),{format:this.format}),f=[...u.steps,...c.steps];if(o&&a){const e=Lo(this,c.node,l,o,a,s);f.push(e.step);const t=ui(e.value,this.set.view("simplify"),{format:this.format});return f.push(...this.tidyStep(e.shown,e.value),...t.steps),this.result(t.node,f,n,{antiderivative:c.node,variable:l},it(i)&&"int"===i.op?i:null)}let h=c.node;if(n.constant){const e=new Set([...bn(s),l]);h=nt("+",[h,Ge(!0===n.constant?["C","c","K"].find(t=>!e.has(t))??"C":String(n.constant))])}return this.result(h,f,n,{variable:l},it(i)&&"int"===i.op?i:nt("int",[i,Ge(l)]))}solve(e,t,n={}){const s=this.node(e),i=this.variable(s,t);if(it(s)&&Vo.has(s.op))return this.inequality(s,i,n);const r=lr(this,s,i,n);let o=r.solutions;if(n.approximate){const e="number"==typeof n.approximate?n.approximate:15;o=o.map(t=>Qs(t,{digits:e}))}const a=e=>e.length?e.map(e=>nt("=",[Ge(i),e])).reduce((e,t)=>e?nt("|",[e,t]):t,null):null,l=(r.base??o).map(e=>nt("=",[Ge(i),e])),u=a(r.base??o),c=Li(r.steps,s,{parse:rt,replaceAt:pt}),f=e=>it(e)&&"|"===e.op?e.args.flatMap(f):[e.s],h=c[c.length-1];if(h&&u&&!n.approximate){let e=null;try{e=rt(h.to)}catch{}if(e&&e.s!==u.s&&f(e).sort().join("\n")===f(u).sort().join("\n"))h.to=u.s;else if(e&&e.s!==u.s){const t=e=>it(e)&&"|"===e.op?e.args.flatMap(t):[e],n=t(e);n.length>=l.length&&n.every(e=>it(e)&&"="===e.op&&e.args[0].s===i)&&c.push(this.step("normal","Work out and collect",["tidy","arithmetic"],e,u))}}const p=r.base?a(o):u;if(r.base&&u&&!n.approximate){const e=c.length?rt(c[c.length-1].to):u;p&&p.s===e.s||c.push(this.step("solve.interval","The answers in the interval",["interval"],e,p??e,{lo:r.interval[0],hi:r.interval[1],v:Ge(i),count:String(o.length)}))}return r.steps=c,{solutions:o,result:p,variable:i,text:r.always?`true for every ${i}`:p?this.format(p):r.unsolved.length?`no exact solution found for ${i}`:"no solution",unsolved:r.unsolved.filter(e=>!e.always),always:r.always,periodic:Boolean(r.periodic),period:r.period??null,...r.interval?{interval:r.interval}:{},steps:this.select(r.steps,n.steps,s)}}inequality(e,t,n){const s=Lr(this,e,t,n),i={solutions:[],variable:t,unsolved:[],always:!1,steps:this.select(s.steps,n.steps,e)};if(!s.pieces)return{...i,pieces:null,intervals:"",result:null,unsolved:[e],text:`no exact solution found for ${t}`};const r=Ge(t),o=1===s.pieces.length&&!s.pieces[0].lo&&!s.pieces[0].hi,a=s.pieces.map(({lo:e,hi:t,loClosed:n,hiClosed:s})=>e&&t&&e.s===t.s?nt("=",[r,e]):e||t?e?t?nt(s?"≤":"<",[nt(n?"≤":"<",[e,r]),t]):nt(n?"≥":">",[r,e]):nt(s?"≤":"<",[r,t]):null).filter(Boolean).reduce((e,t)=>e?nt("|",[e,t]):t,null),l=s.pieces.length?s.pieces.map(({lo:e,hi:t,loClosed:n,hiClosed:s})=>e&&t&&e.s===t.s?`{${this.format(e)}}`:`${n?"[":"("}${e?this.format(e):"-∞"}, ${t?this.format(t):"∞"}${s?"]":")"}`).join(" ∪ "):"∅",u=o?`true for every ${t}`:a?this.format(a):"no solution";return{...i,pieces:s.pieces,intervals:l,result:a,always:o,text:u}}limit(e,t,n,s={}){null==n||"object"!=typeof n||Array.isArray(n)||n.type||(s=n,n=void 0);const i=this.node(e),r=eo(i);if(!r&&ft(i,"pre").some(({node:e})=>eo(e))){let e=i;for(const{node:t,path:n}of ft(i,"post").filter(({node:e})=>eo(e)).reverse()){const s=this.limit(t,void 0,void 0,{steps:!1});if(!s.exists)return s;if(s.infinite)throw new dt("a limit inside an expression that is infinite is not worked out here");e=pt(e,n,s.result)}return{...this.simplify(e,s),exists:!0,infinite:!1}}const o=r?r.f:i,a=r?r.v:this.variable(i,t),l=r?r.to:"number"==typeof n?Xe(String(n)):this.node(n??"0"),u="right"===s.side||"+"===s.side?1:"left"===s.side||"-"===s.side?-1:r?r.side:0;try{const{value:e,steps:t}=Kr(this,o,a,to(l),u);return{...this.result(no(e),Li(t,fn(o),{parse:rt,replaceAt:pt}),s),exists:!0,infinite:Boolean(e.inf)}}catch(e){if(!(e instanceof Cr))throw e;const t={result:null,text:"does not exist",exists:!1,reason:e.message,steps:[]};if(!u&&!to(l).inf){const e=e=>{try{return no(Kr(this,o,a,to(l),e).value)}catch{return null}};t.left=e(-1),t.right=e(1)}return t}}solveSystem(e,t,n={}){const s=e.map(e=>this.node(e)),i=t??[...new Set(s.flatMap(e=>[...bn(e)]))].sort(),r=function(e,t,n){const s=[],i=t.map(t=>{const s=ar(t)?_t([cn(t.args[0]),sn(cn(t.args[1]))]):cn(t),i=n.map(t=>{const n=Bi(s,t);if(!n||Math.max(0,...n.keys())>1)throw new dt(`not linear in ${t}`);const i=n.get(1)??Nt(yt.ZERO);if(!Lt(i))throw new dt(`the coefficient of ${t} must be a number (it is ${e.format(mn(i))})`);return i.q});let r=s;for(let e=0;e<n.length;e++)r=_t([r,Ut([Nt(i[e].neg()),cn(Ge(n[e]))])]);for(const e of n)if(Fi(r,e))throw new dt(`not linear in ${e}`);return{coeffs:i,rhs:sn(r)}}),r=()=>i.map(e=>rr(mn(_t(e.coeffs.map((e,t)=>Ut([Nt(e),cn(Ge(n[t]))])))),mn(e.rhs))).reduce((e,t)=>e?nt("&",[e,t]):t,null),o=e=>Nr[e]??`${e+1}th`,a=(t,n,i,o)=>{const a=r();a.s!==i.s&&s.push(e.step(t,n,["eliminate"],i,a,o))};let l=0;const u=[];for(let e=0;e<n.length&&l<i.length;e++){const t=i.findIndex((t,n)=>n>=l&&!t.coeffs[e].isZero);if(t<0)continue;const s=Ge(n[e]);if(t!==l){const e=r();[i[l],i[t]]=[i[t],i[l]],a("system.swap","Swap",e,{v:s,row:o(l),other:o(t)})}const c=i[l],f=c.coeffs[e];if(!f.equals(yt.ONE)){const e=r();c.coeffs=c.coeffs.map(e=>e.div(f)),c.rhs=Ut([Nt(f.inv()),c.rhs]),a("system.scale","Divide",e,{v:s,row:o(l),by:mn(Nt(f))})}for(let t=0;t<i.length;t++){if(t===l||i[t].coeffs[e].isZero)continue;const n=r(),u=i[t].coeffs[e];i[t].coeffs=i[t].coeffs.map((e,t)=>e.sub(u.mul(c.coeffs[t]))),i[t].rhs=_t([i[t].rhs,Ut([Nt(u.neg()),c.rhs])]);const f=u.sign<0?u.neg():u,h=f.equals(yt.ONE);a(`system.${u.sign<0?"add":"subtract"}${h?"":"-multiple"}`,"Eliminate",n,{v:s,row:o(t),from:o(l),k:mn(Nt(f))})}u.push(e),l++}for(const e of i.slice(l))if(!Lt(e.rhs)||!e.rhs.q.isZero)return{solution:null,steps:s,status:"none"};if(u.length<n.length)return{solution:null,steps:s,status:"many"};const c=new Map;return u.forEach((e,t)=>c.set(n[e],mn(i[t].rhs))),{solution:c,steps:s,status:"one"}}(this,s,i),o=r.solution?Object.fromEntries([...r.solution].map(([e,t])=>[e,t])):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:this.select(r.steps,n.steps)}}substitute(e,t,n={}){const s=this.node(e);let i=s;for(const[e,n]of Object.entries(t))i=pr(i,e,"number"==typeof n?this.node(String(n)):this.node(n));const r=this.simplify(i,n),o=[this.step("substitute","Substitute",["substitute"],s,i)];return{...r,steps:[...this.select(o,n.steps),...r.steps]}}defined(e){const t=this.set.view("define");return t.size?ui(e,t,{format:this.format}).node:e}approximate(e,t={}){const n=this.defined(this.node(e));if(bn(n).size&&!t.scope){const e=Qs(fn(n),t);return{result:e,text:this.format(e),number:null,exact:!1}}const s=Hs(n,t);return{result:s.node,text:s.text,number:s.number,re:s.re,im:s.im,exact:s.exact}}equivalent(e,t){const n=this.node(e),s=this.node(t),i=this.defined(nt("-",[n,s])),r=this.simplify(i,{steps:!1}).result;if("num"===r.type&&"0"===r.token)return{equal:!0,how:"exact"};const o=[...bn(i)];if(!o.length)try{return{equal:Math.abs(Hs(i,{digits:30}).number)<1e-25,how:"numeric"}}catch{return{equal:!1,how:"numeric"}}const a=[.31,1.7,2.9,-.83,.57];let l=0;for(let e=0;e<a.length;e++){const t=Object.fromEntries(o.map((t,n)=>[t,String(a[(e+n)%a.length]+n/7)]));let n;try{n=Hs(i,{digits:30,scope:t}).number}catch{continue}if(l++,Math.abs(n)>1e-20)return{equal:!1,how:"numeric"}}return{equal:l>0,how:"numeric"}}modes(){return this.set.modes()}}function Yo(e={}){const t=!1===e.defaults?[]:[...Wo,...e.complex?_o:[]],{specs:n,messages:s}=function(e){si();const t=[],n={};for(const s of e){const e="string"==typeof s?Yn(s):s,i=Array.isArray(e)?e:e?.rules??[];for(const t of(Array.isArray(e)?[]:e?.operators)??[]){if(!t?.symbol)throw new Error("an operator needs a symbol");We(t.symbol)||De({symbol:String(t.symbol),arity:"any"===t.arity?Ze:Number(t.arity),label:t.label})}Object.assign(n,(Array.isArray(e)?null:e?.messages)??{});for(const e of i)t.push(e)}return{specs:t,messages:n}}([...t,...e.rules??[]]),i=Mt(e.complex,()=>ii(n)),r={...Ko};for(const e of Object.keys(s))for(const t of Object.keys(r))t.startsWith(`${e}.`)&&!(t in s)&&delete r[t];return new Qo(i,{...r,...s},e.format??Zo,e.read??null,Boolean(e.complex))}const Go=Symbol.for("inlinemath.expressions"),Xo=new Map,ea={re:"Re",im:"Im",conj:"overline"},ta=["Re","Im","re","im","conj","arg"];function na(e){const t=[],s=e=>{"op"===e.type?(e.args.forEach(s),n.operator(e.op)?(-1===n.operator(e.op).arity&&t.push(String(e.args.length)),t.push(e.op)):t.push(String(e.args.length),`\\:${ea[e.op]??e.op}`)):t.push(e.token)};return s(e),t}function sa(e,t){if(!t)return e;const s=new Map;for(const[e,i]of Object.entries(t))if("number"==typeof i?Number.isFinite(i):"bigint"==typeof i||"string"==typeof i)try{s.set(e,n.parse(String(i)))}catch{}if(!s.size)return e;const i=function(e){let t;try{t=n.fromPostfix(e)}catch{return new Set}const s=e=>"symbol"===e?.type?e.value:"op"===e?.type&&["=","→"].includes(e.op)&&"symbol"===e.args[0].type?e.args[0].value:null,i=new Set;return n.walk(t,e=>{if("op"!==e.type||e.args.length<2)return;const t=e.op.startsWith("\\:")?e.op.slice(2):e.op;["der","int","lim","diff","derivative","differentiate","integrate","integral","solve","limit"].includes(t)&&s(e.args[1])&&i.add(s(e.args[1]))}),i}(e);return e.flatMap(e=>s.has(e)&&!i.has(e)?s.get(e):[e])}const ia={right:"right",r:"right","+":"right",left:"left",l:"left","-":"left"},ra=new Set(["simplify","expand","factor","cancel","diff","integrate","solve","approx","limit"]),oa={integral:"integrate",differentiate:"diff",approximate:"approx",simp:"simplify"};function aa(e={}){const t=e.rules||e.names?null:e.complex?"complex":"default";if(t&&Xo.has(t))return Xo.get(t);const s=[...e.names??[],...e.complex?ta:[],...ra,...Object.keys(oa)],i=Yo({...e,read:e=>n.parse(e,{names:s}),format:Zo});return t&&Xo.set(t,i),i}const la=e=>String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");var ua='/*\n * Inline Math stylesheet. Everything is under .mv; colors are left to the page.\n *\n * The numbers marked "metric" must match the constants at the top of\n * src/layout.js (line-height 1, bar 0.06em, gap 0.1em); everything else can\n * be changed freely.\n *\n * Handy hooks:\n * .mv-n[data-node="4"] one node (ids from MathZetta)\n * .mv-var .mv-num .mv-word variables, numbers, function names\n * .mv-op-frac .mv-op-pow … a kind of operation\n * .mv-hl the class highlight() adds\n * --mv-hl highlight color\n */\n\n.mv {\n display: inline-block;\n font-family: "Inline Math Roman", "Latin Modern Roman", "STIX Two Text", "Cambria", "Times New Roman", serif;\n font-size: 1.2em;\n font-style: normal;\n font-weight: normal;\n line-height: 1; /* metric */\n white-space: nowrap;\n text-indent: 0;\n text-align: left;\n letter-spacing: 0;\n}\n.mv-display { display: block; text-align: center; margin: 0.6em 0; }\n.mv span, .mv svg { line-height: 1; }\n.mv-n { display: inline-block; border-radius: 0.12em; }\n\n/* ---- letters and signs -------------------------------------------------- */\n.mv-var { font-style: italic; padding-right: 0.03em; }\n.mv-num, .mv-word, .mv-name, .mv-ord, .mv-text, .mv-d, .mv-conj { font-style: normal; }\n.mv-prime { margin-left: 0.04em; }\n.mv-bin { margin: 0 0.22em; }\n.mv-rel { margin: 0 0.28em; }\n.mv-conj { margin: 0 0.6em; } /* x = 2 or x = 3 */\n.mv-punct { margin-right: 0.17em; }\n.mv-sign { margin-right: 0.04em; }\n.mv-times { display: inline-block; width: 0.06em; }\n.mv-callgap { display: inline-block; width: 0.05em; }\n.mv-fnspace { display: inline-block; width: 0.17em; }\n.mv-space { display: inline-block; width: 0.33em; }\n.mv-dx { display: inline-block; margin-left: 0.17em; }\n.mv-text { margin: 0 0.25em; }\n/* Tighter spacing in limits and exponents: n=1, x→0. */\n.mv-script .mv-rel, .mv-sup .mv-rel, .mv-sub .mv-rel { margin: 0 0.12em; }\n.mv-script .mv-bin, .mv-sup .mv-bin, .mv-sub .mv-bin { margin: 0 0.1em; }\n\n/* ---- fractions (metric: padding and border) ------------------------------ */\n.mv-frac { display: inline-flex; flex-direction: column; align-items: stretch; margin: 0 0.12em; }\n.mv-numer, .mv-denom { display: block; text-align: center; padding: 0 0.1em; }\n.mv-numer { padding-bottom: 0.1em; }\n.mv-denom { padding-top: 0.1em; border-top: 0.06em solid currentColor; }\n.mv-frac-nobar > .mv-denom { border-top: 0; }\n.mv-scaled { display: inline-block; }\n\n/* ---- scripts ----------------------------------------------------------------- */\n.mv-sup, .mv-sub { display: inline-block; margin-left: 0.04em; }\n.mv-subsup, .mv-limits { display: inline-flex; flex-direction: column; justify-content: space-between; align-items: flex-start; margin-left: 0.04em; }\n.mv-limits { margin-left: 0.02em; margin-right: 0.12em; }\n.mv-limits > .mv-lower { margin-left: -0.3em; }\n.mv-script { display: block; }\n.mv-under { display: inline-flex; flex-direction: column; align-items: center; margin-right: 0.15em; }\n.mv-under > .mv-script { margin-top: 0.05em; }\n.mv-bigop { display: inline-flex; flex-direction: column; align-items: center; margin: 0 0.12em; }\n.mv-bigop > .mv-script { display: block; margin: 0.08em 0; }\n.mv-bigop > svg { display: block; }\n\n/* ---- radicals (metric: border and padding-top) ----------------------------- */\n.mv-sqrt { display: inline-block; white-space: nowrap; }\n.mv-radicand { display: inline-block; position: relative; border-top: 0.06em solid currentColor; padding: 0.1em 0.1em 0 0.06em; }\n/* the hook, in the radicand\'s left margin (layout.js sets its width and that margin): from the bar\'s center\n (just below the middle of the 0.06em border above the box) to the bottom of what it holds, so the tip always meets the bar */\n.mv-hook { position: absolute; top: -0.02em; height: calc(100% + 0.02em); overflow: visible; } /* a hair below the center: never above the bar */\n.mv-rootindex { display: inline-block; margin: 0 -0.32em 0 0.12em; }\n\n/* ---- delimiters: drawn at the full height of what they enclose -------------- */\n.mv-fence { display: inline-block; position: relative; }\n.mv-delim { position: absolute; top: 0; bottom: 0; height: 100%; }\n.mv-delim-l { left: 0.03em; }\n.mv-delim-r { right: 0.03em; }\nspan.mv-delim { width: 0.16em; border: 0 solid currentColor; box-sizing: border-box; }\n.mv-delim.mv-lbrack { border-width: 0.06em 0 0.06em 0.06em; left: 0.06em; }\n.mv-delim.mv-rbrack { border-width: 0.06em 0.06em 0.06em 0; right: 0.06em; }\n.mv-delim.mv-vert { border-left-width: 0.06em; width: 0; left: 0.07em; }\n.mv-delim.mv-vert.mv-delim-r { left: auto; right: 0.07em; }\n.mv-delim.mv-lfloor { border-width: 0 0 0.06em 0.06em; }\n.mv-delim.mv-rfloor { border-width: 0 0.06em 0.06em 0; }\n.mv-delim.mv-lceil { border-width: 0.06em 0 0 0.06em; }\n.mv-delim.mv-rceil { border-width: 0.06em 0.06em 0 0; }\n/* around one line: inline, placed from the baseline like a typed bracket (0.25em below it, 0.75em above),\n not stretched over the line box, which sits higher or lower in every font; the margins keep the widths */\n.mv-fence-line > .mv-delim { position: static; display: inline-block; vertical-align: -0.25em; height: 1em; }\n.mv-fence-line > svg.mv-delim-l { margin: 0 0.07em 0 0.03em; }\n.mv-fence-line > svg.mv-delim-r { margin: 0 0.03em 0 0.07em; }\n.mv-fence-line > span.mv-delim-l { margin: 0 0.08em 0 0.06em; }\n.mv-fence-line > span.mv-delim-r { margin: 0 0.06em 0 0.08em; }\n.mv-fence-line > .mv-delim.mv-vert.mv-delim-l { margin: 0 0.11em 0 0.07em; }\n.mv-fence-line > .mv-delim.mv-vert.mv-delim-r { margin: 0 0.07em 0 0.11em; }\n\n/* ---- shapes ----------------------------------------------------------------- */\n.mv svg { overflow: visible; }\n.mv svg path[stroke] { stroke-width: 0.065em; stroke-linecap: round; stroke-linejoin: round; }\n.mv-intsign path[stroke] { stroke-width: 0.075em; }\n.mv-bigsign { display: inline-block; margin: 0 0.06em; }\n.mv-intsign { margin-right: 0.12em; }\n\n/* ---- piecewise ------------------------------------------------------------- */\n.mv-cases { display: inline-grid; grid-template-columns: auto auto; column-gap: 1em; row-gap: 0.25em; align-items: baseline; text-align: left; margin: 0 0.1em; }\n.mv-case-value, .mv-case-cond { display: block; }\n.mv-matrix { display: inline-grid; column-gap: 0.8em; row-gap: 0.3em; align-items: baseline; justify-items: center; margin: 0 0.15em; }\n.mv-matrix-row { display: contents; }\n.mv-matrix-cell { display: block; }\n\n/* ---- decorations: \\boxed \\cancel \\overline \\vec … --------------------------- */\n.mv-boxed { display: inline-block; border: 0.06em solid currentColor; padding: 0.16em 0.2em; }\n.mv-over { display: inline-block; position: relative; padding-top: 0.14em; }\n.mv-over::before { content: \'\'; position: absolute; left: 0; right: 0; top: 0.21em; border-top: 0.06em solid currentColor; } /* metric */\n.mv-over-low::before { top: 0.48em; }\n.mv-underline { display: inline-block; border-bottom: 0.06em solid currentColor; padding-bottom: 0.06em; }\n.mv-cancel { display: inline-block; position: relative; }\n.mv-cancel-line { position: absolute; left: 0; top: 0; width: 100%; height: 100%; overflow: visible; pointer-events: none; }\n.mv-accent { display: inline-block; position: relative; padding-top: 0.3em; }\n.mv-accent-mark { position: absolute; top: -0.27em; left: 0; right: 0; text-align: center; font-size: 0.7em; line-height: 0.6; } /* metric: measured over F, h, A */\n/* ˆ ˜ ˙ ¨ are spacing marks that sit high in their em: full size, pulled down onto the letter */\n.mv-accent-hat, .mv-accent-widehat, .mv-accent-tilde, .mv-accent-dot, .mv-accent-ddot { font-size: 1em; line-height: 1; top: 0.02em; }\n/* over an italic letter the mark leans with it, right of the box\'s center */\n.mv-accent:has(> .mv-var) > .mv-accent-mark { transform: translateX(0.1em); }\n/* a letter with no ascender (x, u, α; layout.js adds -low): the mark comes down to its top */\n.mv-accent-low > .mv-accent-mark { top: 0.08em; }\n.mv-accent-low > .mv-accent-hat, .mv-accent-low > .mv-accent-widehat, .mv-accent-low > .mv-accent-tilde, .mv-accent-low > .mv-accent-dot, .mv-accent-low > .mv-accent-ddot { top: 0.31em; }\n\n/* ---- interaction -------------------------------------------------------------- */\n.mv-hl { background: var(--mv-hl, rgba(255, 200, 0, 0.35)); box-shadow: 0 0 0 0.08em var(--mv-hl, rgba(255, 200, 0, 0.35)); }\n/* Windows high contrast (and other forced colors) drops backgrounds and shadows: outline a highlight instead */\n@media (forced-colors: active) {\n .mv-hl { outline: 0.08em solid Highlight; outline-offset: 0.04em; }\n}\n.mv-clickable .mv-n { cursor: pointer; }\n.mv-editable .mv-n:hover { outline: 1px dashed rgba(0, 0, 0, 0.25); }\n/* the box editing a part in place (view.editable, or a Markdown textbox variable) */\n.mv-edit { transform: translateY(-50%); z-index: 1000; box-sizing: content-box; padding: 0.1em 0.35em; font-family: inherit;\n border: 1px solid #1a5fb4; border-radius: 0.25em; background: #fff; color: #111; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.18); }\n.mv-edit[aria-invalid="true"] { border-color: #c33; outline: 2px solid #c33; }\n/* the live region a view announces steps through ({ announce: true }): read, never seen */\n.mv-sr-only, .mv-sr-math { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }\n.mv-clickable .mv-n:hover { outline: 1px dashed rgba(0, 0, 0, 0.25); }\n/* the keyboard: the expression is one tab stop, and the part the arrow keys are on is ringed */\n.mv[tabindex]:focus-visible { outline: 0.1em solid #1a5fb4; outline-offset: 0.12em; }\n.mv[tabindex]:focus .mv-focus { outline: 0.1em solid #1a5fb4; outline-offset: 0.06em; border-radius: 0.1em; }\n/* while a part is ringed, the whole expression\'s ring steps back so the part is the one that stands out */\n.mv[tabindex]:focus-visible:has(.mv-focus) { outline: 1px dashed #1a5fb4; }\n@media (forced-colors: active) {\n .mv[tabindex]:focus-visible, .mv[tabindex]:focus .mv-focus { outline-color: Highlight; }\n}\n\n/* ---- steps (stepsHTML from \'@mathzetta/inlinemath/cas\') ---------------------------------------- */\n.mv-steps { margin: 0; padding-left: 1.6em; }\n.mv-step { margin: 0.5em 0 0.9em; }\n.mv-step-name { display: block; font-size: 0.85em; font-weight: 600; color: #555; }\n.mv-step-maths { display: flex; flex-wrap: wrap; align-items: center; gap: 0.4em 0.8em; margin: 0.15em 0; }\n.mv-step-arrow { color: #888; }\n.mv-step-why { margin: 0.1em 0 0; font-size: 0.9em; color: #444; }\n\n/* ---- Markdown with math (markdownToHTML from \'@mathzetta/inlinemath/markdown\') ------------------- */\n.mv-md-math { display: inline-block; vertical-align: middle; }\n.mv-md-display { display: block; text-align: center; margin: 0.6em 0; overflow-x: auto; }\n.mv-md-block { margin: 0.8em 0; }\n.mv-md-error code { background: rgba(200, 60, 0, 0.08); color: #a33; border-bottom: 1px dotted #a33; }\n/* saved variables: $A := 2+2$ draws A ≔ 2 + 2; $A := [[…]]$ an input that sets A */\n.mv-md-input-def { display: inline-flex; align-items: center; gap: 0.3em; }\n.mv-md-assign { margin: 0 0.1em; }\n.mv-md-input { font: inherit; font-size: 0.9em; }\ninput.mv-md-textbox { font-family: inherit; padding: 0.05em 0.3em; field-sizing: content; min-width: 3ch; }\ninput.mv-md-textbox[aria-invalid="true"] { outline: 2px solid #c33; outline-offset: 1px; }\ninput.mv-md-slider { vertical-align: middle; }\n.mv-md-output { font-variant-numeric: tabular-nums; min-width: 2ch; }\n';const ca=ua;if("undefined"!=typeof document&&!document.getElementById("inlinemath-css")){const e=document.createElement("style");e.id="inlinemath-css",e.textContent=ua,document.head.append(e)}return Object.defineProperty(e,"toText",{enumerable:!0,get:function(){return i.toText}}),e.CSS=ca,e.DEFAULTS=M,e.PATHS=r,e.View=G,e.casBlocks=function(e={}){const n=e.cas??aa(),s=void 0===e.steps?{}:{steps:e.steps},r=(e,o)=>{let a;try{a=n.read(e)}catch{return t.calculateBlock(e,o)}const l=o&&o[Go];l&&(a=a.flatMap(e=>Object.hasOwn(l,e)?l[e]:[e])),a=sa(a,o);const u=a[a.length-1],c=u?.startsWith("\\:")?oa[u.slice(2)]??u.slice(2):null,f=c&&ra.has(c),h="der"===u||"int"===u||"lim"===u;if(!f&&!h)return t.calculateBlock(e,o);const p=n.node(a),d=h&&p.op!==u,m=f?p.args:[p],g=e=>e?e.s:void 0,v=(e,t,i)=>{if(!t||"="!==t.op)return n.diff(e,g(t),{...s,order:i});const r=t.args[0].s,o=n.diff(e,r,{...s,order:i}),a=n.substitute(o.result,{[r]:t.args[1].s},s);return{...a,steps:[...o.steps??[],...a.steps??[]]}};let b;try{switch(d?"simplify-read":f?c:"der"===u?"derivative":"lim"===u?"lim":"antiderivative"){case"simplify-read":b=n.simplify(p,s);break;case"simplify":b=n.simplify(m[0],s);break;case"expand":b=n.expand(m[0],s);break;case"factor":b=n.factor(m[0],s);break;case"cancel":b=n.cancel(m[0],s);break;case"diff":b=v(m[0],m[1],m[2]?Number(m[2].s):1);break;case"integrate":b=n.integrate(m[0],g(m[1]),{...s,...m[3]?{from:m[2].s,to:m[3].s}:{}});break;case"solve":b=n.solve(m[0],g(m[1]),s);break;case"lim":b=n.limit(p,void 0,void 0,s);break;case"limit":b=(([e,t,i,r])=>{let o=r?ia[r.s.replace(/^\\/,"")]:void 0;if(r&&!o)throw new Error(`a side is right or left, not ${r.s}`);if(t&&"→"===t.op){[t,i]=t.args;const e="^"===i.op?i.args[1].s.replace(/^\\/,""):null;"+"!==e&&"-"!==e||(o=ia[e],i=i.args[0])}return n.limit(e,g(t),i,{...s,...o?{side:o}:{}})})(m);break;case"approx":b=n.approximate(m[0],{...s,digits:m[1]?Number(m[1].s):15});break;case"derivative":b=v(p.args[0],p.args[1],1);break;default:b=n.integrate(p,void 0,s)}}catch(t){return`(${e})`}if(r.last=b,!b.result)return`"${b.text}"`;const y=i.toText(na(b.result));return/^-?\d+(\.\d+)?$/.test(y)?y:`(${y})`};return r},e.createVariables=pe,e.extractMath=ge,e.layout=I,e.markdownToHTML=function(e,t={}){return Te(we(e,t,t.variables||null),t)},e.mathCAS=aa,e.nodeAt=R,e.numberTree=_,e.pathOf=W,e.render=function(e,t,n={}){return new G(e,t,n)},e.renderMarkdown=Ie,e.renderMarkdownInto=function(e,t,n={}){const s=void 0===n.variables?de:n.variables||null;Ce();const i=Le.get(e);i&&i.stop(i.store!==s);let r=we(t,n,s,e);if(e.innerHTML=Te(r,n),!s)return Le.delete(e),e;s.own(e,r.defs);let o=e.isConnected;const a=t=>{const i=t.target,r=i&&i.dataset&&i.dataset.mvVar;if(void 0!==r&&e.contains(i)){if("text"===i.type)try{K(i.value,{blocks:n.blocks,scope:{}}),i.removeAttribute("aria-invalid")}catch{return void i.setAttribute("aria-invalid","true")}s.set(r,i.value)}},l=i=>{const o=i.target.closest?.("[data-node]"),a=o&&o.closest("[data-mv-md]");if(!a||!e.contains(a))return;const l=Number(a.dataset.mvMd),u=r.trees[l];if(!u)return;const c=Number(o.dataset.node),f=W(u,c)||[];let h=null;for(let e=f.length;e>=0&&!h;e--){const t=R(u,f.slice(0,e));t&&void 0!==t.from&&(h={node:t,depth:e})}const p=h&&s.definitions().get(h.node.from);if(p&&p.input&&"textbox"===p.input.kind){i.preventDefault();const t=p.name,r=e.ownerDocument.querySelector(`[data-mv-var="${CSS.escape(t)}"]`),a=n.editable&&n.editable.toText;if(!a)return void(r&&(r.focus(),r.select()));const l=e=>K(e),c=R(u,f);return void Y(o,a(re(c,l)),{label:`Edit ${t}`,parse:e=>K(e,{blocks:n.blocks}),commit:e=>{const n=Q(re(h.node,l),f.slice(h.depth),e);s.set(t,a(n))}})}const d=p&&r.defs.get(p.name),m=d&&d.key===p.key&&void 0!==d.start?{...r.math[l],start:d.start,end:d.end,raw:t.slice(d.start,d.end)}:r.math[l];e.dispatchEvent(new CustomEvent("inlinemath:select",{bubbles:!0,detail:{index:l,start:m.start,end:m.end,raw:m.raw,source:m.source,id:c,path:f}}))};e.addEventListener("input",a),e.addEventListener("change",a),e.addEventListener("dblclick",l);const u=s.subscribe(i=>{i!==e&&(e.isConnected?(o=!0,Ce(),(()=>{const i=we(t,n,s,e);i.drawn.forEach((t,n)=>{if(t===r.drawn[n]||i.inputs.has(n))return;const s=e.querySelector(`[data-mv-md="${n}"]`);s&&(s.outerHTML=t)});for(const t of e.querySelectorAll("[data-mv-var], [data-mv-out]")){const e=i.defs.get(t.dataset.mvVar??t.dataset.mvOut);if(!e)continue;const n=s.textOf(e);void 0!==t.dataset.mvOut?t.textContent=n:t.value!==n&&t!==t.ownerDocument?.activeElement&&(t.value=n)}r=i})()):o&&c(!0))});function c(t){u(),e.removeEventListener("input",a),e.removeEventListener("change",a),e.removeEventListener("dblclick",l),je.delete(f),Le.delete(e),t&&s.own(e,null)}const f={element:e,store:s,stop:c,connected:()=>o};return je.add(f),Le.set(e,f),e},e.select=D,e.shouldAnimate=ee,e.signature=F,e.stepsHTML=function(e,t={}){return`<ol class="mv-steps">${e.map(e=>{const n=J(na(rt(e.from)),{...t,highlight:e.path&&e.path.length?{path:e.path}:void 0}),s=e.to===e.from?"":`<span class="mv-step-arrow" aria-label="becomes">⟶</span>${J(na(rt(e.to)),t)}`,i=e.explanation?`<p class="mv-step-why">${la(e.explanation)}</p>`:"";return`<li class="mv-step" data-rule="${la(e.id)}"><span class="mv-step-name">${la(e.name)}</span><div class="mv-step-maths">${n}${s}</div>${i}</li>`}).join("")}</ol>`},e.toHTML=J,e.tokensOf=na,e.treeOf=K,e.variables=de,e}({},MathZetta,MathZetta,MathZetta,MathZetta);