@mathzetta/inlinemath 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +282 -2
- package/dist/cas.external.js +2 -0
- package/dist/cas.js +2 -0
- package/dist/chunks/calculate-BX9lJ7Ff.js +2 -0
- package/dist/chunks/draw-Cm4exbg7.js +2 -0
- package/dist/chunks/html-CvuSyhzk.js +2 -0
- package/dist/chunks/html-DWtfytjA.js +2 -0
- package/dist/chunks/lite-Bj_L6w2g.js +2 -0
- package/dist/fonts/GUST-FONT-LICENSE.txt +30 -0
- package/dist/fonts/fonts.css +17 -0
- package/dist/fonts/lmroman12-italic.woff2 +0 -0
- package/dist/fonts/lmroman12-regular.woff2 +0 -0
- package/dist/inlinemath-cas.external.global.min.js +2 -0
- package/dist/inlinemath-cas.global.min.js +2 -0
- package/dist/inlinemath-lite-calc.global.min.js +2 -0
- package/dist/inlinemath-lite.external.global.min.js +2 -0
- package/dist/inlinemath-lite.global.min.js +2 -0
- package/dist/inlinemath.css +127 -0
- package/dist/inlinemath.external.global.min.js +2 -0
- package/dist/inlinemath.external.js +2 -0
- package/dist/inlinemath.global.min.js +2 -0
- package/dist/inlinemath.js +2 -0
- package/dist/lite-calc.js +2 -0
- package/dist/lite.external.js +2 -0
- package/dist/lite.js +2 -0
- package/dist/markdown.external.js +2 -0
- package/dist/markdown.js +2 -0
- package/fonts/GUST-FONT-LICENSE.txt +30 -0
- package/fonts/fonts.css +17 -0
- package/fonts/lmroman12-italic.woff2 +0 -0
- package/fonts/lmroman12-regular.woff2 +0 -0
- package/inlinemath.css +127 -0
- package/package.json +95 -4
- package/src/calculator.js +6 -0
- package/src/cas.d.ts +3 -0
- package/src/cas.js +139 -0
- package/src/draw.js +72 -0
- package/src/glyphs.js +38 -0
- package/src/html.js +32 -0
- package/src/index.d.ts +3 -0
- package/src/index.js +17 -0
- package/src/layout.js +605 -0
- package/src/lite-calc.d.ts +3 -0
- package/src/lite-calc.js +15 -0
- package/src/lite.d.ts +3 -0
- package/src/lite.js +18 -0
- package/src/markdown.d.ts +3 -0
- package/src/markdown.js +361 -0
- package/src/mathzetta.js +17 -0
- package/src/select.js +108 -0
- package/src/types.d.ts +133 -0
- package/src/view.js +162 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/* Inline Math 0.1.0 — MIT licence; includes mathzetta (and @mathzetta/cas, for the CAS) */
|
|
2
|
+
var InlineMath=function(e){"use strict";const t=-1,n={"+":{prec:50,assoc:"left",arity:2,fixity:"infix"},"-":{prec:50,assoc:"left",arity:2,fixity:"infix"},"±":{prec:50,assoc:"left",arity:2,fixity:"infix"},"*":{prec:70,assoc:"left",arity:2,fixity:"infix"},"/":{prec:70,assoc:"left",arity:2,fixity:"infix"},"^":{prec:80,assoc:"right",arity:2,fixity:"infix"},mod:{prec:45,assoc:"left",arity:2,fixity:"infix"},neg:{prec:75,assoc:"none",arity:1,fixity:"prefix"},pm:{prec:75,assoc:"none",arity:1,fixity:"prefix"},"!":{prec:90,assoc:"none",arity:1,fixity:"postfix"},_:{prec:100,assoc:"none",arity:2,fixity:"infix"},sqrt:r(1),abs:r(1),floor:r(1),ceil:r(1),ln:r(1),loglog:r(1),logloglog:r(1),expm1:r(1),sin:r(1),cos:r(1),tan:r(1),csc:r(1),sec:r(1),cot:r(1),sinh:r(1),cosh:r(1),tanh:r(1),arcsin:r(1),arccos:r(1),arctan:r(1),arcsinh:r(1),arccosh:r(1),arctanh:r(1),random:r(0),log:r(2),root:r(2),atan2:r(2),round:r(2),fixed:r(2),perm:r(2),comb:r(2),der:r(2),max:r(t),min:r(t),gcd:r(t),mean:r(t),sum:r(t),prod:r(t),int:r(t),lim:r(t),"\\sumidx":r(t),"\\prodidx":r(t),"()":s(),"[]":s(),"{}":s(),"(]":s(),"[)":s(),"=":{prec:30,assoc:"left",arity:2,fixity:"infix"},"===":{prec:30,assoc:"left",arity:2,fixity:"infix"},"≠":{prec:30,assoc:"left",arity:2,fixity:"infix"},"≠=":{prec:30,assoc:"left",arity:2,fixity:"infix"},"<":{prec:34,assoc:"left",arity:2,fixity:"infix"},">":{prec:34,assoc:"left",arity:2,fixity:"infix"},"≤":{prec:34,assoc:"left",arity:2,fixity:"infix"},"≥":{prec:34,assoc:"left",arity:2,fixity:"infix"},"∈":{prec:32,assoc:"left",arity:2,fixity:"infix"},"∉":{prec:32,assoc:"left",arity:2,fixity:"infix"},"∪":{prec:33,assoc:"left",arity:2,fixity:"infix"},"∩":{prec:33,assoc:"left",arity:2,fixity:"infix"},"≈":{prec:30,assoc:"left",arity:2,fixity:"infix"},"≡":{prec:30,assoc:"left",arity:2,fixity:"infix"},pmod:{prec:2,assoc:"left",arity:2,fixity:"infix"},"→":{prec:38,assoc:"left",arity:2,fixity:"infix"},"\\not":{prec:85,assoc:"none",arity:1,fixity:"prefix"},"&":{prec:20,assoc:"left",arity:2,fixity:"infix"},"\\xor":{prec:19,assoc:"left",arity:2,fixity:"infix"},"|":{prec:18,assoc:"left",arity:2,fixity:"infix"},"\\nor":{prec:17,assoc:"left",arity:2,fixity:"infix"},"\\nand":{prec:17,assoc:"left",arity:2,fixity:"infix"},"?:":{prec:10,assoc:"right",arity:3,fixity:"infix"}};function r(e){return{prec:100,assoc:"none",arity:e,fixity:"prefix"}}function s(){return{prec:5,assoc:"left",arity:t,fixity:"none",group:!0}}const i="\\:",o=e=>"string"==typeof e&&e.startsWith(i)&&e.length>2;function a(e){return Object.prototype.hasOwnProperty.call(n,e)?n[e]:o(e)?l:void 0}const l=r(t),u=e=>a(e)?.prec;function c(e,t,n){if("mod"===e&&t)return u(t)<=70;if("mod"===t&&["*","/"].includes(e))return!0;if("mod"===t&&["+","-","±"].includes(e))return"right"===n;const r=u(e),s=u(t);if(!r||!s)return!1;if(s!==r)return s<r;const i=a(e).assoc;return"left"===i?"right"===n:"right"===i&&"left"===n}const h=100,p={ln:h,log:h,loglog:h,logloglog:h,sqrt:h,sqrtpow:h,pow:h,expm1:h,der:h,lim:h,int:h,round:h,fixed:h,floor:h,ceil:h,abs:h,random:h,sum:h,prod:h,"\\sumidx":h,"\\prodidx":h,perm:h,comb:h,"\\perm":h,"\\comb":h,"\\binom":h,max:h,min:h,gcd:h,mean:h,sin:h,cos:h,tan:h,csc:h,sec:h,cot:h,sinh:h,cosh:h,tanh:h,arcsin:h,arccos:h,arctan:h,arcsinh:h,arccosh:h,arctanh:h,atan2:h,_:h,"!":90,"\\not":85,"^":80,"*":70,"/":70,frac:70,mod:45,"+":50,"-":50,"±":50,"→":38,"<":34,">":34,"≤":34,"≥":34,"∈":32,"∉":32,"∪":33,"∩":33,"=":30,"==":30,"===":30,"≠":30,"≠=":30,"!==":30,"≈":30,"≡":30,pmod:2,"&":20,"\\xor":19,"|":18,"∨":18,"\\nor":17,"\\nand":17,"?:":10,"?":9,",":5},f=e=>Object.prototype.hasOwnProperty.call(p,e),m=new Set(["^","?:","?","log"]),d=["(","{","["],g=[")","}","]"];function b(e,t=!1){if(!e)return!1;for(let n=0;n<e.length;n++)if(!("0123456789.".includes(e[n])||t&&0===n&&"-"===e[n]&&e.length>1))return!1;return!0}for(const e of[p])Object.setPrototypeOf(e,null);const v=e=>({type:"number",value:String(e)}),y=e=>({type:"symbol",value:e}),w=(e,t)=>({type:"op",op:e,args:t}),x=['"',"'","`"];function $(e){return b(e,!0)?v(e):x.includes(e[0])?{type:"string",value:e}:y(e)}const k={"0-":"neg",sqrtpow:"root",pow:"^","==":"=","!==":"≠="};function q(e){if(!Array.isArray(e)||0===e.length)throw new Error("Empty postfix");const n=[],r=[];if(e.forEach((e,s)=>{const i=k[e]??String(e),o=a(i);if(!o)return n.push({...$(i),id:s}),void r.push(1);let l=o.arity;if(l===t){const e=n.pop();if(r.pop(),l=e&&"number"===e.type?Number(e.value):NaN,!Number.isInteger(l)||l<0)throw new Error(`'${i}' takes a variable number of arguments, so it must follow a count`)}if(n.length<l)throw new Error(`'${i}' needs ${l} operand${1===l?"":"s"}`);const u=1+Math.max(0,...r.splice(r.length-l,l));if(u>1e3)throw new Error("Nested too deeply (more than 1000 levels)");r.push(u),n.push({...w(i,n.splice(n.length-l,l)),id:s})}),1!==n.length)throw new Error(`Postfix leaves ${n.length} values instead of 1`);return n[0]}function M(e){const n=[];return function e(r){"op"===r.type?(r.args.forEach(e),a(r.op)?.arity===t&&n.push(String(r.args.length)),n.push(r.op)):n.push(r.value)}(e),n}function N(e){if(Array.isArray(e))return q(e);if(e&&"object"==typeof e&&e.type)return e;throw new Error("Expected a postfix array or an expression tree")}function S(e,t,n=null){t(e,n),"op"===e.type&&e.args.forEach(n=>S(n,t,e))}function A(e){let t="";return S(e,e=>{!t&&"symbol"===e.type&&1===e.value.length&&/[a-zA-Zʹ-Ͽ]/.test(e.value)&&(t=e.value)}),t}for(const e of[k])Object.setPrototypeOf(e,null);const O={alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω"};function E(e){for(;"op"===e.type&&e.args.length;)e=e.args[0];return"op"===e.type?"":e.value}function I(e){if("*"!==e.op)return!1;const[t,n]=e.args;return"number"===t.type&&"-1"===t.value&&"-1"!==E(n)}function _(e){return"op"!==e.type||a(e.op)?.group?null:"sum"===e.op?"+":"prod"===e.op?"*":I(e)?null:e.op}const T=(e,t,n)=>c(e.op,_(t),n);function j(e,t){const n=_(t),r=n&&a(n)?.prec;return!!r&&("!"===e?r<=a("!").prec:"\\not"===e?r<a("\\not").prec:r<70||B(t)||"\\not"===n)}function C(e,t,n={}){const r=n.left?"bracket":Z(e),s=n.right?"bracket":R(t);return"digit"!==s&&"sign"!==s&&"word"!==r&&"word"!==s&&"other"!==r&&("frac"!==s||"digit"!==r&&"frac"!==r)}function z(e){return 1===e.length||Boolean(O[e])||/^Δ.$/.test(e)||/^.′+$/.test(e)}function L(e){return"op"===e.type&&!a(e.op)?.group&&(a(e.op)?.prec??100)<70&&!["sum","prod"].includes(e.op)}function R(e){if("number"===e.type)return e.value.startsWith("-")?"sign":"digit";if("op"!==e.type)return"symbol"===e.type&&z(e.value)?"name":"word";const t=e.op;return"neg"===t||"pm"===t||I(e)?"sign":"/"===t?"frac":a(t)?.group||L(e)?"bracket":F(e)||["der","int","lim","comb"].includes(t)?"call":["^","!","_"].includes(t)?L(e.args[0])?"bracket":R(e.args[0]):["*","sum","prod","perm"].includes(t)?R(e.args[0]):"other"}function Z(e){if("number"===e.type)return"digit";if("op"!==e.type)return"symbol"===e.type&&z(e.value)?"name":"word";const t=e.op;return"/"===t?"frac":"^"===t||"_"===t?"script":a(t)?.group||L(e)||F(e)||["der","int","lim","comb","perm"].includes(t)?"bracket":["*","neg","pm","sum","prod"].includes(t)?Z(e.args[e.args.length-1]):"other"}function F(e){if("op"!==e.type)return!1;const t=a(e.op);return"prefix"===t?.fixity&&100===t.prec}function B(e){if("number"===e.type)return e.value.startsWith("-");if("op"!==e.type)return!1;if("neg"===e.op||I(e))return!0;const t=a(e.op);return"infix"===t?.fixity&&!T(e,e.args[0],"left")&&B(e.args[0])}const P=e=>"symbol"===e.type&&1===e.value.length&&/[a-zA-Zʹ-Ͽ]/.test(e.value),D=e=>e.slice(2);function W(e){const t=e.args[1];let n=0,r=e;for(;"op"===r.type&&"der"===r.op&&U(r.args[1],t);)n++,r=r.args[0];return{n:n,body:r,by:t,variable:"symbol"===r.type&&z(r.value)}}const U=(e,t)=>e.type===t.type&&e.value===t.value&&"op"!==e.type,V=new Set(["<",">","≤","≥","=","≠"]);function H(e){if("op"!==e.type||!V.has(e.op)||2!==e.args.length)return null;const[t,n]=e.args;if("op"!==t.type||!V.has(t.op)||2!==t.args.length)return null;return{type:"op",op:"&",args:[H(t)??t,{type:"op",op:e.op,args:[t.args[1],n]}]}}for(const e of[O])Object.setPrototypeOf(e,null);function G(e){const t=new Map;for(const[n,r,s]of e)if(n&&""!==n.trim()&&(t.set(n,r),!s))for(const e of Q(n))t.get(e)||t.set(e,r);const n=new Map;for(const e of t.keys()){let t=n;for(let n=0;n<e.length;n++)t.has(e[n])||t.set(e[n],new Map),t=t.get(e[n]);t.end=!0}return e=>{let r="",s=0;for(;s<e.length;){const i=X(n,e,s);i?(r+=t.get(e.slice(s,s+i)),s+=i):r+=e[s++]}return r}}function X(e,t,n){let r=e,s=0;for(let e=n;e<t.length&&(r=r.get(t[e]),r);e++)r.end&&(s=e-n+1);return s}function Q(e){const t=new Set([e.toLowerCase(),e.toUpperCase(),J(e)]);return t.delete(e),t}function J(e){let t="",n=!1;for(const r of e){const e=r>="a"&&r<="z",s=r>="A"&&r<="Z";t+=!n&&e?r.toUpperCase():r,n=e||s}return t}const Y="({[",K=")}]";function ee(e){const t=e.replace(/^\s*(?:\\(?:text|textrm|mathrm)\s*\{\s*(?:if|for|when|where)\s*\}|\b(?:if|for|when|where)\b)\s*,?/,"").replace(/[\s,.;]+$/,"").trim();return/^(?:\\(?:text|textrm|mathrm)\s*\{\s*)?(?:otherwise|else)\s*\}?$/.test(t)?"":t}function te(e,t){const n=[];let r=0,s=0;for(let i=0;i<e.length;i++)Y.includes(e[i])?r++:K.includes(e[i])?r--:0===r&&e.startsWith(t,i)&&(n.push(e.slice(s,i)),i+=t.length-1,s=i+1);return n.push(e.slice(s)),n}function ne(e,t,n){let r=0;const s=new RegExp(`\\b${n}\\b`,"iy");for(let n=t;n<e.length;n++)if(Y.includes(e[n]))r++;else if(K.includes(e[n])){if(--r<0)return-1}else if(0===r&&(s.lastIndex=n,s.test(e)))return n;return-1}function re(e,t){let n=0;for(let r=t;r<e.length;r++)if(Y.includes(e[r]))n++;else if(K.includes(e[r])&&--n<0)return r;return e.length}function se(e,t){let n=1;for(let r=t+1;r<e.length;r++)if("?"===e[r])n++;else if(":"===e[r]&&0===--n)return e.slice(0,t+1)+"("+e.slice(t+1,r)+")?:"+e.slice(r+1);return e}function ie(e){for(let t=2;t<e.length;t++)if("g"===e[t]&&"log"===e.slice(t-2,t+1))if("_"===e[t+1]){if(Y.includes(e[t+2]))continue;const n=/^(?:\d+(?:\.\d+)?|[A-Za-z\u0370-\u03FF])/.exec(e.slice(t+2))?.[0];if(!n)continue;const r=t+2+n.length;e=e.slice(0,t+2)+"{"+n+"}"+e.slice(r)}else if("("===e[t+1]){let n=1,r=0,s="",i="",o=0;for(let a=t+2;a<e.length;a++){if(")]".includes(e[a])?n--:"([".includes(e[a])&&n++,0===n){o=a;break}1===n&&","===e[a]?r++:0===r?s+=e[a]:i+=e[a]}1===r&&(e=e.slice(0,t+1)+"_{"+i+"}("+s+")"+e.slice(o+1))}return e}function oe(e){const t="⌈"===e[0]?"ceil":"floor";let n=1;for(let r=1;r<e.length;r++)if("⌊"===e[r]||"⌈"===e[r]?n++:"⌋"!==e[r]&&"⌉"!==e[r]||n--,0===n)return t+"("+e.slice(1,r)+")"+e.slice(r+1);return e}function ae(e){let t=1;for(let n=0;n<e.length;n++){if(")]".includes(e[n])?t--:"([".includes(e[n])&&t++,0!==t)continue;const r=e.slice(0,n),s=e[n+1];if("{"===s||"("===s)return s+r+","+e.slice(n+2);const i=/^[A-Za-z0-9.\u0370-\u03FF]+/.exec(e.slice(n+1))?.[0]??"";return"{"+r+","+i+"}"+e.slice(n+1+i.length)}return e}function le(e){const t=e.indexOf("}"),n=e.indexOf("{");if(t<0||n>=0&&n<t)return!1;const r=e.slice(0,t);if(!r.includes("matrix"))return!1;const s=e.indexOf("\\end{"+r+"}"),i=e.indexOf("\\begin{"+r+"}",t+1);if(s<0||-1!==i&&i<s)return!1;const o=e.slice(t+1,s).trim().split("\\\\").map(e=>e.trim()).filter(e=>e.length).map(e=>"["+e.replace(/&/g,", ")+"]");return"["+o.join(", ")+"]"+e.slice(s+6+r.length)}function ue(e,t){if("{"!==e[t+1])return[e[t+1],t+2];let n=1,r="";for(let s=t+2;s<e.length;s++){if("{"===e[s])n++;else if("}"===e[s]&&0===--n)return[r,s+1];r+=e[s]}return[r,e.length]}function ce(e){const{lower:t,upper:n,next:r}=function(e){let t="",n="",r=0;return"_"===e[0]&&([t,r]=ue(e,0),"^"===e[r]&&([n,r]=ue(e,r))),{lower:t,upper:n,next:r}}(e),s=e.slice(r),i=e=>e.replace(/\\,/g,"").replace(/\\!/g,"");let o,a="",l="",u=s.indexOf("\\mathrm{d}");if(u>=0){o=s.slice(0,u);const e=/^\{([^{}]*)\}/.exec(s.slice(u+10));a=e?e[1]:s[u+10],l=s.slice(u+10+(e?e[0].length:1))}else(u=function(e){let t=0;for(let n=0;n<e.length;n++)if(Y.includes(e[n]))t++;else if(K.includes(e[n]))t--;else if(0===t&&"d"===e[n]&&/[A-Za-z\u0370-\u03FF]/.test(e[n+1]??"")&&!/[A-Za-z]/.test(e[n+2]??""))return n;return-1}(s))>=0?(o=s.slice(0,u),a=s[u+1],l=s.slice(u+2)):o=s;if(!a){const e=/frac\{d([A-Za-z])\}/.exec(o);e&&(a=e[1],o=o.replace(e[0],"frac{1}"))}if(!a&&/^[A-Za-z]$/.test(t)){a=[...i(o).matchAll(/(?<![A-Za-z\\])([A-Za-z])(?![A-Za-z(])/g)].map(e=>e[1]).find(e=>e!==t&&e!==n)??"x"}let c="int("+(i(o)||"1");return a&&(c+=","+a),(t||n)&&(c+=","+t+","+n),c+")"+l}function he(e){const t=e[0];if(!(t>="A"&&t<="Z"||t>="a"&&t<="z"||t>="α"&&t<="ω"))return!1;const n=e.slice(2);let r=1;for(let e=0;e<n.length;e++)if(K.includes(n[e])?r--:Y.includes(n[e])&&r++,0===r)return"("+n.slice(0,e)+","+t+")"+n.slice(e+1);return!1}function pe(e){return"{"===e[0]||e.length<2?e:"{"+e[0]+"}{"+e[1]+"}"+e.slice(2)}const fe=/[A-Za-z\u0370-\u03FF]/;function me(e,t){if("{"!==e[t])return null;let n=0;for(let r=t;r<e.length;r++)if("{"===e[r])n++;else if("}"===e[r]&&0===--n)return[e.slice(t+1,r),r+1];return null}function de(e,t){const n=/^\^(?:\{(\d+)\}|(\d))/.exec(e.slice(t));return n?[Number(n[1]??n[2]),t+n[0].length]:[1,t]}function ge(e,t){const n=e.replace(/\\mathrm\{d\}/g,"d"),r=t.replace(/\\mathrm\{d\}/g,"d"),s=/^d(?:\^\{?(\d+)\}?)?([A-Za-z\u0370-\u03FF]?)$/.exec(n),i=/^d([A-Za-z\u0370-\u03FF])(?:\^\{?(\d+)\}?)?$/.exec(r);return s&&i?{n:Number(s[1]??1),of:s[2],by:i[1]}:null}function be(e,t){if(Y.includes(e[t])){let n=0;for(let r=t;r<e.length;r++)if(Y.includes(e[r]))n++;else if(K.includes(e[r])&&0===--n)return[e.slice(t,r+1),r+1];return[e.slice(t),e.length]}let n=0;for(let r=t;r<e.length;r++)if(Y.includes(e[r]))n++;else{if(K.includes(e[r])&&--n<0)return[e.slice(t,r),r];if(0===n&&("="===e[r]||","===e[r]))return[e.slice(t,r),r]}return[e.slice(t),e.length]}const ve=(e,t,n)=>`der(${e},${t}${n>1?","+n:""})`;const ye="strtktk",we="ABCDEFGHIJ",xe=e=>ye+[...String(e)].map(e=>we[e]).join("");function $e(e,t){let n=!1;for(let r=t+1;r<e.length;r++)if(n)n=!1;else if("\\"===e[r])n=!0;else if(e[r]===e[t])return r;return e.length-1}function ke(e,t){if(!t||0===t.size)return e;const n=[...t].sort((e,t)=>t[0].length-e[0].length);return e.map(e=>{for(const[t,r]of n)e=e.split(t).join(r);return e})}const qe={factorial:"((n) => { if (!Number.isInteger(n) || n < 0) return NaN; let r = 1; for (let i = 2; i <= n; i++) r *= i; return r; })",perm:"((n, k) => { let r = 1; for (let i = n - k + 1; i <= n; i++) r *= i; return r; })",comb:"((n, k) => { let r = 1; for (let i = 1; i <= k; i++) r = r * (n - k + i) / i; return r; })",gcd:"((args)=>{let gcd = function(a,b) { return (!b)?a:gcd(b,a%b); }; return Math.abs(args.reduce(gcd));})"};for(const e of[qe])Object.setPrototypeOf(e,null);const Me="([{",Ne=")]}";function Se(e,t){let n=0;for(let r=t;r<e.length;r++)if(Me.includes(e[r]))n++;else if(Ne.includes(e[r])&&0===--n)return r;return-1}function Ae(e){if(!e.trim())return[];const t=[];let n=0,r=0;for(let s=0;s<e.length;s++)Me.includes(e[s])?n++:Ne.includes(e[s])?n--:","===e[s]&&0===n&&(t.push(e.slice(r,s).trim()),r=s+1);return t.push(e.slice(r).trim()),t}function Oe(e,t,n){const r=[...e.matchAll(t)];for(let t=r.length-1;t>=0;t--){const s=r[t],i=s.index+s[0].length-1,o=Se(e,i);if(o<0)continue;const a=n(Ae(e.slice(i+1,o)),s,e.slice(o+1));if(null==a)continue;const[l,u=0]=Array.isArray(a)?a:[a];if((e=e.slice(0,s.index)+l+e.slice(o+1+u)).length>1e5)throw new Error("The expression expands too much when read")}return e}const Ee=e=>new RegExp(`(?<![\\w.])(${e})\\s*\\(`,"g"),Ie=e=>`(${e})`,_e=e=>/^\[.*\]$/s.test(e.trim())?`{${e.trim().slice(1,-1)}}`:e;const Te={IF:e=>e.length>=2&&`((${e[0]}) ? (${e[1]}) : (${e[2]??"false"}))`,AND:e=>e.length&&`(${e.map(Ie).join(" & ")})`,OR:e=>e.length&&`(${e.map(Ie).join(" ∨ ")})`,NOT:e=>1===e.length&&`(!(${e[0]}))`,XOR:e=>2===e.length&&`((${e[0]}) \\xor (${e[1]}))`,LOG:e=>2===e.length?`log_{${e[1]}}(${e[0]})`:1===e.length&&`log_{10}(${e[0]})`,ATAN2:e=>2===e.length&&`atan2(${e[1]}, ${e[0]})`,INT:e=>1===e.length&&`floor(${e[0]})`,FIXED:e=>(1===e.length||2===e.length)&&`fixed(${e[0]}, ${e[1]??2})`,"FLOOR.MATH":e=>1===e.length&&`floor(${e[0]})`,"CEILING.MATH":e=>1===e.length&&`ceil(${e[0]})`,FACT:e=>1===e.length&&`((${e[0]})!)`,COMBIN:e=>2===e.length&&`comb(${e.join(", ")})`,PERMUT:e=>2===e.length&&`perm(${e.join(", ")})`,AVERAGE:e=>`mean(${e.join(", ")})`,SUM:e=>`sum(${e.join(", ")})`,PRODUCT:e=>`prod(${e.join(", ")})`,MAX:e=>`max(${e.join(", ")})`,MIN:e=>`min(${e.join(", ")})`,MEDIAN:e=>`median(${e.join(", ")})`,"STDEV.P":e=>`stdev(${e.join(", ")})`,STDEVP:e=>`stdev(${e.join(", ")})`,CEILING:e=>(1===e.length||2===e.length&&"1"===e[1].trim())&&`ceil(${e[0]})`,RAND:e=>!e.length&&"random()",ISNUMBER:e=>1===e.length&&`((${e[0]}) ∈ ℝ)`,LOG10:e=>1===e.length&&`log_{10}(${e[0]})`};const je={POWER:"pow",SQRT:"sqrt",ABS:"abs",LN:"ln",EXP:"exp",FLOOR:"floor",CEIL:"ceil",CEILING:"ceil",ROUND:"round",GREATEST:"max",LEAST:"min",MOD:"mod",ATAN2:"atan2",FACTORIAL:"factorial",SIN:"sin",COS:"cos",TAN:"tan",SEC:"sec",CSC:"csc",COT:"cot",ASIN:"asin",ACOS:"acos",ATAN:"atan",SINH:"sinh",COSH:"cosh",TANH:"tanh",ASINH:"asinh",ACOSH:"acosh",ATANH:"atanh",COMB:"comb",PERM:"perm",GCD:"gcd",DERIVATIVE:"derivative",LIMIT:"limit",UNION:"union",EXPM1:"expm1",TRUNC:"trunc",SUMMATION:"sum"},Ce="strtktk[A-J]+";function ze(e){for(let t=!0;t;){const n=e;t=(e=e.replace(new RegExp(`(${Ce})\\s*\\|\\|\\s*(${Ce})`,"g"),"$1 + $2"))!==n}const t=new RegExp(`^\\(typeof\\(([^()]*)\\)\\s+IN\\s+\\(${Ce},\\s*${Ce}\\)\\s+AND\\s+(.*)\\)$`,"s");for(let n=e.lastIndexOf("(typeof(");n>=0;n=n>0?e.lastIndexOf("(typeof(",n-1):-1){const r=Se(e,n),s=r>0&&t.exec(e.slice(n,r+1));if(!s)continue;const[,i,o]=s,a={[`${i} = TRUNC(${i})`]:"ℤ",[`${i} = TRUNC(${i}) AND ${i} > 0`]:"ℕ",[`ABS(${i}) < ∞`]:"ℝ"}[o.trim()];a&&(e=`${e.slice(0,n)}((${i}) ∈ ${a})${e.slice(r+1)}`)}e=Oe(e,/(?<![\w.])CAST\s*\(/gi,e=>{const t=1===e.length&&/^(.*)\s+AS\s+(?:REAL|FLOAT|DOUBLE(?:\s+PRECISION)?|NUMERIC|DECIMAL|INTEGER|INT)\s*$/is.exec(e[0]);return t?`(${t[1]})`:null}),e=(e=(e=Oe(e=function(e){for(let t=0;t<50;t++){const t=[...e.matchAll(/\bCASE\s+WHEN\b/gi)];if(!t.length)return e;const n=t[t.length-1].index,r=/\bEND\b/i.exec(e.slice(n));if(!r)return e;const s=e.slice(n+4,n+r.index).split(/\b(WHEN|THEN|ELSE)\b/i).map(e=>e.trim()),i=[];let o="null";for(let e=1;e<s.length;e+=2){const t=s[e].toUpperCase();"WHEN"===t?i.push([s[e+1],s[e+3]]):"ELSE"===t&&(o=s[e+1])}const a=i.reduceRight((e,[t,n])=>`((${t}) ? (${n}) : ${e})`,Ie(o));e=e.slice(0,n)+a+e.slice(n+r.index+3)}return e}(e=e.replace(/(?<![\w.])ARRAY\s*\[/g,"[")),/(?<![\w.])LOG\s*\(/g,e=>2===e.length?`log_{${e[0]}}(${e[1]})`:`log_{10}(${e[0]})`)).replace(/(?<![\w.])PI\s*\(\s*\)/g,"π")).replace(/(?<![\w.])([A-Z][A-Z0-9]*)(?=\s*\()/g,e=>je[e]??e);for(const[t,n]of[[/\bNOT\s+IN\s*\(/g,"∉"],[/\bIN\s*\(/g,"∈"]])for(let r=t.exec(e);r;r=t.exec(e)){const s=r.index+r[0].length-1,i=Se(e,s);if(i<0)break;e=`${e.slice(0,r.index)}${n} {${e.slice(s+1,i)}}${e.slice(i+1)}`,t.lastIndex=0}return e.replace(/<>/g," ≠ ")}const Le={sin:"sin",cos:"cos",tan:"tan",sinh:"sinh",cosh:"cosh",tanh:"tanh",arcsin:"asin",arccos:"acos",arctan:"atan",arcsinh:"asinh",arccosh:"acosh",arctanh:"atanh",arctan2:"atan2",sqrt:"sqrt",cbrt:"cbrt",exp:"exp",expm1:"expm1",log:"log",log2:"log2",log10:"log10",floor:"floor",ceil:"ceil",round:"round",power:"pow",abs:"abs",absolute:"abs",fabs:"abs",pi:"PI",e:"E",gcd:"gcd"},Re={maximum:"max",minimum:"min",nanmax:"max",nanmin:"min",nansum:"sum",nanprod:"prod",nanmean:"mean",nanmedian:"median",nanstd:"stdev",mod:"mod",fmod:"mod",where:"where",isin:"isin",isclose:"isclose",isfinite:"isfinite",logical_and:"logical_and",logical_or:"logical_or",logical_not:"logical_not",logical_xor:"logical_xor",prod:"prod",sum:"sum",trunc:"trunc"};function Ze(e){return e=(e=e.replace(/(?<![\w.])(?:np|numpy)\.random\.random\(\s*\)|(?<![\w.])random\.random\(\s*\)/g,"Math.random()")).replace(/(?<![\w.])(?:np|numpy)\.(\w+)/g,(e,t)=>Le[t]?`Math.${Le[t]}`:Re[t]?Re[t]:{inf:"∞",nan:"NaN"}[t]??e),e=function(e){return e=e.replace(/(?<![\w.])sympy\.Interval\.(open|Lopen|Ropen)\s*\(/g,(e,t)=>`sympy_interval_${t}(`),e=e.replace(/(?<![\w.])sympy\.S\.(\w+)/g,(e,t)=>Be[t]??e),e=e.replace(/(?<![\w.])sympy\.(Reals|Integers|Naturals0?|Rationals|Complexes)\b/g,(e,t)=>Be[t]),e.replace(/(?<![\w.])sympy\.(\w+)/g,(e,t)=>Pe[t]??Fe[t]??e)}(e=(e=(e=e.replace(/(?<![\w.])(?:math|Math)\.(factorial|isfinite|isclose|prod|inf|nan|abs|trunc)\b/g,(e,t)=>({inf:"∞",nan:"NaN"}[t]??t))).replace(/(?<![\w.])Number\.(isInteger|isFinite)\b/g,(e,t)=>t.toLowerCase())).replace(/(?<![\w.])scipy\.(?:special|integrate)\.(\w+)/g,"$1")),(e=e.replace(/\bMZ_INFINITY\b/g,"∞")).replace(/(?<![\w.])mz_(?=\w+\s*\()/g,"")}const Fe={pi:"π",E:"e",oo:"∞",true:"true",false:"false",nan:"NaN",I:"i"},Be={Reals:"ℝ",Integers:"ℤ",Naturals:"ℕ",Naturals0:"ℕ",Rationals:"ℚ",Complexes:"ℂ"},Pe={sqrt:"Math.sqrt",exp:"Math.exp",sin:"Math.sin",cos:"Math.cos",tan:"Math.tan",sinh:"Math.sinh",cosh:"Math.cosh",tanh:"Math.tanh",asin:"Math.asin",acos:"Math.acos",atan:"Math.atan",asinh:"Math.asinh",acosh:"Math.acosh",atanh:"Math.atanh",atan2:"atan2",csc:"csc",sec:"sec",cot:"cot",log:"log",Abs:"abs",floor:"floor",ceiling:"ceil",Max:"max",Min:"min",factorial:"factorial",binomial:"comb",ff:"perm",gcd:"gcd",gcd_list:"sympy_list_gcd",Mod:"mod",root:"sympy_root",Rational:"sympy_rational",Integer:"sympy_value",Float:"sympy_value",Eq:"sympy_eq",Ne:"sympy_ne",And:"sympy_and",Or:"sympy_or",Not:"sympy_not",Xor:"sympy_xor",Nand:"sympy_nand",Nor:"sympy_nor",Piecewise:"sympy_piecewise",FiniteSet:"sympy_set",Interval:"sympy_interval",Contains:"sympy_contains",Union:"union",Intersection:"intersection",diff:"derivative",integrate:"sympy_integrate",limit:"sympy_limit",summation:"sympy_summation",product:"sympy_product",expm1:"expm1"},De={open:"()",Lopen:"(]",Ropen:"[)"};const We=e=>{const t=/^\((.*)\)$/s.exec(e.trim());return t?Ae(t[1]):null},Ue=e=>t=>2===t.length&&`${e[0]}${t[0]}, ${t[1]}${e[1]}`,Ve=e=>We(e)??[e],He={where:e=>3===e.length&&`((${e[0]}) ? (${e[1]}) : (${e[2]}))`,logical_and:e=>2===e.length&&`((${e[0]}) & (${e[1]}))`,logical_or:e=>2===e.length&&`((${e[0]}) ∨ (${e[1]}))`,logical_xor:e=>2===e.length&&`((${e[0]}) \\xor (${e[1]}))`,logical_not:e=>1===e.length&&`(!(${e[0]}))`,isin:e=>2===e.length&&`((${e[0]}) ∈ ${_e(e[1])})`,contains:e=>2===e.length&&`((${e[1]}) ∈ ${_e(e[0])})`,isclose:e=>e.length>=2&&`((${e[0]}) ≈ (${e[1]}))`,isfinite:e=>1===e.length&&`((${e[0]}) ∈ ℝ)`,isinteger:e=>1===e.length&&`((${e[0]}) ∈ ℤ)`,factorial:e=>1===e.length&&`((${e[0]})!)`,union:e=>2===e.length&&`((${e[0]}) ∪ (${e[1]}))`,union_:e=>2===e.length&&`((${e[0]}) ∪ (${e[1]}))`,intersection:e=>2===e.length&&`((${e[0]}) ∩ (${e[1]}))`,sq:e=>1===e.length&&`((${e[0]})^2)`,cube:e=>1===e.length&&`((${e[0]})^3)`,fract:e=>1===e.length&&`((${e[0]}) - floor(${e[0]}))`,inversesqrt:e=>1===e.length&&`(1/sqrt(${e[0]}))`,mod:e=>2===e.length&&`((${e[0]}) \\mod (${e[1]}))`,atan:e=>2===e.length&&`atan2(${e[0]}, ${e[1]})`,exp2:e=>1===e.length&&`((2)^(${e[0]}))`,trunc:e=>1===e.length&&`((${e[0]}) - ((${e[0]}) \\mod 1))`,vec2:e=>`(${e.join(", ")})`,vec3:e=>`(${e.join(", ")})`,vec4:e=>`(${e.join(", ")})`,derivative:e=>e.length>=2&&`der(${e.join(", ")})`,sympy_rational:e=>2===e.length&&`((${e[0]})/(${e[1]}))`,sympy_value:e=>1===e.length&&`(${e[0]})`,sympy_eq:e=>2===e.length&&`((${e[0]}) = (${e[1]}))`,sympy_ne:e=>2===e.length&&`((${e[0]}) ≠ (${e[1]}))`,sympy_and:e=>e.length&&`(${e.map(Ie).join(" & ")})`,sympy_or:e=>e.length&&`(${e.map(Ie).join(" ∨ ")})`,sympy_not:e=>1===e.length&&`(!(${e[0]}))`,sympy_xor:e=>2===e.length&&`((${e[0]}) \\xor (${e[1]}))`,sympy_nand:e=>2===e.length&&`((${e[0]}) \\nand (${e[1]}))`,sympy_nor:e=>2===e.length&&`((${e[0]}) \\nor (${e[1]}))`,sympy_piecewise:e=>{const t=e.map(We);return!t.length||t.some(e=>!e||2!==e.length)?null:t.reduceRight((e,[t,n])=>null===e||/^True$|^true$/.test(n.trim())&&void 0===e?`(${t})`:`((${n}) ? (${t}) : ${e??"(null)"})`,void 0)},sympy_set:e=>`{${e.join(", ")}}`,sympy_interval:Ue("[]"),sympy_interval_open:Ue("()"),sympy_interval_Lopen:Ue("(]"),sympy_interval_Ropen:Ue("[)"),sympy_contains:e=>2===e.length&&`((${e[0]}) ∈ ${e[1]})`,sympy_list_gcd:e=>1===e.length&&`gcd(${e[0].trim().replace(/^\[|\]$/g,"")})`,sympy_root:e=>2===e.length&&`root(${e[1]}, ${e[0]})`,sympy_integrate:e=>{if(2!==e.length)return null;const t=Ve(e[1]);return 3===t.length?`int(${e[0]}, ${t.join(", ")})`:1===t.length?`int(${e[0]}, ${t[0]})`:null},sympy_limit:e=>e.length>=3&&`lim(${e.slice(0,3).join(", ")}${e[3]?`, ${e[3]}`:""})`,sympy_summation:e=>{if(3===e.length&&/^\s*[A-Za-z]\w*\s*==/.test(e[1]))return`sum(${e[0]}, ${e[1].replace("==","=")}, ${e[2]})`;const t=2===e.length&&Ve(e[1]);return 3===t?.length&&`(\\sum_{${t[0]}=${t[1]}}^{${t[2]}} (${e[0]}))`},sympy_product:e=>{if(3===e.length&&/^\s*[A-Za-z]\w*\s*==/.test(e[1]))return`prod(${e[0]}, ${e[1].replace("==","=")}, ${e[2]})`;const t=2===e.length&&Ve(e[1]);return 3===t?.length&&`(\\prod_{${t[0]}=${t[1]}}^{${t[2]}} (${e[0]}))`},limit:e=>e.length>=3&&`lim(${e.join(", ")})`,summation:e=>3===e.length&&/^\s*[A-Za-z]\w*\s*==/.test(e[1])&&`sum(${e[0]}, ${e[1].replace("==","=")}, ${e[2]})`,sum:Ge("sum"),prod:Ge("prod")};function Ge(e){return t=>{const n=1===t.length&&/^(.*?)\s+for\s+(\w+)\s+in\s+range\((.*)\)\s*$/s.exec(t[0]);if(!n)return null;const r=Ae(n[3]),[s,i]=1===r.length?["0",r[0]]:r,o=/\s*\+\s*1$/.test(i)?i.replace(/\s*\+\s*1$/,""):`(${i}) - 1`;return`(\\${e}_{${n[2]}=${s}}^{${o}} (${n[1]}))`}}for(const e of[Te,je,Le,Re,Fe,Be,Pe,De,He])Object.setPrototypeOf(e,null);const Xe=String.raw`(?:\([^()]*\)|\[[^\[\]]*\]|\{[^{}]*\}|(?<![\w.′^])[\w.′^]+)`,Qe=e=>e.trim().split(/\s+/).join(String.raw`\s+`),Je=e=>new RegExp(String.raw`(?<![\w.])${Qe(e)}(?![\w.])`,"gi"),Ye=[["is greater than or equal to","≥"],["is more than or equal to","≥"],["is at least","≥"],["is no less than","≥"],["is not less than","≥"],["is less than or equal to","≤"],["is at most","≤"],["is no more than","≤"],["is not more than","≤"],["is not greater than","≤"],["is greater than",">"],["is more than",">"],["is bigger than",">"],["is larger than",">"],["is above",">"],["exceeds",">"],["is less than","<"],["is smaller than","<"],["is fewer than","<"],["is below","<"],["is not equal to","≠"],["does not equal","≠"],["doesn't equal","≠"],["is different from","≠"],["is approximately equal to","≈"],["is approximately","≈"],["is about","≈"],["is roughly","≈"],["is close to","≈"],["is equal to","="],["is the same as","="],["equals","="],["greater than or equal to","≥"],["less than or equal to","≤"],["at least","≥"],["at most","≤"],["greater than",">"],["more than",">"],["less than","<"],["not equal to","≠"],["equal to","="]],Ke="[<>≤≥=≠≈]",et=[["is non-negative","≥ 0"],["is nonnegative","≥ 0"],["is not negative","≥ 0"],["is non-positive","≤ 0"],["is nonpositive","≤ 0"],["is not positive","≤ 0"],["is positive","> 0"],["is negative","< 0"],["is non-zero","≠ 0"],["is nonzero","≠ 0"],["is not zero","≠ 0"],["is zero","= 0"],["is a whole number","∈ ℤ"],["is an integer","∈ ℤ"],["is not an integer","∉ ℤ"],["is a natural number","∈ ℕ"],["is a real number","∈ ℝ"],["is real","∈ ℝ"],["is a rational number","∈ ℚ"],["is rational","∈ ℚ"]];const tt=G([[" And "," & "],[" Or "," ∨ "],[" Not In "," ∉ "],[" Nor "," \\nor "],[" Xor "," \\xor "],[" Nand "," \\nand "],[" In "," ∈ "],[" Mod "," \\mod "],[" % ","%"],[" Perm ","\\perm "],[" P ","\\perm",!0],[" Comb ","\\comb "],[" C ","\\comb",!0],[" choose ","\\comb "],["! ","!_"],["\\in ","∈"],["\\notin ","∉"],["\\not\\in ","∉"],["\\to ","→"],["===","=...="]]),nt=G([["Math.atan2","atan2"],["Math.atan2(","atan2("],["atan2","atan2"],["\\atan2","atan2"],["Math.random()","random(1)"],["random.random()","random(1)"],["Math.log2(","log_{2}("],["Math.log10(","log_{10}("],["Math.log_{","log_{"],["Math.log","log_{e}"],["Math.ln","log_{e}"],["Math.abs(","abs("],["Math.fabs(","abs("],["Math.gcd(","gcd("],["Math.comb(","comb("],["Math.perm(","perm("],["Math.fmod(","mod("],["Math.exp(","(e)^("],["Math.exp2(","(2)^("],["Math.expm1(","expm1("],["Math.pow(","pow("],["**","^"],["Math.floor(","floor("],["Math.ceil(","ceil("],["Math.round(","round("],["Math.max(","max("],["Math.min(","min("],["Math.pi","π"],["Math.PI","π"],["math.Pi","π"],["Math.e","e"],["math.E","e"],["Math.sqrt2","sqrt(2)"],["Math.sqrt(","sqrt("],["Math.SQRT1_2","sqrt(1/2)"],["Math.SQRT1_{2}","sqrt(1/2)"],["Math.SQRT2","sqrt(2)"],["cbrt","sqrt[3]"],["Math.cbrt","sqrt[3]"],["Sqrt","sqrt"],["Root","sqrt"],["\\sqrt{","sqrt{"],["\\frac","frac"],["\\dfrac","frac"],["\\tfrac","frac"],["\\lim","lim"],["\\sum","\\sumidx"],["\\prod","\\prodidx"],["\\displaystyle",""],["\\textstyle",""],["\\,",""],["\\;",""],["\\!",""],["\\quad",""],["\\qquad",""],["\\lvert","|"],["\\rvert","|"],["\\vert","|"],["^\\prime","′"],["^{\\prime}","′"],["^{\\prime\\prime}","′′"],["\\prime","′"],["\\approx","≈"],["\\varepsilon","ε"],["\\vartheta","θ"],["\\varphi","φ"],["\\cup","∪"],["\\mathbb{R}","ℝ",!0],["\\mathbb{N}","ℕ",!0],["\\mathbb{Z}","ℤ",!0],["\\mathbb{Q}","ℚ",!0],["\\mathbb{C}","ℂ",!0],["\\cap","∩"],["\\barwedge","\\nand"],["∧","&"],["¬","!"],["↑","\\nand"],["↓","\\nor"],["\\downarrow","\\nor"],["∫","\\int"],["∑","\\sum"],["∏","\\prod"],["asin(","arcsin("],["acos(","arccos("],["atan(","arctan("],["asinh(","arcsinh("],["acosh(","arccosh("],["atanh(","arctanh("],["\\sqrt*","sqrt"],["Log","log"],["Max","max"],["Min","min"],["Floor","floor"],["Ceil","ceil"],["Round","round"],["Abs","abs"],["Sum","sum"],["Prod","prod"],["Mean","mean"],["Avg","mean"],["Average","mean"],["Gcd","gcd"],["Math.LOG2e","log_{2}(e)"],["Math.LOG10e","log_{10}(e)"],["Math.LN2","log_{e}(2)"],["Math.LN10","log_{e}(10)"],["Math.tau","τ"],["infinity","∞"],["\\infty","∞"],["\\cdot","*"],["\\times","*"],["×","*"],["·","*"],["÷","/"],["->","→"],["\\to","→"],["\\max","max"],["\\min","min"],["product(","prod("],["log[","log_["],["\\log[","log_["],["\\log_","log_"],["\\log","log_{e}"],["\\ln","log_{e}"],["log(","log_{e}("],["ln(","log_{e}("],["log2(","log_{2}("],["log3(","log_{3}("],["log4(","log_{4}("],["log5(","log_{5}("],["log6(","log_{6}("],["log7(","log_{7}("],["log8(","log_{8}("],["log9(","log_{9}("],["log10(","log_{10}("],["log_10","log_{10}"],["\\log2(","log_{2}("],["\\log3(","log_{3}("],["\\log4(","log_{4}("],["\\log5(","log_{5}("],["\\log6(","log_{6}("],["\\log7(","log_{7}("],["\\log8(","log_{8}("],["\\log9(","log_{9}("],["\\log10(","log_{10}("],["\\log_10","log_{10}"],["log2{","log_{2}{"],["log3{","log_{3}{"],["log4{","log_{4}{"],["log5{","log_{5}{"],["log6{","log_{6}{"],["log7{","log_{7}{"],["log8{","log_{8}{"],["log9{","log_{9}{"],["log10{","log_{10}{"],["\\log2{","log_{2}{"],["\\log3{","log_{3}{"],["\\log4{","log_{4}{"],["\\log5{","log_{5}{"],["\\log6{","log_{6}{"],["\\log7{","log_{7}{"],["\\log8{","log_{8}{"],["\\log9{","log_{9}{"],["\\log10{","log_{10}{"],["\\log_10","log_{10}"],["\\log\\log","\\loglog"],["\\log\\log\\log","\\logloglog"],["\\loglog","\\loglog"],["\\logloglog","\\logloglog"],["loglog(","loglog("],["\\exp","e^"],["exp(","e^("],["\\div","/"],["\\int","\\int"],["\\in","∈"],["\\not\\in","∉"],["\\notin","∉"],["\\nor"," \\nor "],["\\xor"," \\xor "],["\\nand"," \\nand "],["\\uparrow"," \\nand "],["\\downarrow"," \\nor "],["\\oplus"," \\xor "],["\\lor","∨"],["\\land","&"],["Not"," \\not "],["&&","&"],["\\neg"," \\not "],["\\not"," \\not "],["\\rightarrow","→"],["\\limits_","_"],["\\pmod"," pmod "],["\\equiv","≡"],["\\mod"," mod "],["\\bmod"," mod "],["\\pm","±"],["\\plusmn","±"],["\\neq","≠"],["\\ne","≠"],["!==","≠="],["==","="],["=...=","==="],["!=","≠"],["\\gt",">"],["\\lt","<"],["\\ge","≥"],["\\geq","≥"],[">=","≥"],["\\le","≤"],["\\leq","≤"],["<=","≤"],["<>","≠"],["\\lparen","("],["\\rparen",")"],["\\left(","("],["\\right)",")"],["\\left[","["],["\\right]","]"],["\\left{","{"],["\\right}","}"],["\\left\\{","{"],["\\{","{"],["\\}","}"],["\\right\\}","}"],["\\left|","|"],["\\right|","|"],["\\lfloor","⌊"],["\\rfloor","⌋"],["\\lceil","⌈"],["\\rceil","⌉"],["ceiling(","ceil("],["√","sqrt"],["²","^2"],["³","^3"],["⁴","^4"],["⁵","^5"],["⁶","^6"],["⁷","^7"],["⁸","^8"],["⁹","^9"],["⁰","^0"],["¹","^1"],["ⁿ","^n"],["⁻¹","^{-1}"],["⁻²","^{-2}"],["⁻³","^{-3}"],["∛","sqrt[3]"],["∜","sqrt[4]"],["½","(1/2)"],["⅓","(1/3)"],["⅔","(2/3)"],["¼","(1/4)"],["¾","(3/4)"],["⅛","(1/8)"],["⅜","(3/8)"],["⅝","(5/8)"],["⅞","(7/8)"],["⊕"," \\xor "],["∞","∞"],["⋅","*"],["−","-"],["\\wedge","&"],["∨","∨"],["\\vee","∨"],["\\Pi","Π",!0],["\\Alpha","Α",!0],["\\Beta","Β",!0],["\\Gamma","Γ",!0],["\\Delta","Δ",!0],["\\Delta ","Δ",!0],["\\Epsilon","Ε",!0],["\\Zeta","Ζ",!0],["\\Eta","Η",!0],["\\Theta","Θ",!0],["\\Iota","Ι",!0],["\\Kappa","Κ",!0],["\\Lambda","Λ",!0],["\\Mu","Μ",!0],["\\Nu","Ν",!0],["\\Xi","Ξ",!0],["\\Omicron","Ο",!0],["\\Rho","Ρ",!0],["\\Sigma","Σ",!0],["\\Tau","Τ",!0],["\\Upsilon","Υ",!0],["\\Phi","Φ",!0],["\\Chi","Χ",!0],["\\Psi","Ψ",!0],["\\Omega","Ω",!0],["\\pi","π",!0],["\\alpha","α",!0],["\\beta","β",!0],["\\gamma","γ",!0],["\\delta","δ",!0],["\\epsilon","ε",!0],["\\zeta","ζ",!0],["\\eta","η",!0],["\\theta","θ",!0],["\\iota","ι",!0],["\\kappa","κ",!0],["\\lambda","λ",!0],["\\mu","μ",!0],["\\nu","ν",!0],["\\xi","ξ",!0],["\\omicron","ο",!0],["\\rho","ρ",!0],["\\sigma","σ",!0],["\\tau","τ",!0],["\\upsilon","υ",!0],["\\phi","φ",!0],["\\chi","χ",!0],["\\psi","ψ",!0],["\\omega","ω",!0],...function(){const e=[],t=(t,n)=>{e.push([t,n],[t+"(",n+"("])};for(const n of["sin","cos","tan","cot","csc","sec"])if(e.push(["Math."+n+"(",n+"("],["\\"+n+"(",n+"("],["\\"+n,n]),["sin","cos","tan"].includes(n))for(const e of["","h"]){const r=n+e,s="arc"+n+e;e&&(t("Math."+r,r),t("\\"+r,r));for(const n of["^-1","^{-1}","-1"])t("\\"+r+n,s),t(r+n,s),e||t("Math."+r+n,s);e||t("\\a"+r,s),t("\\arc"+r,s),t("Math.a"+r,s),t("Math.arc"+r,s)}return e}()]),rt=[["code",function(e){return/^\s*=|[(.%^<_eE]|\|\||\bif\b|\b(?:True|False|None|TRUE|FALSE|NULL)\b/.test(e)?(/^\s*=(?!=)/.test(e)&&(e=function(e){const t="(?:[\\p{L}_][\\p{L}\\p{N}_.]*|\\d+(?:\\.\\d+)?|§\\d+§)";e=(e=(e=e.replace(/^\s*=/,"").replace(/(?<![\w.])_xlfn\./g,"")).replace(/&/g,"+")).replace(new RegExp(`(^|[(,=<>*/+^-]\\s*)-\\s*(${t})(?=\\s*\\^)`,"gu"),"$1(-$2)");for(let n=!0;n;){const r=e;n=(e=e.replace(new RegExp(`(^|[^\\p{L}\\p{N}_.)§])(${t}\\s*\\^\\s*${t})(?=\\s*\\^)`,"u"),"$1($2)"))!==r}return Oe(e,/(?<![\w.])([A-Z][A-Z0-9]*(?:\.[A-Z]+)?)\s*\(/g,(e,t)=>Te[t[1]]?.(e)||null)}(e)),e=function(e){e=Oe(e,Ee("quad"),(e,t,n)=>{const r=/^lambda\s+(\w+)\s*:\s*(.*)$/s.exec(e[0]??"");if(!r||3!==e.length)return null;const s=/^\s*\[\s*0\s*\]/.exec(n);return[`int(${r[2]}, ${r[1]}, ${e[1]}, ${e[2]})`,s?s[0].length:0]}),e=Oe(e,Ee(Object.keys(He).join("|")),(e,t)=>He[t[1]](e)||null);for(let t=(e=Oe(e,Ee("float"),(e,t,n)=>{const r=/^\s*\.is_integer\(\s*\)/.exec(n);return r&&1===e.length?[`((${e[0]}) ∈ ℤ)`,r[0].length]:null})).lastIndexOf(".includes(");t>=0;t=t>0?e.lastIndexOf(".includes(",t-1):-1){const n=t+9,r=Se(e,n);let s=t;if(Ne.includes(e[t-1])){let n=0;for(s=t-1;s>=0;s--)if(Ne.includes(e[s]))n++;else if(Me.includes(e[s])&&0===--n)break}else for(;s>0&&/[\w.]/.test(e[s-1]);)s--;r<0||s<0||s===t||(e=`${e.slice(0,s)}((${e.slice(n+1,r)}) ∈ ${_e(e.slice(s,t))})${e.slice(r+1)}`)}return e}(e=Ze(e=ze(e=(e=(e=function(e){for(const[t,n]of Object.entries(qe))for(let r=e.lastIndexOf(n);r>=0;r=r>0?e.lastIndexOf(n,r-1):-1){const s=r+n.length,i="("===e[s]?Se(e,s):-1;if(i<0)continue;let o=e.slice(s+1,i);"gcd"===t&&(o=o.trim().replace(/^\[|\]$/g,""));const a="factorial"===t?`((${o})!)`:`${t}(${o})`;e=e.slice(0,r)+a+e.slice(i+1)}for(let t=e.lastIndexOf(").toFixed(");t>=0;t=t>0?e.lastIndexOf(").toFixed(",t-1):-1){const n=t+10-1,r=Se(e,n),s=e.lastIndexOf("Number(",t);r<0||s<0||Se(e,s+7-1)!==t||(e=e.slice(0,s)+`fixed(${e.slice(s+7,t)}, ${e.slice(n+1,r)})`+e.slice(r+1))}return e.replace(/\(\(\)=>\{let (sum|prod) = [01]; let loopCount = 0; for \(let (\w+)=(.*?);\2<=(.*?);\2\+\+\) \{if \(loopCount\+\+ > 1000000\)\{break\};\1 [+*]= (.*?);\}; return \1;\}\)\(\)/g,(e,t,n,r,s,i)=>`(\\${"sum"===t?"sum":"prod"}_{${n}=${r}}^{${s}} (${i}))`)}(e)).replace(/(?<![\w.])9e999\b/g,"∞")).replace(/(?<![\w.])(\d+(?:\.\d+)?)[eE]([+-]\d+)(?![\w.])/g,"($1*10^{$2})")))),e=function(e){for(let t=0;t<50;t++){let t=!0;for(const n of e.matchAll(/\bif\b/g)){const r=n.index;let s=0,i=-1,o=e.length;for(let t=r+2;t<e.length;t++)if(Me.includes(e[t]))s++;else{if(Ne.includes(e[t])&&--s<0){o=t;break}if(0===s&&","===e[t]){o=t;break}if(0===s&&/^then\b/.test(e.slice(t))&&/\W/.test(e[t-1])){i=-2;break}0===s&&i<0&&/^else\b/.test(e.slice(t))&&/\W/.test(e[t-1])&&(i=t)}if(i<0)continue;s=0;let a=0;for(let t=r-1;t>=0;t--)if(Ne.includes(e[t]))s++;else{if(Me.includes(e[t])&&--s<0){a=t+1;break}if(0===s&&","===e[t]){a=t+1;break}}const l=e.slice(a,r).trim();if(!l)continue;const u=`((${e.slice(r+2,i).trim()}) ? (${l}) : (${e.slice(i+4,o).trim()}))`;e=e.slice(0,a)+u+e.slice(o),t=!1;break}if(t)return e}return e}(e),(e=(e=e.replace(/\b(?:True|TRUE)\b/g,"true").replace(/\b(?:False|FALSE)\b/g,"false").replace(/\b(?:None|NULL)\b/g,"null")).replace(/\^\^/g," \\xor ")).replace(/%(?=\s*(?:[(-]|[A-Za-z_][\w.]*\s*\())/g," \\mod ")):e}],["english",function(e){if(!/[A-Za-z]{2}/.test(e))return e;let t=e;const n=(e,n,r,s="∈")=>{t=t.replace(new RegExp(String.raw`(?<![\w.])${Qe(e)}\s+(${Xe})\s+(?:and|to)\s+(${Xe})(?:\s+(inclusive|exclusive))?(?![\w.])`,"gi"),(e,t,i,o)=>{const[a,l]="exclusive"===o?.toLowerCase()?["(",")"]:"inclusive"===o?.toLowerCase()?["[","]"]:[n,r];return` ${s} ${a}${t}, ${i}${l} `})};n("is not strictly between","(",")","∉"),n("is not between","[","]","∉"),n("is strictly between","(",")"),n("is between","[","]"),n("between","[","]"),t=t.replace(new RegExp(String.raw`(?<![\w.])is\s+(not\s+)?in\s+the\s+(open|closed|half-open)\s+interval\s+from\s+(${Xe})\s+to\s+(${Xe})`,"gi"),(e,t,n,r,s)=>{const[i,o]={open:["(",")"],closed:["[","]"],"half-open":["[",")"]}[n.toLowerCase()];return` ${t?"∉":"∈"} ${i}${r}, ${s}${o} `});const r=String.raw`(${Xe})\s+`;t=t.replace(new RegExp(r+String.raw`is\s+(not\s+)?within\s+(${Xe})\s*(%|\s+percent)?\s+of\s+(${Xe})`,"gi"),(e,t,n,r,s,i)=>`(abs((${t}) - (${i})) ${n?">":"≤"} ${s?`(${r})/100 * ${/^\d+(\.\d+)?$/.test(i)?i:`abs(${i})`}`:`(${r})`})`),t=t.replace(new RegExp(r+String.raw`is\s+(?:a\s+)?multiple\s+of\s+(${Xe})`,"gi"),"(($1) mod ($2) = 0)"),t=t.replace(new RegExp(r+String.raw`is\s+(not\s+)?divisible\s+by\s+(${Xe})`,"gi"),(e,t,n,r)=>`((${t}) mod (${r}) ${n?"≠":"="} 0)`),t=t.replace(new RegExp(String.raw`(${Xe})\s+divides\s+(${Xe})`,"gi"),"(($2) mod ($1) = 0)"),t=t.replace(new RegExp(r+String.raw`is\s+(not\s+)?(even|odd)(?![\w.])`,"gi"),(e,t,n,r)=>`((${t}) mod 2 ${"even"===r.toLowerCase()!==Boolean(n)?"=":"≠"} 0)`);for(const[e,n]of et)t=t.replace(Je(e),` ${n} `);t=t.replace(Je("is not in")," ∉ ").replace(Je("is in")," ∈ ").replace(Je("is an element of")," ∈ ");for(const[e,n]of Ye)t=t.replace(Je(e),` ${n} `);t=t.replace(Je("is not")," ≠ "),t=t.replace(/(?<=[\w.)\]}′]\s+)is(?=\s+[\w.(\[{-])/gi," = ");for(let e=!0;e;){const n=t;t=t.replace(new RegExp(String.raw`(${Xe})\s*(${Ke})\s*(${Xe})\s+(and|or)\s+(${Ke})`,"gi"),"$1 $2 $3 $4 $1 $5"),e=t!==n}t=t.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?absolute\s+value\s+of\s+(${Xe})`,"gi"),"abs($1)"),t=t.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?square\s+root\s+of\s+(${Xe})`,"gi"),"sqrt($1)"),t=t.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?cube\s+root\s+of\s+(${Xe})`,"gi"),"root(3, $1)"),t=t.replace(new RegExp(String.raw`(${Xe})\s+to\s+the\s+power\s+of\s+(${Xe})`,"gi"),"($1)^($2)");const s={second:2,third:3,fourth:4,fifth:5,sixth:6,seventh:7,eighth:8,ninth:9,tenth:10};t=t.replace(new RegExp(String.raw`(${Xe})\s+to\s+the\s+(${Object.keys(s).join("|")}|(\d+|n)(?:st|nd|rd|th))(?:\s+power)?(?![\w.])`,"gi"),(e,t,n,r)=>`(${t})^(${s[n.toLowerCase()]??r})`),t=t.replace(new RegExp(String.raw`(${Xe})\s+to\s+the\s+(${Xe})(?![\w.])`,"gi"),"($1)^($2)");const i={sine:"sin",cosine:"cos",tangent:"tan",secant:"sec",cosecant:"csc",cotangent:"cot","natural log":"ln","natural logarithm":"ln",arcsine:"arcsin",arccosine:"arccos",arctangent:"arctan","hyperbolic sine":"sinh","hyperbolic cosine":"cosh","hyperbolic tangent":"tanh",floor:"floor",ceiling:"ceil"};for(const[e,n]of Object.entries(i).sort((e,t)=>t[0].length-e[0].length))t=t.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?${Qe(e)}\s+of\s+(${Xe})`,"gi"),`${n}($1)`);t=t.replace(new RegExp(String.raw`(${Xe})\s+squared(?![\w.])`,"gi"),"($1)^2"),t=t.replace(new RegExp(String.raw`(${Xe})\s+cubed(?![\w.])`,"gi"),"($1)^3"),t=t.replace(new RegExp(String.raw`(?<![\w.])half\s+of\s+(${Xe})`,"gi"),"($1)/2"),t=t.replace(new RegExp(String.raw`(?<![\w.])twice\s+(${Xe})`,"gi"),"2*($1)"),t=t.replace(new RegExp(String.raw`(\d+(?:\.\d+)?)\s+percent(?![\w.])`,"gi"),"$1%");const o=e=>new RegExp(String.raw`(?<=[\w.′)\]}]\s+)${Qe(e)}(?=\s+[\w.(\[{-])`,"gi");for(const[e,n]of[["divided by","/"],["over","/"],["multiplied by","*"],["times","*"],["plus","+"],["minus","-"],["modulo","mod"]])t=t.replace(o(e),` ${n} `);return t}],["words",tt],["spaced",function(e){e=function(e){for(let t=0;t<100;t++){const t=[...e.matchAll(/\bif\b/gi)];if(!t.length)return e;const n=t[t.length-1].index,r=ne(e,n+2,"then");if(r<0)return e;const s=e.slice(n+2,r),i=ne(e,r+4,"else"),o=re(e,i<0?r+4:i+4),a=e.slice(r+4,i<0?o:i),l=i<0?"unchanged":e.slice(i+4,o).trim();e=`${e.slice(0,n)}((${s.trim()}) ? (${a.trim()}) : (${l}))${e.slice(o)}`}return e}(e),e=function(e){for(let t=0;t<e.length;t++){const n=n=>e.slice(Math.max(0,t-n),t+1);if("t"===e[t]&&"\\text"===n(4)&&"{"===e[t+1]){let n=1,r=t+2,s="";for(;n>0&&r<e.length;)"{"===e[r]?n++:"}"===e[r]?n--:s+=e[r],r++;e=e.slice(0,t-4)+s+e.slice(r)}}return e}(e=(e=e.replace(/\(\s*\\?b?mod\s+([^()]+?)\s*\)/g," \\pmod{$1}")).replace(/(^|[^A-Za-z\\])lim\s+([^\s_{}]+?)\s*(->|→|\\to)\s*([^\s]+)\s+/g,"$1lim_{$2→$4} ")),e=ie(e);for(let t=0;t<e.length-1;t++)if("?"===e[t]&&":"!==e[t+1])e=se(e,t);else if("_"===e[t]||"^"===e[t]){const n=/^§\d+§/.exec(e.slice(t+1));if(n){e=`${e.slice(0,t+1)}{${n[0]}}${e.slice(t+1+n[0].length)}`;continue}let r=t+1;for("-"===e[r]&&r++;r<e.length&&".0123456789".includes(e[r]);)r++;r===t+2&&"-"===e[t+1]&&(r=t+1),r>t+1&&(e=e.slice(0,t+1)+"{"+e.slice(t+1,r)+"}"+e.slice(r))}return e}],["squeeze",function(e){return e.replace(/\s+/g,(t,n)=>{const r=e[n-1]??"",s=e[n+t.length]??"";return"Δ"===r?"":/[A-Za-z\u0370-\u03FF′]/.test(r)&&/[A-Za-z\u0370-\u03FF]/.test(s)?" ":""})}],["symbols",nt],["compact",function(e){e=function(e){for(let t=e.indexOf(")′");t>=0;t=e.indexOf(")′",t+1)){let n=0,r=-1;for(let s=t;s>=0;s--)if(")"===e[s])n++;else if("("===e[s]&&0===--n){r=s;break}if(r<0)continue;for(;r>0&&/[A-Za-z\u0370-\u03FF′]/.test(e[r-1]);)r--;let s=0;for(;"′"===e[t+1+s];)s++;e=e.slice(0,r)+ve(e.slice(r,t+1),"x",s)+e.slice(t+1+s),t=r}return e}(e=(e=ie(e)).replace(/(?<![A-Za-z])frac(\d)(\d)/g,"frac{$1}{$2}")),e=function(e){for(let t=0;t<e.length;t++){const n=t>0&&fe.test(e[t-1]);let r,s=null,i=t;if(e.startsWith("frac{",t)){const n=me(e,t+4),r=n&&me(e,n[1]);s=r&&ge(n[0],r[0]),s&&(i=r[1])}else if("d"===e[t]&&!n){let[n,r]=de(e,t+1),o="";if(fe.test(e[r]??"")&&"/"===e[r+1]&&(o=e[r++]),"/"===e[r]&&"d"===e[r+1]&&fe.test(e[r+2]??"")){const t=e[r+2],[,a]=de(e,r+3);s={n:n,of:o,by:t},i=a}}if(s){if(s.of)r=ve(s.of,s.by,s.n);else{const[t,n]=be(e,i);if(!t)continue;r=ve(t,s.by,s.n),i=n}e=e.slice(0,t)+r+e.slice(i),t+=3}}return e}(e);for(let t=0;t<e.length;t++){const n=e[t],r=n=>e.slice(Math.max(0,t-n),t),s=n=>e.slice(Math.max(0,t-n),t+1);if("{"===n){if("\\begin"===r(6)){const n=le(e.slice(t+1));n&&(e=e.slice(0,t-6)+n)}}else if("["===n)"\\sqrt"===r(5)?e=e.slice(0,t-5)+"sqrt"+ae(e.slice(t+1)):"sqrt"===r(4)&&(e=e.slice(0,t-4)+"sqrt"+ae(e.slice(t+1)));else if("⌊"===n||"⌈"===n)e=e.slice(0,t)+oe(e.slice(t));else if("t"===n)"\\int"===s(3)&&(e=e.slice(0,t-3)+ce(e.slice(t+1)));else if("m"===n)"\\binom"===s(5)&&(e=e.slice(0,t-5)+"\\binom"+pe(e.slice(t+1)));else if("d"===n&&"dd"===s(1)&&"("===e[t+2]){const n=he(e.slice(t+1));n&&(e=e.slice(0,t-1)+"der"+n)}}return e.replace(/\\log/g,"log")}],["tidy",e=>e.replace(/ {2,}/g," ").trim()]];function st(e,t={}){if("string"!=typeof e)throw new Error("Expression must be a string");const{text:n,strings:r}=function(e){const t=new Map;let n="",r=0;for(;r<e.length;){const s=e[r];if('"'!==s&&"'"!==s&&"`"!==s){n+=e[r++];continue}let i=r+1,o="",a=!1;for(;i<e.length&&(a||e[i]!==s);)a=!a&&"\\"===e[i],o+=e[i++];const l=xe(t.size);t.set(l,s+o+s),n+=l,r=i+1}return{text:n,strings:t}}(function(e){let t="";for(let n=0;n<e.length;n++){const r=e[n];if('"'===r||"`"===r){const r=$e(e,n);t+=e.slice(n,r+1),n=r}else if("'"===r)if(/[A-Za-z0-9)\]′\u0370-\u03FF]/.test(t[t.length-1]??""))t+="′";else{const r=$e(e,n);t+=e.slice(n,r+1),n=r}else t+=r}return t}(e));let s=n.replace(/\t/g," ");t.evaluate&&(s=function(e,t,n){let r=0;for(;;){const s=e.indexOf("{{",r);if(s<0)return e;const i=it(e,s);if(i<0)return e;let o=e.slice(s+2,i).trim();for(const[e,n]of t)o=o.split(e).join(n);try{let a=n(o);if(/^["'`]/.test(a)){const e=xe(t.size);t.set(e,a),a=e}const l=e.slice(0,s).trimEnd(),u=e.slice(i+2).trimStart();/^[\d.]/.test(a)&&(/[\d.]$/.test(l)||/^[\d.]/.test(u))&&(a=`(${a})`),e=e.slice(0,s)+" "+a+" "+e.slice(i+2),r=0}catch{r=i+2}}}(s,r,t.evaluate));const i=[["strings",s]];for(const[e,t]of rt){if(s=t(s),s.length>1e5)throw new Error("The expression expands too much when read");i.push([e,s])}return{cleaned:s,stringMap:r,steps:i}}function it(e,t){let n=0;for(let r=t+2;r<e.length;r++){if(e.startsWith("}}",r)&&0===n)return r;"{"===e[r]?n++:"}"===e[r]&&n--}return-1}const ot=Object.keys(p).filter(e=>100===p[e]&&/^[a-z]{2,}$/.test(e)),at=["frac"],lt=[...Object.keys(O),"pi","tau","inf","infinity","exp"],ut="\n cost costs coast cosine cosines cosy sine sines since sincere sinus single\n tank tanks tango stand stank\n point points print prints paint paints pint pints mint hint hints lint tint saint faint joint into\n spin spine pipe pipes pine pines pick picks pink pity pie pies pilot pivot pixel pizza piano\n order orders under wonder border render older elder ladder cider rider wider bidder\n logic logo logs blog clog login slog\n model models mode modes modal modest modern module modules\n limb limbs slim lime limo limit limits climb\n maxi minute minutes mince mind mine mines\n sums sumo summit rounds floors ceils means meant sect sects secs expo kiln\n meta metal metals taxi must mute muse nut nuts\n".trim().split(/\s+/),ct=new Set([...lt,...ut,"true","false","null","undefined","deg","mod","pmod","NaN","Infinity"]),ht=/^[a-zA-ZͰ-Ͽ]$/,pt=new Set(["f","g","h","u","v","F","G","H"]),ft=e=>ot.includes(e)||at.includes(e),mt=[...ot,...at,...lt].sort((e,t)=>t.length-e.length),dt=[...ot,...at,"pi"].sort((e,t)=>t.length-e.length);function gt(e,t=mt){const n=[];let r=0;for(;r<e.length;){const s=t.find(t=>e.startsWith(t,r))??e[r];n.push(s),r+=s.length}return n}function bt(e){if(ft(e))return!0;const t=gt(e,dt);return t.length>1&&ft(t[t.length-1])&&!ct.has(e)}function vt(e,{mode:t="plain",followed:n=!0}={}){if(e.includes("′")&&/^[a-zA-Z′]+$/.test(e)&&!/^.′+$/.test(e))return e.match(/[a-zA-Z]′*/g);if(!((r=e).length>0&&[...r].every(e=>ht.test(e)))||1===e.length||ct.has(e)||ft(e))return[e];var r;if("Δ"===e[0]&&2===e.length)return[e];if("latex"===t)return yt(gt(e),n);if(e.length<=2)return[...e];const s=yt(gt(e,dt),n),i=s.findIndex(e=>e.length>1);if(i<0)return[e];if("pi"===s[i]&&!s.some(e=>ot.includes(e)))return 3===e.length?s:[e];const o=i;let a=0,l=0;for(const e of s.slice(i))a=1===e.length?a+1:0,l=Math.max(l,a);return o<=1&&l<=2?s:[e]}function yt(e,t){const n=e[e.length-1];return t||!ot.includes(n)?e:[...e.slice(0,-1),...n]}const wt="§",xt=/[A-Za-zͰ-Ͽ′]/,$t=e=>/^[A-Za-zͰ-Ͽ][A-Za-zͰ-Ͽ′]*$/.test(e);function kt(e,t="plain"){if("string"!=typeof e)throw new Error("Tokenizer input must be a string");const n=[];let r="";const s=e=>{r&&($t(r)?n.push(...function(e,t,n){if((e=>new RegExp(`^${ye}[${we}]+$`).test(e))(e))return[e];if(d.includes(t))return function(e,t){if(/^[a-zA-Z]′+$/.test(e))return[i+e];if("if"===e.toLowerCase())return["\\:if"];if(1===e.length)return pt.has(e)?[i+e]:[e];if(f(e))return[e];const n=vt(e,{mode:t,followed:!0});return n.length>1?n:e.length<=2?[...e]:[i+e]}(e,n);const r=void 0!==t&&!/[+\-*/=<>),\]}|!≤≥≠]/.test(t);return vt(e,{mode:n,followed:r})}(r,e,t)):n.push(r),r="")};for(let t=0;t<e.length;t++){const o=e[t];if(o===wt){s(o);const r=e.indexOf(wt,t+1),a=e.slice(t,r+1);n.push(d.includes(e[r+1])?i+a:a),t=r;continue}if($t(r)&&/[0-9]/.test(o)&&f(r+o)){const{op:s,end:i}=qt(e,t,r+o);n.push(s),r="",t=i;continue}if(xt.test(o)&&"′"!==o&&b(r)&&(n.push(r),r=""),xt.test(o)&&(""===r?"′"!==o:$t(r)))r+=o;else if(/[0-9]/.test(o)&&$t(r)&&!bt(r))r+=o;else if($t(r)&&s(" "===o?e[t+1]:o),"(){}[]".includes(o))r&&n.push(...Mt(r,o)),r="",n.push(o);else if("_"!==o&&" "!==o){if(f(r+o)){const{op:s,end:i}=qt(e,t,r+o);n.push(s),r="",t=i;continue}if(f(o)){s(o);const{op:r,end:i}=qt(e,t,o);n.push(r),t=i;continue}r+=o}else s(e[t+1]),"_"===o&&n.push("_")}if(s(void 0),n.some(e=>/^:/.test(e)))throw new Error("Unmatched ':'");return n}function qt(e,t,n){let r=t;for(;r+1<e.length&&f(n+e[r+1]);)n+=e[r+1],r++;return"!"===n&&"_"===e[r+1]&&r++,{op:n,end:r}}function Mt(e,t){if(!d.includes(t))return[e];if("\\"===e[0]){const t=e.slice(1);return[f(t)?t:i+t]}return b(e)?[e,"*"]:f(e)||ft(e)||b(e[0])?[e]:[i+e]}const Nt=70,St=100,At="%mod",Ot=e=>d.includes(e),Et=e=>g.includes(e),It=e=>o(e)||p[e]===St&&"_"!==e,_t=new Set(["\\comb","\\perm","comb","perm"]),Tt={frac:"/","\\binom":"\\binom"},jt={"\\comb":"comb","\\perm":"perm",deg:"°","π":"pi","∨":"|"};class Ct{constructor(e){this.tokens=e,this.pos=0,this.out=[],this.absDepth=0,this.frames=[]}peek(e=0){return this.tokens[this.pos+e]}next(){return this.tokens[this.pos++]}emit(...e){this.out.push(...e)}parseAll(){if(!this.tokens.length)throw new Error("Empty expression");this.parseExpression(0);const e=this.peek();if(void 0!==e)throw new Error(Et(e)?`Unmatched '${e}'`:`Unexpected '${e}'`);return this.out}parseExpression(e,t=!1){for(this.parseOperand();;){const n=this.peek();if(void 0===n||Et(n))return;const r=this.operatorAt(n,t);if(!r||r.lbp<=e)return;r.run()}}operatorAt(e,t){if("|"===e)return this.pipe();if(","===e)return{lbp:5,run:()=>{this.next(),this.frames.length&&(this.frames[this.frames.length-1].comma=!0),this.parseExpression(5),this.emit(",")}};if("?"===e)return{lbp:9,run:()=>this.ternary()};if("mod"===e)return{lbp:p.mod,run:()=>this.modulo()};if(e===At)return{lbp:Nt,run:()=>{this.next(),this.parseExpression(Nt),this.emit("mod")}};if("pmod"===e)return{lbp:p.pmod,run:()=>{this.next(),this.parseScript(),this.emit("pmod")}};if("?:"===e)return{lbp:10,run:()=>{throw new Error("Unmatched ':'")}};if("!"===e)return{lbp:90,run:()=>{this.next(),this.emit("!")}};if("_"===e)return{lbp:St,run:()=>{this.next(),this.parseScript(),this.emit("_")}};if(_t.has(e))return{lbp:St,run:()=>{this.next(),this.parseExpression(St),this.emit(e)}};const n=p[e];if(void 0!==n&&!It(e)&&"\\not"!==e&&!(e in Tt)){const t=m.has(e)?n-1:n;return{lbp:n,run:()=>{this.next(),this.parseExpression(t),this.emit(e)}}}return this.startsOperand(e)?this.implicit(e,t):null}implicit(e,t){return{lbp:t&&!It(e)?71:Nt,run:()=>{this.parseExpression(Nt),this.emit("*")}}}startsOperand(e){return void 0===e||Et(e)||"|"===e?"|"===e:e!==At&&(!!(Ot(e)||It(e)||e in Tt)||!f(e))}pipe(){if(this.absDepth>0)return null;let e=0;for(let t=this.pos;t<this.tokens.length;t++)"|"===this.tokens[t]&&e++;const t="|"===this.peek(1);return e%2==0&&!t&&this.startsOperand(this.peek(1))?this.implicit("|",!1):{lbp:p["|"],run:()=>{this.next(),t&&e%2==0&&this.next(),this.parseExpression(p["|"]),this.emit("|")}}}modulo(){this.next(),this.parseExpression(Nt,!0),this.emit("mod")}ternary(){if(this.next(),this.parseExpression(10),"?:"!==this.next())throw new Error("Unmatched '?'");this.parseExpression(8),this.emit("?:")}parseOperand(){const e=this.next(),t=this.tokens[this.pos-2],n=this.peek();if(void 0===e)throw new Error("An operator is missing an operand at the end");if(Ot(e))return this.bracket(e,"{"===e&&("∈"===t||"∉"===t));if("|"===e)return this.absolute();if("-"===e||"+"===e){return"^"===t&&(void 0===n||Et(n))||Ot(t)&&Et(n)?this.emit("\\"+e):"+"===e?this.parseExpression(75):this.negate()}if("±"===e)return this.parseExpression(75),this.emit("pm");if("!"===e||"\\not"===e)return this.parseExpression(85),this.emit("\\not");if(e in Tt)return this.parseScript(),this.parseScript(),this.emit(Tt[e]);if("log"===e)return this.logarithm();if("lim"===e&&"_"===n)return this.limit();if(("\\sumidx"===e||"\\prodidx"===e)&&"_"===n)return this.bigOperator(e);if(It(e))return this.functionCall(e);if(Et(e)||f(e))throw new Error(`'${e}' is missing an operand`);this.emit(e)}negate(){const e=this.out.length;this.parseExpression(75);const t=this.out.slice(e);1!==t.length||!b(t[0])&&"∞"!==t[0]?this.emit("neg"):this.out[e]="-"+t[0]}bracket(e,t=!1){if(Et(this.peek()))return void this.emit("∅",e+this.next());this.frames.push({comma:!1}),this.parseExpression(0);const{comma:n}=this.frames.pop(),r=this.peek();Et(r)&&(this.next(),n?this.emit(e+r):t&&this.emit("{}"))}absolute(){this.absDepth++,this.parseExpression(0),this.absDepth--,"|"===this.peek()&&this.next(),this.emit("abs")}parseScript(){const e=this.peek();if(Ot(e))return this.parseOperand();if("-"===e||"+"===e)return this.parseOperand();if(It(e))return this.parseOperand();if(this.next(),void 0===e||Et(e)||f(e))throw new Error("Missing a sub- or superscript");this.emit(e)}logarithm(){"_"===this.peek()?(this.next(),this.parseScript()):this.emit("e"),this.argument(),this.emit("log")}limit(){this.next();const e=this.out.length;this.parseScript();const t=this.out.splice(e);this.parseExpression(p["+"],!0),this.emit(...t,",","()","lim")}bigOperator(e){this.next();const t=this.out.length;this.parseScript();let n=this.out.splice(t);"^"===this.peek()&&(this.next(),this.parseScript(),n=[...n,...this.out.splice(t),","]),this.parseExpression(p["+"],!0),this.emit(...n,",","()",e)}functionCall(e){if(void 0===this.peek())return this.emit(e);let t=null;if("^"===this.peek()){this.next();const e=this.out.length;this.parseScript(),t=this.out.splice(e)}if(0===a(e)?.arity&&!Ot(this.peek()))return this.emit(e);this.argument(),this.emit(e),t&&this.emit(...t,"^")}argument(){const e=this.peek();if(Ot(e))return this.next(),this.bracket(e);this.parseExpression(Nt,!0)}}function zt(e,t){e=function(e){const t=[];for(let n=0;n<e.length;n++){const r=e[n],s=e=>"string"==typeof e&&/^[a-zA-Z]$/.test(e);if(pt.has(r)&&"^ { - 1 } ("===e.slice(n+1,n+7).join(" ")){t.push(i+r+"⁻¹"),n+=5;continue}const[o,a,l]=e.slice(n+1,n+4),u=s(a)?a!==r:b(a);s(r)&&"e"!==r&&"("===o&&u&&")"===l?t.push(i+r):t.push(r)}return t}(e);const n=[];for(const r of e)f(r)||Ot(r)||Et(r)||"_"===r||o(r)||b(r)?n.push(r):n.push(...Lt(r,t));return n}function Lt(e,t){const n=e=>zt(kt(e,t),t);let r=0;for(;r<e.length&&b(e.slice(0,r+1));)r++;if(0===r){if("%"===e[0])return[At,...n(e.slice(1))];const r=e.indexOf("%");return r>0&&r<e.length-1?[...Lt(e.slice(0,r),t),At,...n(e.slice(r+1))]:[e]}const s=e.slice(r);return"%"===s[0]?1===s.length?[e]:[e.slice(0,r),At,...n(s.slice(1))]:[e.slice(0,r),...n(s)]}for(const e of[Tt,jt])Object.setPrototypeOf(e,null);const Rt=new Set(["()","[]","{}","(]","[)"]),Zt={pow:"^",sqrtpow:"root","\\binom":"comb","\\comb":"comb","\\perm":"perm",frac:"/","==":"=","!==":"≠="},Ft=new Set(["round","fixed","der"]),Bt=e=>o(e)||100===p[e];function Pt(e){const n=[],r=e=>{if(!n.length)throw new Error(`'${e}' is missing an operand`);return n.pop()},s=e=>e.list?e.list:[e],i=(e,t)=>{if(e.list)throw new Error(`A list of values needs brackets around it (near '${t}')`);return e};if(e.forEach((l,u)=>{if("∅"===l)return void n.push({list:[]});if(","===l){const e=r(l),t=r(l);return void n.push({list:[...s(t),...s(e)]})}if(Rt.has(l)){const t=s(r(l));if(!t.length&&!Bt(e[u+1]))throw new Error("Empty brackets");return void n.push(w(l,t))}const c=Zt[l]??l,h=a(c);if(!h){if("?"===l||"abs("===l)throw new Error(`Unmatched '${l[0]}'`);return void n.push($(l))}let p;if(Bt(l)&&Rt.has(e[u-1])&&n[n.length-1]?.op===e[u-1])p=n.pop().args;else{let e=h.arity===t||Ft.has(c)?1:h.arity;if(n.length<e)throw new Error(`'${l}' needs ${e} operand${1===e?"":"s"}`);p=n.splice(n.length-e,e).map(e=>i(e,l))}n.push(function(e,n){switch(e){case"sqrt":if(2===n.length)return w("root",n);break;case"round":if(1===n.length)return w("round",[n[0],v(0)]);break;case"sum":case"prod":{const t=n[1];if("op"===t?.type&&"symbol"===t.args[0]?.type&&(3===n.length&&"="===t.op||2===n.length&&"∈"===t.op))return w("sum"===e?"\\sumidx":"\\prodidx",n);break}case"fixed":if(1===n.length)return w("fixed",[n[0],v(2)]);break;case"der":if(1===n.length)return w("der",[n[0],y("x")]);if(3===n.length)return function([e,t,n]){const r="number"===n.type?Number(n.value):NaN;if(!Number.isInteger(r)||r<1||r>20)throw new Error("der(f, x, n) needs n to be a whole number from 1 to 20");let s=e;for(let e=0;e<r;e++)s=w("der",[s,t]);return s}(n);break;case"log":if("symbol"===n[0].type&&"e"===n[0].value)return w("ln",[n[1]]);break;case"lim":return w("lim",function(e){const t=e=>"op"===e.type&&"^"===e.op&&"symbol"===e.args[1].type?{"\\+":"r","\\-":"l"}[e.args[1].value]:void 0,[n,r,s]=e;if(2===e.length&&"op"===r.type&&"→"===r.op&&t(r.args[1])){const[e,s]=r.args;return[n,e,s.args[0],y(t(s))]}return 3===e.length&&t(s)?[n,r,s.args[0],y(t(s))]:e}(n));case"\\:if":if(2===n.length||3===n.length)return w("?:",[n[0],n[1],n[2]??y("unchanged")]);throw new Error("if() takes a condition, a value, and optionally an alternative")}return function(e,n){const{arity:r}=a(e);if(r===t){if(0===n.length&&!o(e))throw new Error(`'${e}' needs at least one argument`);return}if(n.length!==r){throw new Error(`'${e}' takes ${r} argument${1===r?"":"s"}, not ${n.length}`)}}(e,n),w(e,n)}(c,p))}),1!==n.length)throw new Error(n.length?"Some values are not connected by an operator":"Empty expression");return i(n[0],"end")}for(const e of[Zt])Object.setPrototypeOf(e,null);const Dt=/\\(?:text|textrm|textit|mathrm|mathit|operatorname)\{\s*([A-Za-z][A-Za-z0-9 ]*[A-Za-z0-9])\s*\}/g;const Wt=e=>/^[a-z][a-z0-9]*$/.test(e)&&f(e);function Ut(e){return e.includes("\\")?(e=function(e){for(let t=0;t<50;t++){const t=e.lastIndexOf("\\begin{cases}"),n=t<0?-1:e.indexOf("\\end{cases}",t);if(n<0)return e;const r=te(e.slice(t+13,n),"\\\\").map(e=>te(e,"&")).filter(e=>e.join("").trim());let s=null;for(let e=r.length-1;e>=0;e--){const t=r[e][0].trim(),n=ee(r[e].slice(1).join("&"));s=null!==s||n?`((${n||"true"}) ? (${t}) : ${s??"(unchanged)"})`:`(${t})`}e=e.slice(0,t)+(s??"")+e.slice(n+11)}return e}(e),e.replace(/\{\}\^\{([^{}]*)\}\s*\\mathrm\{P\}\s*_\{([^{}]*)\}/g,"\\perm($1,$2)")):e}let Vt=null;function Ht(e,t={}){const n={original:e};try{if("string"!=typeof e)throw new Error("Expression must be a string");const r=t.maxLength??5e3;if(e.length>r)throw new Error(`Longer than ${r} characters (options.maxLength)`);const s=/^\s*=(?!=)/.test(e);s&&(e=e.replace(/("(?:[^"]|"")*")|\$(?=[A-Za-z]{0,3}\d|[A-Za-z]{1,3}\$?\d)/g,(e,t)=>t??""));const i=s?[...new Set(e.replace(/"(?:[^"]|"")*"/g,"").match(/(?<![\w.])[A-Za-z]{1,3}\d+(?::[A-Za-z]{1,3}\d+)?(?![\w.(])/g)??[])]:[],{text:o,protectedNames:a}=function(e,t=[],n=[]){const r=new Map,s=e=>{const t=`${wt}${r.size}${wt}`;return r.set(t,e),t};e=e.replace(Dt,(e,t)=>Wt(t.trim())?` ${t.trim()}`:s(t.trim()));for(const n of[...t].sort((e,t)=>t.length-e.length)){const t=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");e=e.replace(new RegExp(`(?<![A-Za-z_])${t}(?![A-Za-z0-9_])`,"g"),()=>s(n))}for(const t of[...n].sort((e,t)=>t.length-e.length)){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");e=e.replace(new RegExp(`(?<![A-Za-z_])${n}(?![A-Za-z0-9_])(\\s*)(\\(?)`,"g"),(e,n,r)=>s(t)+(r?" * (":n))}return{text:e,protectedNames:r}}(Ut(e),t.names,[...t.values??[],...i]),l=(e=>/\\[A-Za-z]/.test(e)?"latex":"plain")(o),{cleaned:u,stringMap:c,steps:h}=((e,t={})=>{const n=void 0===t.blocks?Vt:t.blocks;return st(e,{evaluate:n?e=>n(e,t.scope):void 0})})(o,{blocks:t.blocks,scope:t.scope}),p=e=>ke(ke(e,c),a);n.mode=l,n.cleaned=p([u])[0],n.cleanSteps=h,n.tokens=kt(u,l),n.rawPostfix=p(function(e,t="plain"){return new Ct(zt(e,t)).parseAll().map(e=>jt[e]??e)}(n.tokens,l));const f=M(Pt(n.rawPostfix));n.postfix=f,n.tree=q(f)}catch(e){n.error=e instanceof RangeError?"Nested too deeply":e.message}return n}const Gt=e=>"string"==typeof e&&e.length>80?`${e.slice(0,77)}…`:e;function Xt(e,t={}){const n=Ht(e,t);if(n.error)throw new Error(`Failed to parse expression "${Gt(e)}": ${n.error}`);return n.tree}const Qt=(e,t)=>"string"==typeof e?Xt(e,t):N(e),Jt=e=>Array.isArray(e)&&0===e.length,Yt={pi:Math.PI,"π":Math.PI,e:Math.E,tau:2*Math.PI,"τ":2*Math.PI,"∞":1/0,"-∞":-1/0,true:!0,false:!1},Kt=(e,t)=>t?Kt(t,e%t):Math.abs(e),en={neg:e=>-e,pm:e=>[e,-e],"!":e=>{if(!Number.isInteger(e)||e<0)return NaN;if(e>170)return 1/0;let t=1;for(let n=2;n<=e;n++)t*=n;return t},"\\not":e=>!e,sqrt:Math.sqrt,abs:Math.abs,floor:Math.floor,ceil:Math.ceil,ln:Math.log,loglog:e=>Math.log(Math.log(e)),logloglog:e=>Math.log(Math.log(Math.log(e))),expm1:Math.expm1,sin:Math.sin,cos:Math.cos,tan:Math.tan,csc:e=>1/Math.sin(e),sec:e=>1/Math.cos(e),cot:e=>1/Math.tan(e),sinh:Math.sinh,cosh:Math.cosh,tanh:Math.tanh,arcsin:Math.asin,arccos:Math.acos,arctan:Math.atan,arcsinh:Math.asinh,arccosh:Math.acosh,arctanh:Math.atanh},tn={"+":(e,t)=>e+t,"-":(e,t)=>e-t,"*":(e,t)=>e*t,"/":(e,t)=>e/t,"^":(e,t)=>e**t,mod:(e,t)=>e%t,log:(e,t)=>Math.log(t)/Math.log(e),root:(e,t)=>t**(1/e),atan2:Math.atan2,round:(e,t)=>Math.round(e*10**t)/10**t,"±":(e,t)=>[e+t,e-t],fixed:(e,t)=>Number(e).toFixed(t),perm:(e,t)=>{if(!Number.isInteger(e)||!Number.isInteger(t)||t<0||t>e)return NaN;let n=1;for(let r=e-t+1;r<=e&&n!==1/0;r++)n*=r;return n},comb:(e,t)=>{if(!Number.isInteger(e)||!Number.isInteger(t)||t<0||t>e)return NaN;t=Math.min(t,e-t);let n=1;for(let r=1;r<=t&&n!==1/0;r++)n=n*(e-t+r)/r;return Math.round(n)},"=":(e,t)=>e==t,"===":(e,t)=>e===t,"≠":(e,t)=>e!=t,"≠=":(e,t)=>e!==t,"≈":(e,t)=>Math.abs(e-t)<1e-9,"≡":(e,t)=>e===t,"∪":(e,t)=>[...new Set([...[].concat(e),...[].concat(t)])],"∩":(e,t)=>[].concat(e).filter(e=>[].concat(t).includes(e)),"<":(e,t)=>e<t,">":(e,t)=>e>t,"≤":(e,t)=>e<=t,"≥":(e,t)=>e>=t,"&":(e,t)=>e&&t,"|":(e,t)=>e||t,"\\xor":(e,t)=>Boolean(e)!==Boolean(t),"\\nor":(e,t)=>!(e||t),"\\nand":(e,t)=>!(e&&t)},nn={max:e=>Math.max(...e),min:e=>Math.min(...e),sum:e=>e.reduce((e,t)=>e+t,0),prod:e=>e.reduce((e,t)=>e*t,1),mean:e=>e.reduce((e,t)=>e+t,0)/e.length,gcd:e=>e.reduce(Kt),"()":e=>e,"[]":e=>e,"{}":e=>e};const rn=5e6;let sn=0,on=0;function an(e,t){if(++sn>rn)throw new Error("Too much to work out");switch(e.type){case"number":return Number(e.value);case"string":return e.value.slice(1,-1);case"symbol":if(Object.prototype.hasOwnProperty.call(t,e.value))return t[e.value];if(Object.prototype.hasOwnProperty.call(Yt,e.value))return Yt[e.value];throw new Error(`No value for '${e.value}'`)}const n=H(e);if(n)return an(n,t);const{op:r,args:s}=e;if("?:"===r)return an(s[0],t)?an(s[1],t):an(s[2],t);if("∈"===r||"∉"===r)return function(e,t){const[n,r]=e.args,s=an(n,t);let i;if("symbol"===r.type&&ln[r.value])return i=ln[r.value](s),"∈"===e.op?i:!i;if("op"===r.type&&["()","[]","(]","[)"].includes(r.op)&&2===r.args.length){const[e,n]=r.args.map(e=>an(e,t)),o="["===r.op[0]?s>=e:s>e,a="]"===r.op[1]?s<=n:s<n;i=o&&a}else{const e=an(r,t);i=Array.isArray(e)&&e.includes(s)}return"∈"===e.op?i:!i}(e,t);if("random"===r)return Math.random();if(("\\sumidx"===r||"\\prodidx"===r)&&3===s.length&&"op"===s[1].type&&"="===s[1].op&&"symbol"===s[1].args[0].type){const[e,n,i]=[s[0],s[1].args[1],s[2]],o=s[1].args[0].value,a=an(n,t),l=an(i,t);if(!Number.isFinite(a)||!Number.isFinite(l)||l-a>1e6)throw new Error(`Can't evaluate '${r}' over that range`);let u="\\sumidx"===r?0:1;for(let n=a;n<=l;n++){const s=an(e,{...t,[o]:n});u="\\sumidx"===r?u+s:u*s}return u}if("pmod"===r){const[e,n]=s,r=an(n,t);if("op"===e.type&&["≡","="].includes(e.op)){const[n,s]=e.args.map(e=>an(e,t));return(n-s)%r===0}return an(e,t)%r}const i=s.map(e=>an(e,t));if(en[r]&&1===i.length)return en[r](i[0]);if(tn[r]&&2===i.length)return tn[r](i[0],i[1]);if(nn[r])return nn[r](i);throw new Error(`Can't evaluate '${r}'`)}const ln={"ℝ":Number.isFinite,"ℤ":Number.isInteger,"ℕ":e=>Number.isInteger(e)&&e>0,"ℚ":Number.isFinite,"ℂ":e=>"number"==typeof e&&!Number.isNaN(e)};for(const e of[Yt,en,tn,nn,ln])Object.setPrototypeOf(e,null);class un extends Error{}class cn extends Error{}const hn={bits:2e5,factorial:2e4,terms:1e5,rootIndex:12,steps:5e6};let pn=0,fn=0;const mn=e=>e<0n?-e:e,dn=e=>0n===e?0:mn(e).toString(2).length;function gn(e,t){for(e=mn(e),t=mn(t);t;)[e,t]=[t,e%t];return e}function bn(e,t=1n){if(0n===t)throw new un("division by zero");t<0n&&(e=-e,t=-t);const n=gn(e,t)||1n;return{n:e/n,d:t/n}}const vn=bn(0n),yn=bn(1n),wn=(e,t)=>bn(e.n*t.d+t.n*e.d,e.d*t.d),xn=(e,t)=>bn(e.n*t.n,e.d*t.d),$n=(e,t)=>bn(e.n*t.d,e.d*t.n),kn=e=>({n:-e.n,d:e.d}),qn=(e,t)=>{const n=e.n*t.d-t.n*e.d;return n<0n?-1:n>0n?1:0},Mn=e=>{const t=e.n/e.d;return e.n<0n&&t*e.d!==e.n?t-1n:t};function Nn(e){const t=dn(e.n),n=dn(e.d);if(t<1e3&&n<1e3)return Number(e.n)/Number(e.d);const r=BigInt(Math.max(t,n)-1e3),s=e.d>>r;return 0n===s?e.n<0n?-1/0:1/0:Number(e.n>>r)/Number(s)}function Sn(e){let t=String(e).trim(),n=1n;t.startsWith("-")&&(n=-1n,t=t.slice(1));const r=t.endsWith("..");r&&(t=t.slice(0,-2));let s=0;const i=t.search(/e/i);i>=0&&(s=Number(t.slice(i+1)),t=t.slice(0,i));const[o="",a=""]=t.split(".");if(!(/^\d*$/.test(o)&&/^\d*$/.test(a)&&o+a))throw new cn(`'${e}' is not a number`);let l;if(r&&a){let e=1;for(let t=1;2*t<=a.length;t++)if(a.slice(-t)===a.slice(-2*t,-t)){e=t;break}const t=a.slice(-e);let n=a;for(;n.endsWith(t);)n=n.slice(0,-e);const r=BigInt(n||"0"),s=BigInt(n+t);l=wn(bn(BigInt(o||"0")),bn(s-r,(10n**BigInt(e)-1n)*10n**BigInt(n.length)))}else l=bn(BigInt(o+a||"0"),10n**BigInt(a.length));return s&&(l=s>0?xn(l,bn(10n**BigInt(s))):$n(l,bn(10n**BigInt(-s)))),n<0n?kn(l):l}function An(e,t=0,n=0,r=null){return 0n===e.n?{kind:"x",c:vn,pi:0,e:0,root:null}:{kind:"x",c:e,pi:t,e:n,root:r}}const On=(e,t=1n)=>An(bn(BigInt(e),BigInt(t))),En=An(yn,1),In=An(yn,0,1),_n=e=>null!==e&&"object"==typeof e&&"x"===e.kind,Tn=e=>_n(e)&&!e.pi&&!e.e&&!e.root,jn=e=>_n(e)?0n===e.c.n:0===e,Cn=e=>Tn(e)&&1n===e.c.d?e.c.n:null,zn=(e,t)=>Object.assign(e,{group:t}),Ln=e=>({kind:"s",text:e});function Rn(e,t){return e&&t?e.n===t.n&&e.r===t.r:e===t}const Zn=(e,t)=>0===qn(e.c,t.c)&&e.pi===t.pi&&e.e===t.e&&Rn(e.root,t.root);function Fn(e){if("number"==typeof e)return e;if(_n(e)){let t=Nn(e.c);return e.pi&&(t*=Math.PI**e.pi),e.e&&(t*=Math.E**e.e),e.root&&(t*=Nn(bn(e.root.r))**(1/e.root.n)),t}if("boolean"==typeof e)return e?1:0;throw new cn("not a number")}function Bn(e,...t){if(Number.isNaN(e))throw new un("undefined");if(!Number.isFinite(e)&&t.every(Number.isFinite))throw new cn("too large to calculate");return e}const Pn=e=>"boolean"==typeof e?e:_n(e)?0n!==e.c.n:"number"==typeof e?0!==e:Boolean(e);function Dn(e){if("bigint"==typeof e)return An(bn(e));if("number"==typeof e)return Number.isFinite(e)?An(Number.isInteger(e)&&Math.abs(e)<=Number.MAX_SAFE_INTEGER?bn(BigInt(e)):Sn(String(e))):e;if("boolean"==typeof e)return e;if("string"==typeof e)return/^-?(\d+\.?\d*|\.\d+)(\.\.)?$/.test(e.trim())?An(Sn(e)):Nr(Xt(e),{});if(Array.isArray(e))return zn(e.map(Dn),e.group||"()");if(_n(e)||"function"==typeof e)return e;throw new cn(`can't use ${typeof e} as a value`)}function Wn(e){return Array.isArray(e)?e.map(Wn):e&&"s"===e.kind?e.text:"boolean"==typeof e?e:Fn(e)}function Un(e,t){if(e<2n)return e;const n=BigInt(t);let r=1n<<BigInt(Math.ceil(dn(e)/t));for(;;){const t=((n-1n)*r+e/r**(n-1n))/n;if(t>=r)return r;r=t}}function Vn(e,t,n,r=0,s=0){if(0n===n)return An(vn);const{coef:i,root:o}=function(e,t){let n=1n,r=t;const s=BigInt(e),i=r<10n**24n?1000000n:10000n;for(let e=2n;e<=i&&e*e<=r;e+=2n===e?1n:2n){const t=e**s;for(;r%t===0n;)r/=t,n*=e}const o=Un(r,e);if(o**s===r&&(n*=o,r=1n),1n===r)return{coef:n,root:null};for(let t=e;t>=2;t--){if(e%t!==0)continue;const s=Un(r,t);if(s**BigInt(t)===r)return{coef:n,root:{n:e/t,r:s}}}return{coef:n,root:{n:e,r:r}}}(t,n);return o&&1===o.n?An(xn(e,bn(i*o.r)),r,s):An(xn(e,bn(i)),r,s,o)}function Hn(e,t){const n=xn(e.c,t.c);if(dn(n.n)+dn(n.d)>hn.bits)return null;const r=e.pi+t.pi,s=e.e+t.e;if(!e.root||!t.root)return An(n,r,s,e.root||t.root);const i=yr(e.root.n,t.root.n);if(i>hn.rootIndex)return null;const o=e.root.r**BigInt(i/e.root.n)*t.root.r**BigInt(i/t.root.n);return dn(o)>4e3?null:Vn(n,i,o,r,s)}function Gn(e){if(0n===e.c.n)throw new un("division by zero");const t=An($n(yn,e.c),-e.pi,-e.e);if(!e.root)return t;const{n:n,r:r}=e.root;return Hn(t,Vn(bn(1n,r),n,r**BigInt(n-1)))}function Xn(e,t){if(0n===t){if(0n===e.c.n)throw new un("0^0 is undefined");return An(yn)}if(t<0n){const n=Gn(e);return n&&Xn(n,-t)}if((dn(e.c.n)+dn(e.c.d)+(e.root?dn(e.root.r):0))*Number(t)>hn.bits||t>100000n)return null;const n=bn(e.c.n**t,e.c.d**t),r=Number(t);if(!e.root)return An(n,e.pi*r,e.e*r);const{n:s,r:i}=e.root,o=i**(t/BigInt(s));return Vn(xn(n,bn(o)),s,i**(t%BigInt(s))||1n,e.pi*r,e.e*r)}function Qn(e,t,n){if(!Tn(e)||n>1000n)return null;const r=Xn(e,t);if(!r)return null;let{n:s,d:i}=r.c,o=!1;if(s<0n){if(n%2n==0n)throw new un("not a real number");o=!0,s=-s}const a=function(e,t){const n=e.n*e.d**BigInt(t-1);return dn(n)>4e3?null:Vn(bn(1n,e.d),t,n)}({n:s,d:i},Number(n));return a?o?An(kn(a.c),a.pi,a.e,a.root):a:null}function Jn(e){return t=>Array.isArray(t)?zn(t.map(t=>Jn(e)(t)),t.group):e(t)}function Yn(e){const t=(n,r)=>{const s=Array.isArray(n),i=Array.isArray(r);if(s&&i){if(n.length!==r.length)throw new un("lists of different lengths");return zn(n.map((e,n)=>t(e,r[n])),n.group)}return s?zn(n.map(e=>t(e,r)),n.group):i?zn(r.map(e=>t(n,e)),r.group):e(n,r)};return t}const Kn=Yn((e,t)=>_n(e)&&_n(t)&&function(e,t){if(0n===e.c.n)return t;if(0n===t.c.n)return e;if(e.pi!==t.pi||e.e!==t.e||!Rn(e.root,t.root))return null;const n=wn(e.c,t.c);return dn(n.n)+dn(n.d)>hn.bits?null:An(n,e.pi,e.e,e.root)}(e,t)||Bn(Fn(e)+Fn(t),Fn(e),Fn(t))),er=Jn(e=>_n(e)?An(kn(e.c),e.pi,e.e,e.root):-Fn(e)),tr=(e,t)=>Kn(e,er(t)),nr=Yn((e,t)=>_n(e)&&_n(t)&&Hn(e,t)||Bn(Fn(e)*Fn(t),Fn(e),Fn(t))),rr=Yn((e,t)=>{if(jn(t))throw new un("division by zero");if(_n(e)&&_n(t)){const n=Gn(t),r=n&&Hn(e,n);if(r)return r}return Bn(Fn(e)/Fn(t),Fn(e),Fn(t))}),sr=Yn((e,t)=>{if(_n(e)&&Tn(t)){const{n:n,d:r}=t.c,s=1n===r?Xn(e,n):Qn(e,n,r);if(s)return s}const n=Fn(e),r=Fn(t);if(0===n&&0===r)throw new un("0^0 is undefined");if(0===n&&r<0)throw new un("division by zero");if(n<0&&!Number.isInteger(r))throw new un("not a real number");return Bn(n**r,n,r)});function ir(e,t){if(Tn(e)&&Tn(t))return qn(e.c,t.c);if(_n(e)&&_n(t)&&Zn(e,t))return 0;const n=Fn(e),r=Fn(t);return n===r||Number.isFinite(n)&&Number.isFinite(r)&&Math.abs(n-r)<=1e-12*Math.max(1,Math.abs(n),Math.abs(r))?0:n<r?-1:1}function or(e,t){return Array.isArray(e)||Array.isArray(t)?Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>or(e,t[n])):e&&"s"===e.kind?Boolean(t&&"s"===t.kind&&e.text===t.text):"boolean"==typeof e||"boolean"==typeof t?e===t:0===ir(e,t)}const ar={0:()=>On(0),2:()=>On(1,2),3:()=>Vn(bn(1n,2n),2,2n),4:()=>Vn(bn(1n,2n),2,3n),6:()=>On(1)};function lr(e){e=(e%24+24)%24;const[t,n]=e<=6?[e,1]:e<=12?[12-e,1]:e<=18?[e-12,-1]:[24-e,-1],r=ar[t];return r?n<0?er(r()):r():null}const ur=e=>lr(e+6),cr=(e,t)=>Math.abs(e)<1e-15&&Math.abs(t)>1e-6?0:e;function hr(e,t){const n=function(e){if(jn(e))return 0;if(!_n(e)||1!==e.pi||e.e||e.root)return null;const t=xn(e.c,bn(12n));return 1n!==t.d?null:Number((t.n%24n+24n)%24n)}(t);if(null!==n){const t=lr(n),r=ur(n);if(t&&r)switch(e){case"sin":return t;case"cos":return r;case"tan":return rr(t,r);case"cot":return rr(r,t);case"sec":return rr(On(1),r);case"csc":return rr(On(1),t)}}const r=Fn(t),s=cr(Math.sin(r),r),i=cr(Math.cos(r),r),o={sin:s,cos:i,tan:s/i,cot:i/s,sec:1/i,csc:1/s}[e];if(!Number.isFinite(o)&&Number.isFinite(r))throw new un("undefined");return Bn(o)}function pr(e,t){const n={arcsin:[-6,6],arccos:[0,12],arctan:[-5,5]}[e],r=t=>"arcsin"===e?lr(t):"arccos"===e?ur(t):ur(t)&&!jn(ur(t))?rr(lr(t),ur(t)):null;if(_n(t))for(let e=n[0];e<=n[1];e++){const n=r(e);if(n&&_n(n)&&Zn(n,t))return An(bn(BigInt(e),12n),1)}const s=Fn(t);if("arctan"!==e&&Math.abs(s)>1)throw new un("not a real number");return{arcsin:Math.asin,arccos:Math.acos,arctan:Math.atan}[e](s)}function fr(e){if(_n(e)){if(0n===e.c.n)throw new un("ln 0 is undefined");if(e.c.n<0n)throw new un("not a real number");if(1n===e.c.n&&1n===e.c.d&&!e.pi&&!e.root)return On(e.e)}const t=Fn(e);if(t<=0)throw new un(0===t?"ln 0 is undefined":"not a real number");return Math.log(t)}function mr(e){if(e<.5)return Math.PI/(Math.sin(Math.PI*e)*mr(1-e));const t=[.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-.13857109526572012,9984369578019572e-21,1.5056327351493116e-7];let n=t[0];const r=(e-=1)+7+.5;for(let r=1;r<9;r++)n+=t[r]/(e+r);return Math.sqrt(2*Math.PI)*r**(e+.5)*Math.exp(-r)*n}function dr(e,t){const n=Cn(e)??("number"==typeof e&&Number.isInteger(e)?BigInt(e):null);if(null===n)throw new un(`${t} needs whole numbers`);return n}const gr=Jn(e=>Tn(e)?An(bn(Mn(e.c))):Dn(Math.floor(Fn(e)))),br=Jn(e=>Tn(e)?An(bn(-Mn(kn(e.c)))):Dn(Math.ceil(Fn(e))));function vr(e,t){const n=Number(dr(t,"round"));if(Tn(e)){const t=bn(10n**BigInt(Math.abs(n))),r=n>=0?xn(e.c,t):$n(e.c,t),s=Mn(wn(xn(bn(2n),bn(mn(r.n),r.d)),yn))/2n,i=bn(r.n<0n?-s:s);return An(n>=0?$n(i,t):xn(i,t))}const r=10**n;return Math.sign(Fn(e))*Math.round(Math.abs(Fn(e))*r)/r}const yr=(e,t)=>e/wr(e,t)*t,wr=(e,t)=>t?wr(t,e%t):e,xr={pi:()=>En,"π":()=>En,tau:()=>An(bn(2n),1),"τ":()=>An(bn(2n),1),e:()=>In,"∞":()=>1/0,"-∞":()=>-1/0,true:()=>!0,false:()=>!1},$r={abs:e=>_n(e)?An(bn(mn(e.c.n),e.c.d),e.pi,e.e,e.root):Math.abs(Fn(e)),floor:gr,ceil:br,sqrt:e=>sr(e,On(1,2)),ln:Jn(fr),loglog:Jn(e=>fr(fr(e))),logloglog:Jn(e=>fr(fr(fr(e)))),expm1:Jn(e=>jn(e)?On(0):Math.expm1(Fn(e))),sinh:Jn(e=>jn(e)?On(0):Math.sinh(Fn(e))),cosh:Jn(e=>jn(e)?On(1):Math.cosh(Fn(e))),tanh:Jn(e=>jn(e)?On(0):Math.tanh(Fn(e))),arcsinh:Jn(e=>jn(e)?On(0):Math.asinh(Fn(e))),arccosh:Jn(e=>{const t=Fn(e);if(t<1)throw new un("not a real number");return 1===t?On(0):Math.acosh(t)}),arctanh:Jn(e=>{const t=Fn(e);if(Math.abs(t)>=1)throw new un("undefined");return jn(e)?On(0):Math.atanh(t)}),"!":Jn(function(e){const t=Cn(e)??("number"==typeof e&&Number.isInteger(e)?BigInt(e):null);if(null!==t){if(t<0n)throw new un("factorial of a negative number");if(t>BigInt(hn.factorial))throw new cn("too large to calculate");let e=1n;for(let n=2n;n<=t;n++)e*=n;return An(bn(e))}const n=Fn(e);if(n<0&&Number.isInteger(n))throw new un("factorial of a negative number");return Bn(mr(n+1),n)}),neg:er,pm:e=>zn([e,er(e)],"pm"),"\\not":e=>!Pn(e)};for(const e of["sin","cos","tan","csc","sec","cot"])$r[e]=Jn(t=>hr(e,t));for(const e of["arcsin","arccos","arctan"])$r[e]=Jn(t=>pr(e,t));const kr={"+":Kn,"-":tr,"*":nr,"/":rr,"^":sr,"±":(e,t)=>zn([Kn(e,t),tr(e,t)],"pm"),mod:Yn(function(e,t){if(jn(t))throw new un("division by zero");if(Tn(e)&&Tn(t))return An(wn(e.c,kn(xn(t.c,bn(Mn($n(e.c,t.c)))))));const n=Fn(e),r=Fn(t);return Bn((n%r+r)%r)}),log:Yn(function(e,t){if(_n(e)&&Zn(e,In))return fr(t);const n=Fn(e),r=Fn(t);if(n<=0||1===n)throw new un("not a valid base");if(r<=0)throw new un(0===r?"log 0 is undefined":"not a real number");const s=Math.log(r)/Math.log(n);if(Tn(e)&&Tn(t))for(let n=1n;n<=12n;n++){const r=Math.round(s*Number(n));if(Math.abs(s*Number(n)-r)>1e-9)continue;const i=Xn(e,BigInt(r)),o=Xn(t,n);if(i&&o&&Zn(i,o))return An(bn(BigInt(r),n))}return s}),root:Yn((e,t)=>sr(t,rr(On(1),e))),atan2:(e,t)=>Math.atan2(Fn(e),Fn(t)),round:vr,fixed:function(e,t){const n=Number(dr(t,"fixed"));if(n<0)throw new un("fixed needs 0 or more decimal places");const r=vr(e,t);if(Tn(r)){const e=r.c.n*10n**BigInt(n)/r.c.d,t=(e<0n?-e:e).toString().padStart(n+1,"0");return Ln(`${e<0n?"-":""}${t.slice(0,t.length-n)}${n?"."+t.slice(-n):""}`)}return Ln(Number(Fn(r)).toFixed(n))},perm:function(e,t){const n=dr(e,"permutations"),r=dr(t,"permutations");if(r<0n||r>n)throw new un("undefined");if(r>BigInt(hn.terms))throw new cn("too large to calculate");let s=1n;for(let e=n-r+1n;e<=n;e++)s*=e;return An(bn(s))},comb:function(e,t){const n=dr(e,"combinations");let r=dr(t,"combinations");if(r<0n||r>n)throw new un("undefined");if(n-r<r&&(r=n-r),r>BigInt(hn.terms))throw new cn("too large to calculate");let s=1n;for(let e=1n;e<=r;e++)s=s*(n-r+e)/e;return An(bn(s))},"=":(e,t)=>or(e,t),"===":(e,t)=>or(e,t),"≠":(e,t)=>!or(e,t),"≠=":(e,t)=>!or(e,t),"≈":(e,t)=>Math.abs(Fn(e)-Fn(t))<=1e-9*Math.max(1,Math.abs(Fn(e)),Math.abs(Fn(t))),"<":(e,t)=>ir(e,t)<0,">":(e,t)=>ir(e,t)>0,"≤":(e,t)=>ir(e,t)<=0,"≥":(e,t)=>ir(e,t)>=0,"&":(e,t)=>Pn(e)&&Pn(t),"|":(e,t)=>Pn(e)||Pn(t),"\\xor":(e,t)=>Pn(e)!==Pn(t),"\\nor":(e,t)=>!(Pn(e)||Pn(t)),"\\nand":(e,t)=>!(Pn(e)&&Pn(t))},qr={sum:e=>e.reduce((e,t)=>Kn(e,t),On(0)),prod:e=>e.reduce((e,t)=>nr(e,t),On(1)),max:e=>e.reduce((e,t)=>ir(t,e)>0?t:e),min:e=>e.reduce((e,t)=>ir(t,e)<0?t:e),mean:e=>rr(qr.sum(e),On(e.length)),gcd:e=>An(bn(e.map(e=>dr(e,"gcd")).reduce(gn)))},Mr=["∈","∉","∪","∩","pmod","random","(]","[)"];function Nr(e,t){if(++pn>hn.steps)throw new cn("too much to work out");switch(e.type){case"number":return An(Sn(e.value));case"string":return Ln(e.value.slice(1,-1));case"symbol":return Sr(e.value,t)}const n=H(e);if(n)return Nr(n,t);const{op:r,args:s}=e,i=e=>Nr(e,t);if("?:"===r)return Pn(i(s[0]))?i(s[1]):i(s[2]);if("_"===r){if(s.every(e=>"op"!==e.type))return Sr(`${s[0].value}_${s[1].value}`,t);throw new cn("subscript")}if("der"===r)return function(e,t){const[n,r]=e.args,s=Or(r);if(!s||!Object.prototype.hasOwnProperty.call(t,s))throw new cn(`a derivative needs a value for ${s||"its variable"}`);const i=Fn(t[s]),o=Ar(n,s,t);if(!Number.isFinite(o(i)))throw new un("undefined");const a=1e-6*Math.max(1,Math.abs(i)),l=(o(i+a)-o(i))/a,u=(o(i)-o(i-a))/a;if(!Number.isFinite(l)||!Number.isFinite(u)||Math.abs(l-u)>.001*Math.max(1,Math.abs(l)))throw new un("not differentiable here");let c=.1*Math.max(1,Math.abs(i));const h=1.4,p=[[(o(i+c)-o(i-c))/(2*c)]];let f=p[0][0],m=1/0;for(let e=1;e<12;e++){c/=h,p[e]=[(o(i+c)-o(i-c))/(2*c)];let t=h*h;for(let n=1;n<=e;n++){p[e][n]=(p[e][n-1]*t-p[e-1][n-1])/(t-1),t*=h*h;const r=Math.max(Math.abs(p[e][n]-p[e][n-1]),Math.abs(p[e][n]-p[e-1][n-1]));r<=m&&(m=r,f=p[e][n])}if(Math.abs(p[e][e]-p[e-1][e-1])>=2*m)break}if(!Number.isFinite(f))throw new un("not differentiable here");return Tr(f,m)}(e,t);if("int"===r)return function(e,t){const[n,r,s,i]=e,o=e=>e&&"symbol"===e.type&&/^[a-zA-Zʹ-Ͽ]$/.test(e.value);let a,l,u;if(4===e.length)[a,l,u]=[Or(r),s,i];else{if(3!==e.length||o(r))throw new cn("an integral needs limits to be calculated");[a,l,u]=[A(n)||"x",r,s]}let c=Fn(Nr(l,t)),h=Fn(Nr(u,t));if(c===h)return On(0);let p=1;c>h&&([c,h]=[h,c],p=-1);const f=Ar(n,a,t),{value:m,error:d}=Er(f,c,h);return Tr(p*m,d)}(s,t);if("lim"===r)return function(e,t){const[n,r,s,i]=e;let o,a,l=0;if(2===e.length&&"op"===r.type&&"→"===r.op)[o,a]=[Or(r.args[0]),r.args[1]];else if(2===e.length)[o,a]=[A(n),r];else{if(!(e.length>=3))throw new cn("a limit needs a point");[o,a]=[Or(r),s]}if(4===e.length){const e="op"===i.type?"":String(i.value).toLowerCase();l=e.startsWith("r")||"+"===e?1:-1}if(!o)throw new cn("a limit needs a variable");const u=Nr(a,t),c=Fn(u),h=Ar(n,o,t);let p,f;if(Number.isFinite(c))if(l)({value:p,error:f}=_r(e=>h(c+l*e*Math.max(1,Math.abs(c)))));else{const e=_r(e=>h(c+e*Math.max(1,Math.abs(c)))),r=_r(e=>h(c-e*Math.max(1,Math.abs(c))));if(e.value===r.value)({value:p,error:f}=e);else{if(!(Number.isFinite(e.value)&&Number.isFinite(r.value)&&Math.abs(e.value-r.value)<=1e-6*Math.max(1,Math.abs(e.value))))throw new un("the limit does not exist");p=(e.value+r.value)/2,f=Math.max(e.error,r.error,Math.abs(e.value-r.value))}try{const e=Nr(n,{...t,[o]:u});if(Math.abs(Fn(e)-p)<=1e-6*Math.max(1,Math.abs(p)))return e}catch(e){if(!(e instanceof un))throw e}}else({value:p,error:f}=_r(e=>h(Math.sign(c)/e)));return Number.isFinite(p)?Tr(p,f):p}(s,t);if("\\sumidx"===r||"\\prodidx"===r)return function(e,t,n){const[r,s,i]=t;if(t.length<3)throw new cn("a sum needs its limits");let o,a=s;"op"===s.type&&"="===s.op&&"symbol"===s.args[0].type?[o,a]=[s.args[0].value,s.args[1]]:o=A(r)||"n";const l=dr(Nr(a,n),"a sum"),u=Nr(i,n),c=e?Kn:nr;if(u===1/0){if(!e)throw new cn("an infinite product");return function(e,t){const n=[],r=[];let s=0,i=t;for(let o=4;o<=17;o++){const a=2**o;for(;i<t+a;i++){const t=e(i);if(!Number.isFinite(t))throw new un("undefined");s+=t}if(n.push(a),r.push(s),o>=6&&r[r.length-1]===r[r.length-2])return Tr(s,0)}const o=r[r.length-1]-r[r.length-2],a=r[r.length-2]-r[r.length-3];if(Math.abs(o)>=.9*Math.abs(a)&&Math.abs(o)>1e-12)throw new un("the series diverges");const l=n.slice(-7).map(e=>1/e),u=r.slice(-7),c=r.slice(-8,-1),h=(e,t)=>{const n=t.slice();for(let t=1;t<e.length;t++)for(let r=0;r<e.length-t;r++)n[r]=(e[r+t]*n[r]-e[r]*n[r+1])/(e[r+t]-e[r]);return n[0]},p=h(l,u),f=h(n.slice(-8,-1).map(e=>1/e),c);return Tr(p,Math.abs(p-f))}(Ar(r,o,n),Number(l))}const h=dr(u,"a sum");if(h-l+1n>BigInt(hn.terms))throw new cn("too many terms to add one by one");let p=On(e?0:1);for(let e=l;e<=h;e++)p=c(p,Nr(r,{...n,[o]:An(bn(e))}));return p}("\\sumidx"===r,s,t);if(["()","[]","{}"].includes(r))return zn(s.map(i),r);if(Mr.includes(r))return function(e,t){const n={};for(const[e,r]of Object.entries(t))"function"!=typeof r&&(n[e]=Wn(r));try{return Dn(function(e,t={}){0===on&&(sn=0),on++;try{return an(Qt(e),t)}finally{on--}}(e,n))}catch(e){throw new cn(e.message)}}(e,t);if(r.startsWith("\\:")){const e=t[r.slice(2)];if("function"!=typeof e)throw new cn(`no function ${r.slice(2)}`);return Dn(e(...s.map(e=>Wn(i(e)))))}if($r[r]&&1===s.length)return $r[r](i(s[0]));if(kr[r]&&2===s.length)return kr[r](i(s[0]),i(s[1]));if(qr[r])return qr[r](s.map(i));throw new cn(`can't calculate '${r}'`)}function Sr(e,t){if(Object.prototype.hasOwnProperty.call(t,e))return t[e];if(Object.prototype.hasOwnProperty.call(xr,e))return xr[e]();throw new cn(`no value for '${e}'`)}function Ar(e,t,n){return r=>{try{return Fn(Nr(e,{...n,[t]:r}))}catch(e){if(e instanceof un)return NaN;throw e}}}const Or=e=>"symbol"===e.type?e.value:null;function Er(e,t,n){if(t===-1/0&&n===1/0){const t=Er(e,-1/0,0),n=Er(e,0,1/0);return{value:t.value+n.value,error:t.error+n.error}}return n===1/0?Ir(n=>e(t+n/(1-n))/((1-n)*(1-n)),0,1):t===-1/0?Ir(t=>e(n-t/(1-t))/((1-t)*(1-t)),0,1):Ir(e,t,n)}function Ir(e,t,n){const r=(n-t)/2;let s=1,i=0,o=NaN,a=NaN,l=0;const u=s=>{const i=Math.PI/2*Math.sinh(Math.abs(s)),o=Math.exp(-2*i),a=2*r*o/(1+o),u=r*(Math.PI/2)*Math.cosh(s)*(4*o)/((1+o)*(1+o));if(0===a||0===u)return 0;const c=s>0?n-a:t+a;if(0!==s&&(c<=t||c>=n))return 0;const h=e(0===s?(t+n)/2:c);if(!Number.isFinite(h)){if(a<1e-6*r)return 0;throw new un("the integral diverges")}return Math.abs(s)>3.5&&(l=Math.max(l,Math.abs(u*h))),u*h};i=u(0);for(let e=s;e<=4;e+=s)i+=u(e)+u(-e);o=s*i;for(let e=1;e<=8;e++){s/=2;for(let e=s;e<=4;e+=2*s)i+=u(e)+u(-e);a=o,o=s*i;const t=Math.max(1,Math.abs(o));if(l>1e-8*t)throw new un("the integral diverges");if(e>=3&&Math.abs(o-a)<=1e-13*t)break}const c=Math.abs(o-a);if(!Number.isFinite(o)||c>1e-6*Math.max(1,Math.abs(o)))throw new un("the integral does not converge");return{value:o,error:c}}function _r(e){const t=[],n=[];for(let r=0;r<30;r++){const s=.1/2**r,i=e(s);Number.isFinite(i)&&(t.push(s),n.push(i))}if(n.length<6)throw new un("undefined");const r=n.slice(1).map((e,t)=>e-n[t]).slice(-6);if(r.every(e=>Math.sign(e)===Math.sign(r[0])&&0!==e)&&Math.abs(r[5])>=.95*Math.abs(r[0])&&Math.abs(n[n.length-1])>10)return{value:Math.sign(r[0])*(1/0),error:0};const s=e=>{const r=t.slice(e,e+8),s=n.slice(e,e+8);for(let e=1;e<r.length;e++)for(let t=0;t<r.length-e;t++)s[t]=(r[t+e]*s[t]-r[t]*s[t+1])/(r[t+e]-r[t]);return s[0]};let i=null;for(let e=0;e+9<=n.length;e++){const t=s(e),n=s(e+1),r=Math.abs(t-n);Number.isFinite(t)&&(!i||r<i.error)&&(i={value:t,error:r})}const o=n[n.length-1],a=Math.abs(o-n[n.length-2]);if(!i||i.error>Math.max(a,1e-6*Math.max(1,Math.abs(o)))){if(a<=1e-6*Math.max(1,Math.abs(o)))return{value:o,error:10*a};throw new un("the limit could not be found")}return i}function Tr(e,t=0){if(!Number.isFinite(e))return e;const n=Math.max(1e-10,4*t)*Math.max(1,Math.abs(e));if(n>1e-6*Math.max(1,Math.abs(e)))return e;if(Math.abs(e)<n)return On(0);const r=[[On(1),1e3],[En,100],[An(yn,2),100],[In,100],...[2n,3n,5n,6n,7n].map(e=>[An(yn,0,0,{n:2,r:e}),100])];for(const[t,s]of r){const r=e/Fn(t),i=jr(r,s);if(i&&Math.abs(Number(i.n)/Number(i.d)-r)*Fn(t)<=n)return Hn(An(i),t)}return e}function jr(e,t){if(!Number.isFinite(e)||Math.abs(e)>1e12)return null;let[n,r,s,i]=[0,1,1,0],o=e;for(let e=0;e<40;e++){const e=Math.floor(o),a=e*r+n,l=e*i+s;if(l>t)break;if([n,r,s,i]=[r,a,i,l],Math.abs(o-e)<1e-15)break;o=1/(o-e)}return i?bn(BigInt(r),BigInt(i)):null}function Cr(e,t){if("boolean"==typeof e)return String(e);if(e&&"s"===e.kind)return JSON.stringify(e.text);if(Array.isArray(e)){if("pm"===e.group&&2===e.length&&or(e[1],er(e[0])))return`±${zr(e[0],t)}`;const[n,r]={"()":"()","[]":"[]","{}":"{}"}[e.group]||"{}";return n+e.map(e=>Cr(e,t)).join(", ")+r}return"number"==typeof e?Lr(e,t):t.decimal||null!==t.places?function(e,t){if(Tn(e)&&null===t.places){let n=e.c.d,r=0,s=0;for(;n%2n==0n;)n/=2n,r++;for(;n%5n==0n;)n/=5n,s++;const i=Math.max(r,s);if(1n===n&&i<=t.digits){const n=e.c.n*10n**BigInt(i)/e.c.d,r=n<0n,s=mn(n).toString().padStart(i+1,"0"),o=i?`${s.slice(0,-i)}.${s.slice(-i)}`:s;if(s.length<=t.maxDigits)return(r?"-":"")+Rr(o)}}return Tn(e)&&null!==t.places?Cr(vr(e,On(t.places)),{...t,places:null,decimal:!0}):Lr(Fn(e),t)}(e,t):function(e,t){const{c:n}=e,r=mn(n.n);if(r.toString().length>t.maxDigits||n.d.toString().length>t.maxDigits)return function(e,t){if(!Tn(e)||1n!==e.c.d)return Lr(Fn(e),t);const n=mn(e.c.n).toString(),r=BigInt(n.slice(0,t.digits+1)),s=((r+5n)/10n).toString(),i=n.length-1+(s.length>t.digits?1:0),o=Rr(`${s[0]}.${s.slice(1,t.digits)}`);return`${e.c.n<0n?"-":""}${o}*10^(${i})`}(e,t);const s=(e,t)=>1===t?e:`${e}^${t}`,i=[],o=[];e.pi>0&&i.push(s("pi",e.pi));e.pi<0&&o.push(s("pi",-e.pi));e.e>0&&i.push(s("e",e.e));e.e<0&&o.push(s("e",-e.e));e.root&&i.push(2===e.root.n?`sqrt(${e.root.r})`:`root(${e.root.n}, ${e.root.r})`);1n===r&&i.length||i.unshift(r.toString());1n!==n.d&&o.unshift(n.d.toString());const a=e=>e.length>1?`(${e.join("*")})`:e[0],l=o.length?`${a(i)}/${a(o)}`:i.join("*");return(n.n<0n?"-":"")+l}(e,t)}const zr=(e,t)=>{const n=Cr(e,t);return/^[\d.]+$|^[a-zπ]+$/i.test(n)?n:`(${n})`};function Lr(e,t){if(e===1/0)return"∞";if(e===-1/0)return"-∞";if(Object.is(e,-0)||0===e)return"0";if(null!==t.places&&Math.abs(e)<1e21)return e.toFixed(t.places);const n=Math.abs(e);if(n>=1e15||n<1e-6){const[n,r]=e.toExponential(t.digits-1).split("e");return`${Rr(n)}*10^(${Number(r)})`}return String(Number(e.toPrecision(t.digits)))}const Rr=e=>e.includes(".")?e.replace(/\.?0+$/,""):e;function Zr(e,t={},n={}){const r="string"==typeof e?Xt(e):N(e),s={};for(const[e,n]of Object.entries(t))s[e]=Dn(n);let i;0===fn&&(pn=0),fn++;try{i=Nr(r,s)}finally{fn--}const o={decimal:!1,places:null,digits:12,maxDigits:50,...n};void 0===o.places&&(o.places=null);const a=e=>Array.isArray(e)?e.every(a):"number"!=typeof e;return{value:Wn(i),text:Cr(i,o),exact:a(i)}}function Fr(e,t={}){let n=e.trim();const r={},s=/^(~|≈)\s*(\d+)?/.exec(n);s&&(r.decimal=!0,void 0!==s[2]&&(r.places=Number(s[2])),n=n.slice(s[0].length)),/\d\.\d|\.\d/.test(n)&&(r.decimal=!0);try{const{text:e}=Zr(n,t,r);return e.startsWith('"')||/^\d+(\.\d+)?$/.test(e)?e:`(${e})`}catch(e){if(e instanceof un)return'"undefined"';if(e instanceof cn)return`(${n})`;throw e}}Vt=Fr;for(const e of[hn,ar,xr,$r,kr,qr])Object.setPrototypeOf(e,null);const Br={plus:"plus",minus:"minus",times:"times",over:"over",negative:"negative",plusOrMinus:"plus or minus",quantity:"the quantity",of:"of",and:"and",or:"or",not:"not",xor:"exclusive or",nand:"nand",nor:"nor",squared:"squared",cubed:"cubed",toThe:"to the",toThePowerOf:"to the power of",power:"power",sub:"sub",factorial:"factorial",prime:"prime",doublePrime:"double prime",triplePrime:"triple prime",inverse:"inverse",mod:"mod",percent:"percent",degrees:"degrees",equals:"equals",notEqual:"is not equal to",lessThan:"is less than",greaterThan:"is greater than",lessOrEqual:"is less than or equal to",greaterOrEqual:"is greater than or equal to",approx:"is approximately",congruent:"is congruent to",approaches:"approaches",tendsTo:"approaches",isIn:"is in",isNotIn:"is not in",union:"union",intersect:"intersect",squareRoot:"the square root of",cubeRoot:"the cube root of",nthRoot:e=>`the ${e} root of`,absoluteValue:"the absolute value of",floor:"the floor of",ceiling:"the ceiling of",logBase:"log base",naturalLog:"the natural log of",choose:"choose",permute:"permute",derivative:"the derivative",secondDerivative:"the second derivative",nthDerivative:e=>`the ${e} derivative`,withRespectTo:"with respect to",d:"d",integralOf:"the integral of",integralFrom:"the integral from",to:"to",limitAs:"the limit as",fromTheRight:"from the right",fromTheLeft:"from the left",sumFrom:"the sum from",sumOver:"the sum over",sumOf:"the sum of",productFrom:"the product from",productOver:"the product over",productOf:"the product of",theSet:"the set",theList:"the list",openInterval:"the open interval from",closedInterval:"the closed interval from",halfOpenInterval:"the half-open interval from",comma:",",if:"if",then:"then",otherwise:"otherwise",infinity:"infinity",pi:"pi",e:"e",delta:"delta",randomNumber:"a random number",rounded:"rounded to",decimalPlaces:"decimal places",nearestWholeNumber:"the nearest whole number",writtenTo:"written to",asWholeNumber:"written as a whole number",reals:"the real numbers",integers:"the integers",naturals:"the natural numbers",rationals:"the rational numbers",complexes:"the complex numbers",repeating:"repeating",eToThe:"e to the",half:"half",halves:"halves",ordinals:["","","half","third","quarter","fifth","sixth","seventh","eighth","ninth","tenth"],numerators:["","one","two","three","four","five","six","seven","eight","nine"],powers:["","first","squared","cubed","fourth","fifth","sixth","seventh","eighth","ninth","tenth"]},Pr={sin:"sine",cos:"cosine",tan:"tangent",csc:"cosecant",sec:"secant",cot:"cotangent",sinh:"hyperbolic sine",cosh:"hyperbolic cosine",tanh:"hyperbolic tangent",arcsin:"inverse sine",arccos:"inverse cosine",arctan:"inverse tangent",arcsinh:"inverse hyperbolic sine",arccosh:"inverse hyperbolic cosine",arctanh:"inverse hyperbolic tangent",ln:"the natural log",log:"log",loglog:"the log of the log",logloglog:"the log of the log of the log",expm1:"e to the power, minus 1, of",max:"the maximum",min:"the minimum",gcd:"the greatest common divisor",mean:"the mean",atan2:"the arctangent",round:"round",fixed:"fixed",random:"random"},Dr=Object.fromEntries(Object.entries(O).map(([e,t])=>[t,e]));function Wr(e,t={}){return function(e){const t=[];for(const{text:n,id:r}of e){const e=n.trim();if(!e)continue;const s=e.startsWith(","),i=s?e.slice(1).trim():e;s&&t.length&&!t[t.length-1].text.endsWith(",")&&(t[t.length-1].text+=","),i&&t.push({text:i,id:r})}t.length&&(t[t.length-1].text=t[t.length-1].text.replace(/,$/,""));return t}(new Gr({...Br,...t.words},{...Pr,...t.names},t.say||{}).speak(e))}function Ur(e){return e.map(e=>e.text).join(" ").replace(/\s+/g," ").replace(/ ,/g,",").replace(/,(\s*,)+/g,",").replace(/^,\s*/,"").replace(/,\s*$/,"").trim()}const Vr={"=":"equals","===":"equals","≠":"notEqual","≠=":"notEqual","<":"lessThan",">":"greaterThan","≤":"lessOrEqual","≥":"greaterOrEqual","≈":"approx","≡":"congruent","→":"tendsTo","∈":"isIn","∉":"isNotIn","∪":"union","∩":"intersect","±":"plusOrMinus","&":"and","|":"or","\\xor":"xor","\\nand":"nand","\\nor":"nor"},Hr={"ℝ":"reals","ℤ":"integers","ℕ":"naturals","ℚ":"rationals","ℂ":"complexes"};class Gr{constructor(e,t,n){this.w=e,this.names=t,this.say=n}speak(e){const t=this.say["op"===e.type?e.op:e.type];if(t){return[{text:t("op"===e.type?e.args.map(e=>Ur(this.speak(e))):[e.value],e,e=>Ur(this.speak(e))),id:e.id}]}return"number"===e.type?[this.seg(e,this.number(e.value))]:"string"===e.type?[this.seg(e,e.value.slice(1,-1))]:"symbol"===e.type?[this.seg(e,this.symbol(e.value))]:this.operation(e)}seg(e,t){return{text:t,id:e.id}}number(e){const t=this.w;return e.endsWith("..")?`${e.replace(/\.+$/,"")} ${t.repeating}`:e.startsWith("-")?`${t.negative} ${e.slice(1)}`:e}symbol(e){const t=this.w;if("∞"===e)return t.infinity;if("-∞"===e)return`${t.negative} ${t.infinity}`;if("pi"===e||"π"===e)return t.pi;if("tau"===e||"τ"===e)return"tau";if("\\+"===e)return t.plus;if("\\-"===e)return t.minus;if("°"===e)return t.degrees;if(Hr[e])return t[Hr[e]];if(Dr[e])return Dr[e].toLowerCase();if(/^Δ.+$/.test(e))return`${t.delta} ${this.symbol(e.slice(1))}`;const n=/′+$/.exec(e);return n?`${this.symbol(e.slice(0,-n[0].length))} ${this.primes(n[0].length)}`:e.endsWith("⁻¹")?`${this.symbol(e.slice(0,-2))} ${t.inverse}`:e}primes(e){const t=this.w;return[t.prime,t.doublePrime,t.triplePrime][e-1]??`${e} ${t.prime}`}isCompound(e){if("op"!==e.type)return!1;if("sum"===e.op||"?:"===e.op)return!0;const t=u(e.op);return void 0!==t&&t<=50&&!a(e.op).group}quantity(e){return this.isCompound(e)?[this.seg(e,this.w.quantity),...this.speak(e),this.seg(e,this.w.comma)]:this.speak(e)}argument(e){return this.quantity(e)}operation(e){const{op:t,args:n}=e,[r,s]=n,i=this.w,a=t=>this.seg(e,t),l=()=>n.flatMap((e,t)=>t?[a(i.comma),...this.speak(e)]:this.speak(e));if(Vr[t])return[...this.speak(r),a(i[Vr[t]]),...this.speak(s)];if(o(t)){const e=this.symbol(D(t));return n.length?[a(`${e} ${i.of}`),...this.arguments(n)]:[a(e)]}if(this.names[t]&&!["log","round","fixed","atan2","random","expm1"].includes(t))return[a(`${this.names[t]} ${i.of}`),...this.arguments(n)];switch(t){case"+":return I(s)?[...this.speak(r),a(i.minus),...this.speak(s.args[1])]:[...this.speak(r),a(i.plus),...this.speak(s)];case"-":return I(s)?[...this.speak(r),a(i.plus),...this.speak(s.args[1])]:[...this.speak(r),a(i.minus),...this.quantityIfSum(s)];case"*":return this.product(e);case"/":return this.fraction(e);case"^":return this.power(e);case"_":return[...this.speak(r),a(i.sub),...this.speak(s)];case"neg":return this.isCompound(r)||"op"===r.type&&"neg"===r.op?[a(`${i.negative} ${i.quantity}`),...this.speak(r),a(i.comma)]:[a(i.negative),...this.speak(r)];case"pm":return[a(i.plusOrMinus),...this.speak(r)];case"!":return[...this.quantity(r),a(i.factorial)];case"\\not":return[a(i.not),...this.quantity(r)];case"sqrt":return[a(i.squareRoot),...this.speak(r),...this.pauseAfter(r)];case"root":{const e="number"===r.type?Number(r.value):NaN,t=3===e?i.cubeRoot:2===e?i.squareRoot:i.nthRoot(e?this.ordinal(e):Ur(this.speak(r))+"th");return[a(t),...this.speak(s),...this.pauseAfter(s)]}case"abs":return[a(i.absoluteValue),...this.speak(r),...this.pauseAfter(r)];case"floor":return[a(i.floor),...this.speak(r),...this.pauseAfter(r)];case"ceil":return[a(i.ceiling),...this.speak(r),...this.pauseAfter(r)];case"log":return"symbol"===r.type&&"e"===r.value?[a(`${this.names.ln} ${i.of}`),...this.argument(s)]:[a(`${i.logBase}`),...this.speak(r),a(i.of),...this.argument(s)];case"mod":return[...this.quantity(r),a(i.mod),...this.quantity(s)];case"pmod":return[...this.speak(r),a(`${i.comma} ${i.mod}`),...this.speak(s)];case"perm":return[...this.quantity(r),a(i.permute),...this.quantity(s)];case"comb":return[...this.quantity(r),a(i.choose),...this.quantity(s)];case"round":{const e=0===("number"===s.type?Number(s.value):NaN)?i.nearestWholeNumber:`${Ur(this.speak(s))} ${i.decimalPlaces}`;return[...this.speak(r),a(`${i.comma} ${i.rounded} ${e}`)]}case"fixed":return 0===("number"===s.type?Number(s.value):NaN)?[...this.speak(r),a(`${i.comma} ${i.asWholeNumber}`)]:[...this.speak(r),a(`${i.comma} ${i.writtenTo}`),...this.speak(s),a(i.decimalPlaces)];case"atan2":return[a(`${this.names.atan2} ${i.of}`),...this.speak(r),a(i.over),...this.speak(s)];case"random":return[a(i.randomNumber)];case"expm1":return[a(i.eToThe),...this.speak(r),a(`${i.comma} ${i.minus} 1`)];case"?:":return[a(i.if),...this.speak(r),a(`${i.comma} ${i.then}`),...this.speak(s),a(`${i.comma} ${i.otherwise}`),...this.speak(n[2])];case"sum":return n.flatMap((e,t)=>t?[a(i.plus),...this.speak(e)]:this.speak(e));case"prod":return n.flatMap((e,t)=>t?[a(i.times),...this.quantity(e)]:this.quantity(e));case"mean":case"max":case"min":case"gcd":return[a(`${this.names[t]} ${i.of}`),...l()];case"()":return 2===n.length?[a(i.openInterval),...this.speak(r),a(i.to),...this.speak(s)]:l();case"[]":return 2===n.length?[a(i.closedInterval),...this.speak(r),a(i.to),...this.speak(s)]:[a(i.theList),...l()];case"(]":case"[)":return[a(i.halfOpenInterval),...this.speak(r),a(i.to),...this.speak(s)];case"{}":return[a(i.theSet),...l()];case"der":return this.derivative(e);case"int":return this.integral(e);case"lim":return this.limit(e);case"\\sumidx":return this.bigOperator(e,i.sumFrom,i.sumOver,i.sumOf);case"\\prodidx":return this.bigOperator(e,i.productFrom,i.productOver,i.productOf)}throw new Error(`No speech for '${t}'`)}arguments(e){return 1===e.length?this.argument(e[0]):e.flatMap((e,t)=>t?[{text:this.w.comma,id:e.id},...this.speak(e)]:this.speak(e))}pauseAfter(e){return this.isCompound(e)?[this.seg(e,this.w.comma)]:[]}quantityIfSum(e){return this.quantity(e)}product(e){const[t,n]=e.args,r=this.w;if(I(e))return[this.seg(e,r.negative),...this.speak(n)];if("symbol"===n.type&&"°"===n.value)return[...this.speak(t),this.seg(e,r.degrees)];const s=this.quantity(t),i=this.quantity(n);return this.isCompound(t)||this.isCompound(n)||this.isWord(t)||this.isWord(n)||this.startsWithNumber(n)||"op"===n.type&&"/"===n.op||this.isCall(t)||i[0].text.startsWith("the ")?[...s,this.seg(e,r.times),...i]:[...s,...i]}isWord(e){return"symbol"===e.type&&/^[A-Za-z]{2,}$/.test(e.value)&&!O[e.value]&&!["pi","tau"].includes(e.value)}isCall(e){return"op"===e.type&&(o(e.op)||"prefix"===a(e.op)?.fixity&&100===u(e.op))}startsWithNumber(e){let t=e;for(;"op"===t.type&&t.args.length;)t=t.args[0];return"number"===t.type}fraction(e){const[t,n]=e.args,r=this.w,s=t=>this.seg(e,t);if("number"===t.type&&"number"===n.type&&/^[1-9]$/.test(t.value)&&/^([2-9]|10)$/.test(n.value)){const e=Number(t.value),i=Number(n.value),o=2===i?1===e?r.half:r.halves:r.ordinals[i]+(1===e?"":"s");return[s(`${r.numerators[e]} ${o}`)]}return[...this.quantity(t),...this.isCall(t)?[s(r.comma)]:[],s(r.over),...this.quantity(n)]}power(e){const[t,n]=e.args,r=this.w,s=t=>this.seg(e,t),i=this.isCompound(t)||this.isCall(t)||"number"===t.type&&t.value.startsWith("-")||"op"===t.type&&"/"===t.op?[s(r.quantity),...this.speak(t),s(r.comma)]:this.speak(t);if(this.isCall(t)&&this.names[t.op]&&"number"===n.type&&/^[2-3]$/.test(n.value)&&1===t.args.length){const e=2===Number(n.value)?r.squared:r.cubed;return[s(`${this.names[t.op]} ${e} ${r.of}`),...this.argument(t.args[0])]}if("number"===n.type&&/^(?:[1-9]|10)$/.test(n.value)){const e=Number(n.value);return 2===e||3===e?[...i,s(r.powers[e])]:[...i,s(`${r.toThe} ${r.powers[e]}`)]}if("number"===n.type&&/^\d+$/.test(n.value))return[...i,s(`${r.toThe} ${this.ordinal(Number(n.value))}`)];return!(this.isCompound(n)||"op"===n.type&&"/"===n.op&&this.isCompound(n.args[0]))?[...i,s(r.toThe),...this.speak(n)]:[...i,s(r.toThePowerOf),...this.speak(n),s(r.comma)]}ordinal(e){if(e<=10&&e>=1)return"squared"===this.w.powers[e]?"second":"cubed"===this.w.powers[e]?"third":this.w.powers[e];return`${e}${e%100>=11&&e%100<=13?"th":["th","st","nd","rd"][e%10]??"th"}`}derivative(e){const{n:t,body:n,by:r,variable:s}=W(e),i=this.w,o=t=>this.seg(e,t);if(s){return[o(1===t?i.d:`${i.d} ${2===t?i.squared:3===t?i.cubed:`${i.toThe} ${this.ordinal(t)}`}`),...this.speak(n),o(i.d),...this.speak(r),o(1===t?"":2===t?i.squared:3===t?i.cubed:`${i.toThe} ${this.ordinal(t)}`)]}return[o(`${1===t?i.derivative:2===t?i.secondDerivative:i.nthDerivative(this.ordinal(t))} ${i.withRespectTo}`),...this.speak(r),o(i.of),...this.speak(n),...this.pauseAfter(n)]}integral(e){const{args:t}=e,[n,r,s,i]=t,o=this.w,a=t=>this.seg(e,t),l=t.length>=2&&"symbol"===r.type&&1===r.value.length,u=l?this.speak(r):[a(A(n)||"x")];let c=[];4===t.length?c=[s,i]:3===t.length?c=l?[s]:[r,s]:2!==t.length||l||(c=[r]);return[...2===c.length?[a(o.integralFrom),...this.speak(c[0]),a(o.to),...this.speak(c[1]),a(o.of)]:1===c.length?[a(o.integralFrom),...this.speak(c[0]),a(o.of)]:[a(o.integralOf)],...this.speak(n),a(`${o.comma} ${o.d}`),...u]}limit(e){const{args:t}=e,[n,r,s,i]=t,o=this.w,a=t=>this.seg(e,t);let l;if(t.length>=3){if(l=[...this.speak(r),a(o.approaches),...this.speak(s)],4===t.length){const e=String(i.value??"").toLowerCase().startsWith("r");l.push(a(e?o.fromTheRight:o.fromTheLeft))}}else if(2===t.length&&"op"===r.type&&"→"===r.op)l=[...this.speak(r.args[0]),a(o.approaches),...this.speak(r.args[1])];else{if(2!==t.length)return[a(`${o.limitAs.replace(/ as$/,"")} ${o.of}`),...this.speak(n)];{const e=A(n);l=e?[a(e),a(o.approaches),...this.speak(r)]:this.speak(r)}}return[a(o.limitAs),...l,a(o.of),...this.speak(n),...this.pauseAfter(n)]}bigOperator(e,t,n,r){const{args:s}=e,[i,o,a]=s,l=this.w,u=t=>this.seg(e,t);let c;return c=3===s.length?[u(t),...this.speak(o),u(l.to),...this.speak(a),u(l.of)]:2===s.length?[u(n),...this.speak(o),u(l.of)]:[u(r)],[...c,...this.speak(i),...this.pauseAfter(i)]}}for(const e of[Br,Pr,Vr,Hr,Dr])Object.setPrototypeOf(e,null);function Xr(e,t={}){return Jt(e)?"":function(e,t={}){return Ur(Wr(e,t))}(Qt(e),t)}const Qr={"(":{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.015"},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 Jr(e,t,n=""){const r=Qr[e];return`<svg class="${t}" viewBox="0 0 1 1" preserveAspectRatio="none" aria-hidden="true"${n?` style="${n}"`:""}>${r.fill?`<path d="${r.fill}" fill="currentColor"/>`:`<path d="${r.stroke}" fill="none" stroke="currentColor" vector-effect="non-scaling-stroke"/>`}</svg>`}const Yr=.8,Kr=.2,es=.25,ts=.7,ns="−",rs={"+":"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","?:":"cases","()":"tuple","[]":"list","{}":"set","(]":"interval","[)":"interval","\\sumidx":"sum","\\prodidx":"prod",mod:"mod",pmod:"pmod"},ss={"=":"=","===":"=","≠":"≠","≠=":"≠","<":"<",">":">","≤":"≤","≥":"≥","∈":"∈","∉":"∉","→":"→","≈":"≈","≡":"≡","&":"∧","|":"∨","\\xor":"⊕","\\nand":"↑","\\nor":"↓"},is={"±":"±","∪":"∪","∩":"∩",mod:"mod"},os=["sin","cos","tan","csc","sec","cot","sinh","cosh","tanh"],as={arcsin:"sin",arccos:"cos",arctan:"tan",arcsinh:"sinh",arccosh:"cosh",arctanh:"tanh"},ls=[...os,...Object.keys(as),"ln"],us={atan2:"atan2",max:"max",min:"min",gcd:"gcd",mean:"mean",round:"round",fixed:"fixed",expm1:"expm1",random:"random"},cs={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]},hs={"\\partial":"∂","\\nabla":"∇","\\ell":"ℓ","\\infty":"∞","\\emptyset":"∅"},ps={vec:"→",hat:"ˆ",widehat:"ˆ",tilde:"˜",dot:"˙",ddot:"¨"},fs=["boxed","overline","bar","underline","cancel",...Object.keys(ps)],ms={prefix:"mv",display:!0,fnParens:"auto",trigPowers:!0,inverseTrig:"arc",derivativeBrackets:"[",scriptFractions:"slash",cases:!0,label:!0,attributes:null,style:null},ds=e=>String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),gs=e=>+e.toFixed(3)+"em",bs=(e,t=Yr,n=Kr)=>({html:e,h:t,d:n});function vs(...e){const t=e.flat().filter(Boolean);return{html:t.map(e=>e.html).join(""),h:Math.max(Yr,...t.map(e=>e.h)),d:Math.max(Kr,...t.map(e=>e.d))}}function ys(e,t={}){const n=new ws({...ms,...t}),r=n.render(e,{level:0}),s=`${n.p}${n.o.display?` ${n.p}-display`:""}`,i=function(e,t){if(!1===t||null===t)return null;if("string"==typeof t)return t;try{return"function"==typeof t?t(e):Xr(e)}catch{return null}}(e,n.o.label),o=null===i?r.html:r.html.replace(/^<span /,'<span aria-hidden="true" ');return{html:`<span class="${s}"${null===i?"":` role="math" aria-label="${ds(i)}"`}>${o}</span>`,h:r.h,d:r.d}}class ws{constructor(e){this.o=e,this.p=e.prefix}el(e,t,n="",r=""){return`<span class="${e.split(" ").map(e=>`${this.p}-${e}`).join(" ")}"${n?` style="${n}"`:""}${r}>${t}</span>`}text(e,t){const n=bs(this.el(e,ds(t)));return n.leaf={kind:e,content:ds(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 r="";void 0!==e.id&&(r+=` data-node="${e.id}"`),"op"===e.type&&(r+=` data-op="${ds(e.op)}"`);const s=this.o.attributes&&this.o.attributes(e)||{};for(const[e,t]of Object.entries(s))"class"!==e&&"style"!==e&&(r+=` ${e}="${ds(t)}"`);const i=[s.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(s.class?[s.class]:[]).join(" "),a=n.leaf?n.leaf.content:n.html;return{html:`<span class="${o}"${i?` style="${ds(i)}"`:""}${r}>${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){return this.wrap(e,["number"],this.text("num",e.value.replace(/^-/,ns)))}symbol(e){return O[e]&&(e=O[e]),hs[e]?this.text("ord",hs[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)?bs(this.el("var",ds(e[0]))+this.el("prime",ds(e.slice(1)))):/^Δ[A-Za-z]$/.test(e)?bs(this.el("ord","Δ")+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:n,args:r}=e,[s,i]=r,a=(e,n={})=>this.render(e,{...t,...n,forceParens:n.forceParens||!1,before:n.before||!1}),l=rs[n]??(/^[a-z0-9]+$/i.test(n)?n:"other"),u=t=>this.wrap(e,["op",`op-${l}`],t),c=(t,n)=>T(e,t,n)&&"/"!==t.op?this.fence(a(t)):a(t);if(ls.includes(n)||"log"===n)return u(this.named(e,t));if(us[n])return u(vs(this.word(us[n]),this.fence(this.list(r,t))));if(o(n))return u(this.custom(e,t));if(cs[n])return u(this.fence(this.list(r,t),...cs[n]));if(ss[n]&&2===r.length)return u(vs(c(s,"left"),this.rel(ss[n]),c(i,"right")));if(is[n]&&2===r.length)return u(vs(c(s,"left"),this.bin(is[n]),c(i,"right")));switch(n){case"+":return I(i)?u(vs(c(s,"left"),this.bin(ns),this.wrap(i,["op","op-mul"],this.render(i.args[1],t)))):"number"===i.type&&i.value.startsWith("-")?u(vs(c(s,"left"),this.bin(ns),this.wrap(i,["number"],this.text("num",i.value.slice(1))))):u(vs(c(s,"left"),this.bin("+"),this.signed(i,c(i,"right"))));case"-":return u(vs(c(s,"left"),this.bin(ns),this.signed(i,c(i,"right"))));case"*":return u(this.product(e,t));case"/":return u(this.fraction(e,t));case"^":return u(this.power(e,t));case"_":return u(this.script(a(s,{forceParens:!0}),null,t,a(i,{level:t.level+1})));case"neg":return u(vs(this.text("sign",ns),j(n,s)?this.fence(a(s)):a(s,{before:t.before})));case"pm":return u(vs(this.text("sign","±"),j(n,s)?this.fence(a(s)):a(s)));case"!":return u(vs(j(n,s)?this.fence(a(s)):a(s,{forceParens:!0}),this.text("ord","!")));case"\\not":return u(vs(this.text("sign","¬"),j(n,s)?this.fence(a(s)):a(s)));case"pmod":return u(vs(a(s),this.fence(vs(this.word("mod"),this.text("space",""),a(i)))));case"sqrt":return u(this.radical(a(s)));case"root":return u(this.radical(a(i),this.render(s,{level:t.level+2})));case"abs":return u(this.fence(a(s),"|","|"));case"floor":return u(this.fence(a(s),"⌊","⌋"));case"ceil":return u(this.fence(a(s),"⌈","⌉"));case"loglog":return u(vs(this.word("ln"),this.fence(vs(this.word("ln"),this.fence(a(s))))));case"logloglog":return u(vs(this.word("ln"),this.fence(vs(this.word("ln"),this.fence(vs(this.word("ln"),this.fence(a(s))))))));case"perm":return u(this.script(this.script(bs(""),this.render(s,{level:t.level+1}),t),null,t,this.render(i,{level:t.level+1}),this.word("P")));case"comb":return u(this.fence(this.stack(a(s),a(i),!1)));case"?:":return u(this.o.cases?this.cases(e,t):vs(a(s),this.bin("?"),a(i),this.bin(":"),a(r[2])));case"sum":return u(vs(r.map((e,t)=>t?[this.bin("+"),a(e)]:[a(e)]).flat()));case"prod":return u(vs(r.map((e,t)=>t?[this.bin("·"),a(e)]:[a(e)]).flat()));case"der":return u(this.derivative(e,t));case"int":return u(this.integral(r,t));case"lim":return u(this.limit(r,t));case"\\sumidx":return u(this.bigOperator("sum",r,t));case"\\prodidx":return u(this.bigOperator("prod",r,t))}throw new Error(`Inline Math cannot draw '${n}'`)}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 vs(e.map((e,n)=>n?[this.punct(","),this.render(e,t)]:[this.render(e,t)]).flat())}product(e,t){const[n,r]=e.args;if(I(e))return vs(this.text("sign",ns),this.render(r,t));const s=function(e){const[t,n]=e.args;return{left:T(e,t,"left")&&"/"!==t.op,right:T(e,n,"right")&&"/"!==n.op}}(e),i=C(n,r,s),a=function(e){for(;"op"===e.type;){if(ls.includes(e.op)||"log"===e.op||us[e.op]||o(e.op))return!0;if("^"!==e.op&&"*"!==e.op)return!1;e=e.args[0]}return!1}(r),l=s.left?this.fence(this.render(n,t)):this.render(n,{...t,before:i&&!a}),u=s.right?this.fence(this.render(r,t)):this.render(r,{...t,before:t.before});return vs(l,i?bs(this.el(a?"fnspace":"times","")):this.bin("·"),u)}named(e,t,n=null){const{op:r,args:s}=e,i="log"===r?s[1]:s[0];let o;o=as[r]&&"power"===this.o.inverseTrig?this.script(this.word(as[r]),this.text("num","−1"),t):this.word(r),n&&(o=this.script(o,n,t)),"log"===r&&(o=this.script(o,null,t,this.render(s[0],{level:t.level+1})));const a="auto"===this.o.fnParens&&!t.forceParens&&!t.before&&xs(i),l=this.render(i,{...t,forceParens:!1,before:!1});return vs(o,a?vs(bs(this.el("fnspace","")),l):this.fence(l))}custom(e,t){const n=D(e.op),r=e.args;if(fs.includes(n)&&1===r.length)return this.decorate(n,this.render(r[0],t));return vs(/^[A-Za-z]′*(⁻¹)?$/.test(n)?this.symbol(n):this.word(n),bs(this.el("callgap","")),this.fence(this.list(r,t)))}decorate(e,t){switch(e){case"boxed":return bs(this.el("boxed",t.html),t.h+.22,t.d+.22);case"cancel":return bs(this.el("cancel",t.html),t.h,t.d);case"underline":return bs(this.el("underline",t.html),t.h,t.d+.12);case"overline":case"bar":return bs(this.el("over",t.html),t.h+.14,t.d);default:return bs(this.el("accent",this.el("accent-mark",ps[e])+t.html),t.h+.3,t.d)}}fraction(e,t){const[n,r]=e.args;if(t.level>0&&"slash"===this.o.scriptFractions&&xs(n,!0)&&xs(r,!0)){const e=e=>"op"!==e.type||xs(e)?this.render(e,t):this.fence(this.render(e,t));return vs(e(n),this.text("ord","/"),e(r))}const s=t.level>0||t.inFraction||!this.o.display?.8:1,i={...t,inFraction:!0,forceParens:!1,before:!1};return this.stack(this.render(n,i),this.render(r,i),!0,s)}stack(e,t,n=!0,r=1){const s=e=>1===r?e.html:this.el("scaled",e.html,`font-size:${gs(r)}`),i=n?.06:0,o=es+i/2+.1+Math.max(Kr,r*e.d),a=this.el("frac"+(n?"":" frac-nobar"),this.el("numer",s(e))+this.el("denom",s(t)),`vertical-align:${gs(o)}`);return bs(a,o+Math.max(Yr,r*e.h),Math.max(Yr,r*t.h)+Math.max(Kr,r*t.d)+.1+i/2-es)}power(e,t){const[n,r]=e.args,s={...t,level:t.level+1,forceParens:!1,before:!1,inFraction:!1},i=()=>this.render(r,s);if(this.o.trigPowers&&os.includes(n.op)&&ks(r))return this.wrap(n,["op",`op-${n.op}`],this.named(n,t,i()));if("_"===n.op){const e=this.render(n.args[1],s);return this.wrap(n,["op","op-subscript"],this.script(this.render(n.args[0],{...t,forceParens:!0}),i(),t,e))}const o=T(e,n,"left")||"number"===n.type&&n.value.startsWith("-")||"/"===n.op||ls.includes(n.op)?this.fence(this.render(n,t)):this.render(n,{...t,forceParens:!0});return this.script(o,i(),t)}script(e,t,n,r=null,s=null){const i=n.level>0?.8:ts,o=s?vs(e,s):e;let a=t?Math.max(.42,e.h-.38,i*t.d+.12):0,l=r?Math.max(.2,e.d-.05,i*r.h-.45):0;if(t&&r){const e=.1-(a-i*t.d-(i*r.h-l));e>0&&(l+=e)}const u=e=>this.el("script",e.html,`font-size:${gs(i)}`);if(t&&!r)return bs(e.html+this.el("sup",t.html,`font-size:${gs(i)};vertical-align:${gs(a/i)}`),Math.max(o.h,a+i*t.h),Math.max(o.d,i*t.d-a));if(r&&!t)return bs(o.html+this.el("sub",r.html,`font-size:${gs(i)};vertical-align:${gs(-l/i)}`),Math.max(o.h,i*r.h-l),Math.max(o.d,l+i*r.d));const c=a+i*t.h,h=l+i*r.d,p=this.el("subsup",u(t)+u(r),`vertical-align:${gs(a)};height:${gs(c+h)}`);return bs(o.html+p,Math.max(o.h,c),Math.max(o.d,h))}radical(e,t=null){const n=Math.max(e.h,Yr)+.1+.06,r=Math.max(e.d,Kr),s=n+r,i=Jr("sqrt",`${this.p}-hook`,`height:${gs(s)};width:${gs(.5+.06*(s-1))};vertical-align:${gs(-r)}`);let o="";if(t){const e=.8*ts;o=this.el("rootindex",t.html,`font-size:${gs(e)};vertical-align:${gs((.55*s-r)/e)}`)}return bs(this.el("sqrt",o+i+this.el("radicand",e.html)),n,r)}fence(e,t="(",n=")"){const r=Math.max(e.h,Yr)+Math.max(e.d,Kr),s=r>1.25,i=s?.1:0,o=(e,t)=>{if(!e)return{html:"",w:0};const n={"(":.26,")":.26,"{":.36,"}":.36}[e];if(n){const i=n+(s?Math.min(.2,.05*(r-1)):0);return{html:Jr(e,`${this.p}-delim ${this.p}-delim-${t}`,`width:${gs(i)}`),w:i+.1}}const i={"[":"lbrack","]":"rbrack","|":"vert","⌊":"lfloor","⌋":"rfloor","⌈":"lceil","⌉":"rceil"}[e];return{html:this.el(`delim ${i} delim-${t}`,""),w:"|"===e?.18:.3}},a=o(t,"l"),l=o(n,"r"),u=`padding:${gs(i)} ${gs(l.w)} ${gs(i)} ${gs(a.w)}`,c=bs(this.el("fence",a.html+e.html+l.html,u),Math.max(e.h,Yr)+i,Math.max(e.d,Kr)+i);return c.fenced=!0,c}derivative(e,t){const{n:n,body:r,by:s,variable:i}=W(e),o={...t,level:t.level+1},a=()=>this.text("d","d"),l=()=>n>1?this.render({type:"number",value:String(n)},o):null,c={...t,inFraction:!0},h=vs(a(),l()?this.script(this.render(s,c),l(),c):this.render(s,c)),p=e=>vs(l()?this.script(a(),l(),c):a(),e||[]),f=t.level>0||t.inFraction||!this.o.display?.8:1;if(i)return this.stack(p(this.render(r,c)),h,!0,f);const m=_(r)&&u(_(r))<100,[d,g]="("===this.o.derivativeBrackets?["(",")"]:["[","]"],b=m?this.fence(this.render(r,t),d,g):this.render(r,t);return vs(this.stack(p(),h,!0,f),b)}integral(e,t){const[n,r,s,i]=e,o=e=>this.render(e,t),a=e=>e?this.render(e,{...t,level:t.level+1}):null,l=()=>this.text("var",A(n)||"x");let u,c=null,h=null;switch(e.length){case 1:u=l();break;case 2:P(r)?u=o(r):(u=l(),c=a(r));break;case 3:P(r)?(u=o(r),c=a(s)):(u=l(),c=a(r),h=a(s));break;default:u=o(r),c=a(s),h=a(i)}const p=o(n),f=bs(this.el("dx",this.el("d","d")+u.html),u.h,u.d);return vs(this.bigSign("int",p,c,h,t),p,f)}bigSign(e,t,n,r,s){const i=!this.o.display||s.level>0,o=Math.max(i?.6:.95,Math.max(t.h-es,t.d+es)+.12),a=Jr(e,`${this.p}-bigsign ${this.p}-${e}sign`,`height:${gs(2*o)};width:${gs(i?.38:.5)};vertical-align:${gs(es-o)}`);if(!n&&!r)return bs(a,es+o,o-es);const l=ts,u=r||bs(""),c=n||bs(""),h=es+o-l*u.h;c.d;const p=this.el("limits",this.el("script",u.html,`font-size:${gs(l)}`)+this.el("script lower",c.html,`font-size:${gs(l)}`),`vertical-align:${gs(h)};height:${gs(2*o)}`);return bs(a+p,es+o,o-es)}limit(e,t){const[n,r,s,i]=e,o={...t,level:t.level+1},a=e=>this.render(e,o),l=()=>this.rel("→");let u;switch(e.length){case 1:return vs(this.word("lim"),bs(this.el("fnspace","")),this.render(n,t));case 2:{const e=A(n),t="number"===r.type||"symbol"===r.type&&r.value.includes("∞");u=e&&t?vs(this.text("var",e),l(),a(r)):a(r);break}case 3:u=vs(a(r),l(),a(s));break;default:{const e=E(i).toLowerCase().startsWith("r")?"+":ns;u=vs(a(r),l(),this.script(a(s),this.wrap(i,["symbol"],this.text("ord",e)),o))}}return vs(this.under(this.word("lim"),u,t),this.render(n,t))}under(e,t,n){return!this.o.display||n.level>0?this.script(e,null,n,t):bs(this.el("under",e.html+this.el("script",t.html,`font-size:${gs(.7)}`)),e.h,Math.max(e.d,Kr)+.05+.7*(t.h+t.d))}bigOperator(e,t,n){const[r,s,i]=t,o={...n,level:n.level+1},a=s?this.render(s,o):null,l=i?this.render(i,o):null,u=this.render(r,n);if(!this.o.display||n.level>0){const t=.55,r=Jr(e,`${this.p}-bigsign`,`height:${gs(2*t)};width:${gs(.8)};vertical-align:${gs(es-t)}`);return vs(this.script(bs(r,es+t,t-es),l,n,a),u)}const c=.68,h=ts,p=Jr(e,`${this.p}-bigsign`,`height:${gs(1.36)};width:${gs("sum"===e?1:1.05)}`),f=l?1.01+h*l.d:es-c,m=e=>this.el("script",e.html,`font-size:${gs(h)}`),d=this.el("bigop",(l?m(l):"")+p+(a?m(a):""),`vertical-align:${gs(f)}`);return vs(bs(d,.93+(l?.08+h*(l.h+l.d):0),c-es+(a?.08+h*(a.h+a.d):0)),u)}cases(e,t){const n=[];let r=e;for(;"op"===r.type&&"?:"===r.op;)n.push([this.render(r.args[1],t),vs(this.word("if"),this.text("space",""),this.render(r.args[0],t))]),r=r.args[2];n.push([this.render(r,t),this.word("otherwise")]);const s=n.map(([e,t])=>({h:Math.max(e.h,t.h),d:Math.max(e.d,t.d)})),i=s.reduce((e,t)=>e+t.h+t.d,0)+.25*(n.length-1),o=es+i/2-s[0].h,a=n.map(([e,t])=>this.el("case-value",e.html)+this.el("case-cond",t.html)).join(""),l=bs(this.el("cases",a,`vertical-align:${gs(o)}`),es+i/2,i/2-es);return this.fence(l,"{","")}}function xs(e,t=!1){return"number"===e.type?!e.value.startsWith("-")||t:"symbol"===e.type||"op"===e.type&&("abs"===e.op?!t:!t||"neg"!==e.op&&"^"!==e.op?"*"===e.op&&!I(e)&&e.args.every(e=>"number"===e.type&&!e.value.startsWith("-")||$s(e)||"*"===e.op&&xs(e,t)):xs(e.args[0],!0)&&("neg"===e.op||xs(e.args[1],!0)))}const $s=e=>"symbol"===e.type&&(1===e.value.length||/^[α-ωΑ-Ω]$/.test(e.value)||Boolean(O[e.value])),ks=e=>"number"===e.type&&/^[1-9]\d*$/.test(e.value)&&Number(e.value)<10;const qs=e=>M(e).join(" ");function Ms(e,t){const n=new Set;Ns(e,t,n);const r=[];return S(e,e=>{n.has(e)&&r.push(e)}),r}function Ns(e,t,n){if(null!=t)if(Array.isArray(t))t.forEach(t=>Ns(e,t,n));else if("number"!=typeof t)if("function"!=typeof t){if("string"==typeof t){const r=qs(Xt(t));return void S(e,e=>{qs(e)===r&&n.add(e)})}if(t.path){const r=Ss(e,t.path);return void(r&&n.add(r))}if(t.type){const r=qs(t);S(e,e=>{e!==t&&qs(e)!==r||n.add(e)})}}else S(e,(e,r)=>{t(e,r)&&n.add(e)});else S(e,e=>{e.id===t&&n.add(e)})}function Ss(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 As(e,t){const n=[],r=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),r(e.args[t]))return!0;n.pop()}return!1};return r(e)?n:null}function Os(e){let n=0;const r=e=>{"op"===e.type&&(e.args.forEach(r),a(e.op)?.arity===t&&n++),e.id=n++};return r(e),e}function Es(e,t={}){const{blocks:n}=t;if("string"==typeof e)return Xt(e,n?{blocks:e=>n(e,t.scope)}:{});if(Array.isArray(e))return q(e);if(e&&"object"==typeof e&&e.type)return void 0===e.id?Os(structuredClone(e)):e;throw new Error("Inline Math needs an expression, standard postfix or a tree")}function Is(e,t){const{colors:n,highlight:r,scope:s,blocks:i,...o}=t,a=new Map;for(const[t,r]of function(e){return e?Array.isArray(e)?e:Object.entries(e).map(([e,t])=>[/^\d+$/.test(e)?Number(e):e,t]):[]}(n))if(_s(r))for(const n of Ms(e,t))a.set(n,`color:${r}`);const l=new Set(void 0===r?[]:Ms(e,r));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 _s(e){return"string"==typeof e&&/^[#\w\s.,%()/+-]+$/.test(e)&&!/url\s*\(|expression/i.test(e)}function Ts(e,t={}){return Es(e,{...t,blocks:t.blocks??Fr})}function js(e,t={}){return function(e,t={}){const n=Es(e,t);return ys(n,Is(n,t)).html}(e,{...t,blocks:t.blocks??Fr})}class Cs{constructor(e,t,n={}){this.element=e,this.options=n,this.p=n.prefix||"mv",this.handlers=[],this.set(t)}set(e,{animate:t=!1,duration:n=600,easing:r="ease-in-out"}={}){const s=t&&this.tree?this.snapshot():null;return this.tree=Ts(e,this.options),this.element.innerHTML=ys(this.tree,Is(this.tree,this.options)).html,this.root=this.element.firstElementChild,this.handlers.length&&this.root.classList.add(`${this.p}-clickable`),s&&this.morph(s,{duration:n,easing:r}),this}nodes(e){return Ms(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 r=Number(n.dataset.node),s=Ms(this.tree,r)[0];t({node:s,id:r,path:As(this.tree,r),element:n,event:e})};return this.element.addEventListener(e,n),this.handlers.push([e,n]),this.root.classList.add(`${this.p}-clickable`),()=>this.element.removeEventListener(e,n)}segments(e={}){return function(e,t={}){return Jt(e)?[]:Wr(Qt(e),t)}(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 r=this.elementOf(n);if(r){const t=qs(n);e.has(t)||e.set(t,[]),e.get(t).push(r.getBoundingClientRect())}"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 r=s=>{const i=this.elementOf(s),o=i&&e.get(qs(s));if(o&&o.length){const e=o.shift(),r=i.getBoundingClientRect(),s=e.left-r.left,a=e.top-r.top,l=r.width?e.width/r.width:1,u=r.height?e.height/r.height:1;return void((Math.abs(s)+Math.abs(a)>.5||Math.abs(l-1)+Math.abs(u-1)>.01)&&i.animate([{transformOrigin:"0 0",transform:`translate(${s}px, ${a}px) scale(${l}, ${u})`},{transformOrigin:"0 0",transform:"none"}],{duration:t,easing:n}))}"op"===s.type?s.args.forEach(r):i&&i.animate([{opacity:0},{opacity:0},{opacity:1}],{duration:t,easing:n})};r(this.tree)}}const zs=new RegExp("(\\d+)","g");function Ls(e,{delimiters:t=["$$","$","\\[","\\("]}={}){const n=[];let r="",s=0;const i=String(e),o=e=>0===e||"\n"===i[e-1],a=(e,t,r)=>(n.push({source:e,display:t,raw:r}),`${n.length-1}`);for(;s<i.length;){if(o(s)){const e=/^( {0,3})(`{3,}|~{3,})([^\n]*)\n?/.exec(i.slice(s));if(e){const t=e[2],n=new RegExp(`\\n {0,3}${"`"===t[0]?"`":"~"}{${t.length},}[ \\t]*(?=\\n|$)`),o=i.slice(s+e[0].length),l=n.exec(`\n${o}`),u=l?o.slice(0,Math.max(0,l.index-1)):o,c=e[0].length+(l?l.index-1+l[0].length:o.length),h=i.slice(s,s+c);"math"===e[3].trim()?r+=a(u,!0,h):r+=h,s+=c;continue}}const e=i[s];if("`"===e){const e=/^`+/.exec(i.slice(s))[0],t=i.indexOf(e,s+e.length);if(t>-1){r+=i.slice(s,t+e.length),s=t+e.length;continue}r+=e,s+=e.length;continue}if("\\"===e){const e=i.slice(s,s+2),n="\\["===e?"\\]":"\\("===e?"\\)":null;if(n&&t.includes(e)){const t=i.indexOf(n,s+2);if(t>-1){r+=a(i.slice(s+2,t),"\\["===e,i.slice(s,t+2)),s=t+2;continue}}r+=e,s+=2;continue}if("$"===e)if("$"===i[s+1]&&t.includes("$$")){const e=i.indexOf("$$",s+2);if(e>-1){r+=a(i.slice(s+2,e),!0,i.slice(s,e+2)),s=e+2;continue}}else if(t.includes("$")&&i[s+1]&&!/\s/.test(i[s+1])){const e=Rs(i,s+1);if(e>-1){r+=a(i.slice(s+1,e),!1,i.slice(s,e+1)),s=e+1;continue}}r+=e,s++}return{text:r,math:n}}function Rs(e,t){for(let n=t;n<e.length;n++){const t=e[n];if("\\"!==t){if("`"===t)return-1;if("\n"===t&&/^\n[ \t]*\n/.test(e.slice(n)))return-1;if("$"===t&&!/\s/.test(e[n-1])&&!/\d/.test(e[n+1]??"")&&"$"!==e[n+1])return n}else n++}return-1}const Zs=e=>String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),Fs=/^\s*([A-Za-zͰ-Ͽ](?:_\{?\w+\}?)?)\s*(?::=|=)\s*([^=<>≤≥]+)$/;function Bs(e,t,n){const{source:r,display:s}=e;try{const e=js(r,{...t.math,display:s,blocks:t.blocks,scope:n});return!1!==t.define&&function(e,t){const n=Fs.exec(e);if(!n||/\{\{/.test(n[2]))return;try{const e=Zr(n[2],t);"number"!=typeof e.value&&"bigint"!=typeof e.value||(t[n[1].replace(/[{}]/g,"")]=e.exact?e.text:e.value)}catch{}}(r,n),s?`<span class="mv-md-display">${e}</span>`:`<span class="mv-md-math">${e}</span>`}catch(t){return`<span class="mv-md-error" title="${Zs(t.message)}"><code>${Zs(e.raw)}</code></span>`}}const Ps=/^(https?:|mailto:|#|\/|\.{0,2}\/|[^:]*$)/i,Ds=e=>Ps.test(e.trim())?Zs(e.trim()):"#";function Ws(e,t,n){const r=[],s=e=>(r.push(e),`${r.length-1}`);let i=e;return i=i.replace(/(`+)([\s\S]*?[^`])\1(?!`)/g,(e,t,r)=>s(`<code>${Zs(n(r.trim()))}</code>`)),i=i.replace(/\\([\\`*_{}[\]()#+\-.!|~$<>"'])/g,(e,t)=>s(Zs(t))),i=i.replace(/<((?:https?:\/\/|mailto:)[^\s>]+)>/g,(e,t)=>s(`<a href="${Ds(t)}">${Zs(t)}</a>`)),t.html&&(i=i.replace(/<\/?[A-Za-z][^>]*>/g,e=>s(e))),i=i.replace(/!\[([^\]]*)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,t,n,r)=>s(`<img src="${Ds(n)}" alt="${Zs(t)}"${r?` title="${Zs(r)}"`:""}>`)),i=i.replace(/\[([^\]]+)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,r,i,o)=>s(`<a href="${Ds(i)}"${o?` title="${Zs(o)}"`:""}>${Ws(r,t,n)}</a>`)),i=Zs(i),i=i.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g,"<strong>$2</strong>"),i=i.replace(/(^|[^*\w])\*(?=\S)([\s\S]*?\S)\*(?!\*)/g,"$1<em>$2</em>"),i=i.replace(/(^|[^_\w])_(?=\S)([\s\S]*?\S)_(?![_\w])/g,"$1<em>$2</em>"),i=i.replace(/~~(?=\S)([\s\S]*?\S)~~/g,"<del>$1</del>"),i=i.replace(/( {2,}|\\)\n/g,"<br>\n"),i.replace(/(\d+)/g,(e,t)=>r[Number(t)])}const Us=/^( {0,3})(#{1,6}\s|>|```|~~~|([-*+]|\d{1,9}[.)])\s|(\*[ \t]*){3,}$|(-[ \t]*){3,}$|(_[ \t]*){3,}$)/,Vs=/^( {0,3})([-*+]|\d{1,9}[.)])(\s+|$)/,Hs=/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;function Gs(e,t,n){const r=[];let s=0;const i=e=>Ws(e,t,n);for(;s<e.length;){const o=e[s];if(!o.trim()){s++;continue}const a=/^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)/.exec(o);if(a){const t=[];for(s++;s<e.length&&!new RegExp(`^ {0,3}${"`"===a[1][0]?"`":"~"}{${a[1].length},}\\s*$`).test(e[s]);)t.push(e[s++]);s++;const i=a[2]?` class="language-${Zs(a[2])}"`:"";r.push(`<pre><code${i}>${Zs(n(t.join("\n")))}</code></pre>`);continue}const l=/^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/.exec(o);if(l){r.push(`<h${l[1].length}>${i(l[2])}</h${l[1].length}>`),s++;continue}if(/^ {0,3}((\*[ \t]*){3,}|(-[ \t]*){3,}|(_[ \t]*){3,})$/.test(o)){r.push("<hr>"),s++;continue}if(/^ {0,3}>/.test(o)){const i=[];for(;s<e.length&&e[s].trim()&&(/^ {0,3}>/.test(e[s])||i.length);)i.push(e[s].replace(/^ {0,3}> ?/,"")),s++;r.push(`<blockquote>\n${Gs(i,t,n)}\n</blockquote>`);continue}const u=Vs.exec(o);if(u){const i=/\d/.test(u[2]),o=i?parseInt(u[2],10):1,a=[];let l=!1;for(;s<e.length;){const t=Vs.exec(e[s]);if(!t||/\d/.test(t[2])!==i)break;const n=t[0].length,r=[e[s].slice(n)];for(s++;s<e.length;){const t=e[s];if(!t.trim()){const t=e[s+1];if(void 0!==t&&t.startsWith(" ".repeat(Math.min(n,4)))&&t.trim()){r.push(""),l=!0,s++;continue}void 0!==t&&Vs.test(t)&&(l=!0);break}if(t.startsWith(" ".repeat(Math.min(n,4))))r.push(t.slice(Math.min(n,4)));else{if(Vs.test(t)||Us.test(t))break;r.push(t)}s++}for(a.push(r);s<e.length&&!e[s].trim()&&void 0!==e[s+1]&&Vs.test(e[s+1]);)s++}const c=i?"ol":"ul",h=a.map(e=>{let r=Gs(e,t,n);return l||(r=r.replace(/^<p>([\s\S]*?)<\/p>/,"$1").replace(/\n<p>([\s\S]*?)<\/p>/g,"\n$1")),`<li>${r}</li>`});r.push(`<${c}${i&&1!==o?` start="${o}"`:""}>\n${h.join("\n")}\n</${c}>`);continue}if(o.includes("|")&&void 0!==e[s+1]&&Hs.test(e[s+1])&&e[s+1].includes("-")){const t=e=>e.trim().replace(/^\|/,"").replace(/\|$/,"").split(/(?<!\\)\|/).map(e=>e.trim()),n=t(e[s+1]).map(e=>e.startsWith(":")&&e.endsWith(":")?"center":e.endsWith(":")?"right":e.startsWith(":")?"left":""),a=(e,t,r)=>`<${e}${n[r]?` style="text-align:${n[r]}"`:""}>${i(t)}</${e}>`,l=t(o);s+=2;const u=[];for(;s<e.length&&e[s].trim()&&e[s].includes("|");)u.push(t(e[s++]));r.push(`<table>\n<thead><tr>${l.map((e,t)=>a("th",e,t)).join("")}</tr></thead>\n<tbody>\n${u.map(e=>`<tr>${l.map((t,n)=>a("td",e[n]??"",n)).join("")}</tr>`).join("\n")}\n</tbody>\n</table>`);continue}if(/^( {4}|\t)/.test(o)){const t=[];for(;s<e.length&&(/^( {4}|\t)/.test(e[s])||!e[s].trim());)t.push(e[s++].replace(/^( {4}|\t)/,""));for(;t.length&&!t[t.length-1].trim();)t.pop();r.push(`<pre><code>${Zs(n(t.join("\n")))}</code></pre>`);continue}const c=[];for(;s<e.length&&e[s].trim()&&(!c.length||!Us.test(e[s])||/^ {0,3}[-=]+\s*$/.test(e[s]));){if(c.length&&/^ {0,3}(=+|-+)\s*$/.test(e[s])){const t="="===e[s].trim()[0]?1:2;r.push(`<h${t}>${i(c.join("\n"))}</h${t}>`),c.length=0,s++;break}c.push(e[s].replace(/^ {0,3}/,"")),s++}c.length&&r.push(`<p>${i(c.join("\n"))}</p>`)}return r.join("\n")}function Xs(e,t={},n=e=>e){return Gs(String(e).replace(/\r\n?/g,"\n").split("\n"),t,n)}function Qs(e,t={}){const{text:n,math:r}=Ls(e,t),s={...t.scope??{}},i=r.map(e=>Bs(e,t,s));return(t.render?t.render(n):Xs(n,t,e=>e.replace(zs,(e,t)=>r[Number(t)].raw))).replace(new RegExp("<p>\\s*(\\d+)\\s*</p>","g"),(e,t)=>r[Number(t)].display?`<div class="mv-md-block">${i[Number(t)]}</div>`:e).replace(zs,(e,t)=>i[Number(t)])}const Js=new Map,Ys=-1,Ks="\\:",ei=e=>"string"==typeof e&&e.startsWith(Ks)&&e.length>2;function ti(e){if(!e||!e.symbol)throw new Error("operator needs a symbol");if(!Number.isInteger(e.arity)||e.arity<0&&e.arity!==Ys)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 Js.set(t.symbol,t),t}const ni=Object.freeze({symbol:Ks,arity:Ys,commutative:!1,fold:null,label:"function"});function ri(e){const t=Js.get(e);return t||(ei(e)?{...ni,symbol:e,label:e.slice(2)}:null)}function si(e){return Js.has(e)||ei(e)}const ii=e=>Number.isFinite(e)&&Number.isInteger(e)?e:null,oi=e=>Number.isFinite(e)?e:null;!function(){ti({symbol:"+",arity:2,commutative:!0,label:"add",fold:(e,t)=>oi(e+t)}),ti({symbol:"-",arity:2,label:"subtract",fold:(e,t)=>oi(e-t)}),ti({symbol:"*",arity:2,commutative:!0,label:"multiply",fold:(e,t)=>oi(e*t)}),ti({symbol:"/",arity:2,label:"divide",fold:(e,t)=>0===t?null:ii(e/t)}),ti({symbol:"^",arity:2,label:"power",fold:(e,t)=>Number.isInteger(t)&&Math.abs(t)<=64?oi(e**t):null}),ti({symbol:"neg",arity:1,label:"negate",fold:e=>oi(-e)}),ti({symbol:"pm",arity:1,label:"plus or minus"}),ti({symbol:"±",arity:2,label:"plus or minus"}),ti({symbol:"mod",arity:2,label:"modulo",fold:(e,t)=>0===t?null:ii((e%t+t)%t)}),ti({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}),ti({symbol:"_",arity:2,label:"subscript"}),ti({symbol:"der",arity:2,label:"derivative"}),ti({symbol:"int",arity:Ys,label:"integral"}),ti({symbol:"lim",arity:Ys,label:"limit"}),ti({symbol:"\\sumidx",arity:Ys,label:"sum over an index"}),ti({symbol:"\\prodidx",arity:Ys,label:"product over an index"}),ti({symbol:"abs",arity:1,label:"absolute value",fold:e=>oi(Math.abs(e))}),ti({symbol:"floor",arity:1,label:"floor",fold:e=>oi(Math.floor(e))}),ti({symbol:"ceil",arity:1,label:"ceiling",fold:e=>oi(Math.ceil(e))}),ti({symbol:"round",arity:2,label:"round",fold:(e,t)=>Number.isInteger(t)?oi(Math.round(e*10**t)/10**t):null}),ti({symbol:"fixed",arity:2,label:"fixed",fold:()=>null}),ti({symbol:"sqrt",arity:1,label:"square root",fold:e=>ii(Math.sqrt(e))}),ti({symbol:"root",arity:2,label:"nth root",fold:(e,t)=>ii(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","arcsinh","arccosh","arctanh","ln","loglog","logloglog","expm1"])ti({symbol:e,arity:1,label:e});ti({symbol:"log",arity:2,label:"log to a base"}),ti({symbol:"atan2",arity:2,label:"atan2"}),ti({symbol:"perm",arity:2,label:"permutations"}),ti({symbol:"comb",arity:2,label:"combinations"}),ti({symbol:"random",arity:0,label:"random"});for(const e of["max","min","gcd","mean","sum","prod"])ti({symbol:e,arity:Ys,label:e});for(const e of["()","[]","{}","(]","[)"])ti({symbol:e,arity:Ys,label:"group"});for(const e of["=","===","≠","≠=","<",">","≤","≥","∈","∉","∪","∩","≈","≡","→","pmod","&","|","\\xor","\\nand","\\nor"])ti({symbol:e,arity:2,label:e});ti({symbol:"\\not",arity:1,label:"not"}),ti({symbol:"?:",arity:3,label:"if then else"})}();const ai="num",li="sym",ui="op",ci=Object.freeze([]);class hi extends Error{constructor(e){super(e),this.name="ExprError"}}function pi(e){if("number"!=typeof e||!Number.isFinite(e))throw new hi(`not a finite number: ${e}`);const t=(n=e,Object.is(n,-0)?"0":String(n));var n;return Object.freeze({type:ai,token:t,value:e,args:ci,s:t})}function fi(e){if("string"!=typeof e||""===e)throw new hi("symbol needs a non-empty token");return Object.freeze({type:li,token:e,value:null,args:ci,s:e})}function mi(e){const t=/^(-?)0*(\d+?)(?:\.(\d*?)0*)?$/.exec(String(e));if(!t)throw new hi(`not an exact decimal: ${e}`);const[,n,r,s=""]=t,i=s?`${r}.${s}`:r,o=/^0(\.0*)?$/.test(i)?"0":n+i;return Object.freeze({type:ai,token:o,value:Number(o),args:ci,s:o})}const di=/^-?\d+(\.\d+)?$/;function gi(e){const t=String(e);if(di.test(t))return mi(t);if(""!==t&&!/\s/.test(t)){const e=Number(t);if(Number.isFinite(e))return pi(e)}return fi(t)}function bi(e,t){const n=ri(e);if(!n)throw new hi(`unknown operator "${e}"`);if(n.arity!==Ys&&t.length!==n.arity)throw new hi(`"${e}" takes ${n.arity} operand(s), got ${t.length}`);const r=Object.freeze(t.slice()),s=n.arity===Ys?` ${r.length}`:"",i=`${r.length?r.map(e=>e.s).join(" "):""}${r.length,""}${s} ${e}`.trimStart();return Object.freeze({type:ui,op:e,token:e,value:null,args:r,s:i})}const vi=e=>e.type===ai,yi=e=>e.type===ui;function wi(e){return xi(function(e){const t=String(e).trim();return""===t?[]:t.split(/\s+/)}(e))}function xi(e){if(!Array.isArray(e))throw new hi("fromPostfix needs an array of tokens");if(0===e.length)throw new hi("empty expression");const t=[];for(let n=0;n<e.length;n++){const r=String(e[n]);if(si(r)){let e=ri(r).arity;if(e===Ys){const s=t.pop();if(e=s&&s.type===ai&&Number.isInteger(s.value)&&s.value>=0?s.value:-1,e<0)throw new hi(`"${r}" at position ${n+1} takes any number of operands, so a count must come before it`)}if(t.length<e)throw new hi(`"${r}" at position ${n+1} needs ${e} operand(s), only ${t.length} on the stack`);const s=t.splice(t.length-e,e);t.push(bi(r,s))}else t.push(gi(r))}if(1!==t.length){const n=[...new Set(e.filter(e=>!si(e)))];throw new hi(`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 $i(e){if(e.type!==ui)return 0;let t=0;for(const n of e.args)t=Math.max(t,$i(n));return t+1}function ki(e){if(e.type!==ui)return 1;let t=1;for(const n of e.args)t+=ki(n);return t}function qi(e,t=[]){if(e.type!==ui)t.push(e.token);else for(const n of e.args)qi(n,t);return t}function Mi(e){return e.type===ai||e.type!==li&&e.args.every(Mi)}function Ni(e,t="pre",n=[],r=[]){"pre"===t&&r.push({node:e,path:n});for(let s=0;s<e.args.length;s++)Ni(e.args[s],t,n.concat(s),r);return"post"===t&&r.push({node:e,path:n}),r}function Si(e,t,n){if(0===t.length)return n;const[r,...s]=t,i=e.args.slice();return i[r]=Si(i[r],s,n),bi(e.op,i)}class Ai extends Error{constructor(e){super(e),this.name="CasError"}}const Oi=1e5,Ei=e=>e<0n?-e:e,Ii=e=>0n===e?0:Ei(e).toString(2).length;function _i(e,t){for(e=Ei(e),t=Ei(t);t;)[e,t]=[t,e%t];return e}class Ti{constructor(e,t=1n){if(0n===t)throw new Ai("division by zero");t<0n&&(e=-e,t=-t);const n=_i(e,t)||1n;if(this.n=e/n,this.d=t/n,Ii(this.n)>Oi||Ii(this.d)>Oi)throw new Ai("a number too large to keep exactly")}static of(e){return new Ti(BigInt(e))}add(e){return new Ti(this.n*e.d+e.n*this.d,this.d*e.d)}sub(e){return new Ti(this.n*e.d-e.n*this.d,this.d*e.d)}mul(e){return new Ti(this.n*e.n,this.d*e.d)}div(e){if(0n===e.n)throw new Ai("division by zero");return new Ti(this.n*e.d,this.d*e.n)}neg(){return new Ti(-this.n,this.d)}abs(){return this.n<0n?this.neg():this}inv(){return Ti.ONE.div(this)}pow(e){if((e=BigInt(e))<0n)return this.inv().pow(-e);if((0n===this.n||1n===Ei(this.n))&&1n===this.d)return 0n===e||-1n===this.n&&e%2n==0n?Ti.ONE:this;if(BigInt(Math.max(Ii(this.n),Ii(this.d)))*e>BigInt(Oi))throw new Ai("a power too large to work out exactly");return new Ti(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 Ti(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(Ii(this.n),Ii(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 ji(e){const t=/^(-?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(String(e));if(!t||""===t[2]&&!t[3])return null;const[,n,r,s="",i="0"]=t;let o=new Ti(BigInt((r||"0")+s),10n**BigInt(s.length));const a=Number(i);return a&&(o=o.mul(Ti.of(10).pow(a))),n?o.neg():o}function Ci(e,t){if(e<2n)return e;if(t>=Ii(e))return 1n;const n=BigInt(t);let r=1n<<BigInt(Math.ceil(Ii(e)/t));for(;;){const t=((n-1n)*r+e/r**(n-1n))/n;if(t>=r)break;r=t}for(;r**n>e;)r--;for(;(r+1n)**n<=e;)r++;return r}Ti.ZERO=new Ti(0n),Ti.ONE=new Ti(1n),Ti.MINUS_ONE=new Ti(-1n),Ti.HALF=new Ti(1n,2n);const zi=(()=>{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 Li(e,t){const n=BigInt(t);let r=1n,s=1n,i=e;for(const e of zi){if(e*e>i)break;if(i%e)continue;let t=0n;for(;i%e===0n;)i/=e,t++;r*=e**(t/n),s*=e**(t%n)}if(i>1n){const e=function(e,t){if(e<0n)return null;if(e<2n)return e;const n=Ci(e,t);return n**BigInt(t)===e?n:null}(i,t);null!==e?r*=e:s*=i}return{outside:r,inside:s}}const Ri=new Set(["pi","e","π"]),Zi={complex:!1};function Fi(e,t){const n=Zi.complex;Zi.complex=Boolean(e);try{return t()}finally{Zi.complex=n}}const Bi=e=>Ri.has(e)||Zi.complex&&"i"===e,Pi=e=>Zi.complex&&"atom"===e.k&&"sym"===e.node.type&&"i"===e.node.token,Di=e=>({k:"num",q:e}),Wi=Di(Ti.ONE),Ui=Di(Ti.ZERO),Vi=Di(Ti.HALF),Hi=e=>"num"===e.k,Gi=e=>({k:"atom",node:e}),Xi=new WeakMap;function Qi(e){let t=Xi.get(e);return void 0===t&&Xi.set(e,t=Oo(e).s),t}function Ji(e){if("num"===e.k)return 0;if("atom"===e.k)return"sym"===e.node.type&&Bi(e.node.token)?0:1;if("add"===e.k)return Math.max(...e.terms.map(e=>Ji(e.x)));let t=0;for(const n of e.fs){const e=Ji(n.b);e&&(t+=e*(Hi(n.e)?n.e.q.toNumber():1))}return t}function Yi(e,t){return"num"===e.k?t&&!Hi(t)?3:0:Pi(e)?1.5:"atom"===e.k&&"sym"===e.node.type?Bi(e.node.token)?t&&!Hi(t)?3:1:2:"atom"===e.k?3:4}const Ki=(e,t)=>e<t?-1:e>t?1:0;function eo(e){const t=new Map,n=(e,n)=>{"atom"!==e.k||"sym"!==e.node.type||Bi(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,Hi(t.e)?t.e.q.toNumber():1);else n(e,1);return t}function to(e,t){const n=Ji(t.x)-Ji(e.x);if(n)return n;const r=eo(e.x),s=eo(t.x);for(const e of[...new Set([...r.keys(),...s.keys()])].sort()){const t=(s.get(e)??0)-(r.get(e)??0);if(t)return t}return Ki(Qi(e.x),Qi(t.x))}function no(e,t){return e.isOne?t:e.isZero?Ui:oo([Di(e),t])}function ro(e){if("num"===e.k)return{coef:e.q,rest:null};if("mul"!==e.k||e.c.isOne)return{coef:Ti.ONE,rest:e};const t=1===e.fs.length&&Hi(e.fs[0].e)&&e.fs[0].e.q.isOne?e.fs[0].b:{k:"mul",c:Ti.ONE,fs:e.fs};return{coef:e.c,rest:t}}function so(e){let t=Ti.ZERO;const n=new Map,r=(e,t)=>{const r=Qi(t),s=n.get(r);s?s.coef=s.coef.add(e):n.set(r,{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)r(e.coef,e.x)}else{const{coef:e,rest:t}=ro(n);r(e,t)}const s=[...n.values()].filter(e=>!e.coef.isZero);return s.length?t.isZero&&1===s.length?no(s[0].coef,s[0].x):(s.sort(to),{k:"add",c:t,terms:s}):Di(t)}function io(e,t){if(!Hi(t))return e.isOne?{coef:Ti.ONE,fs:[]}:{coef:Ti.ONE,fs:[{b:Di(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 Ai("division by zero");return{coef:Ti.ZERO,fs:[]}}if(e.isOne)return{coef:Ti.ONE,fs:[]};if(e.sign<0){if(n.d%2n==1n){const{coef:r,fs:s}=io(e.neg(),t);return{coef:n.n%2n==0n?r:r.neg(),fs:s}}if(Zi.complex&&2n===n.d){const{coef:r,fs:s}=io(e.neg(),t);return{coef:r,fs:[...s,{b:uo,e:Di(new Ti(n.n))}]}}return{coef:Ti.ONE,fs:[{b:Di(e),e:t}]}}if(!e.isInteger){const r=io(new Ti(e.n),t),s=io(new Ti(e.d),Di(n.neg()));return{coef:r.coef.mul(s.coef),fs:[...r.fs,...s.fs]}}const r=n.floor(),s=n.sub(r);if(BigInt(Ii(e.n))*s.n>BigInt(Oi)||s.d>1000n)return{coef:Ti.ONE,fs:[{b:Di(e),e:t}]};let i=r.isZero?Ti.ONE:e.pow(r.n);const{outside:o,inside:a}=Li(e.n**s.n,Number(s.d));i=i.mul(new Ti(o));return{coef:i,fs:a>1n?[{b:Di(new Ti(a)),e:Di(new Ti(1n,s.d))}]:[]}}function oo(e){let t=Ti.ONE;const n=new Map,r=(e,t)=>{const r=Qi(e),s=n.get(r);s?s.e=so([s.e,t]):n.set(r,{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)r(e.b,e.e)}else r(n,Wi);if(t.isZero)return Ui;const s=[],i=new Map;for(const e of n.values())if(!Hi(e.e)||!e.e.q.isZero){if("num"===e.b.k){if(Hi(e.e)&&!e.e.q.isInteger&&e.b.q.sign>0&&e.b.q.isInteger){const t=e.e.q.toString(),n=i.get(t);n?n.n*=e.b.q.n:i.set(t,{n:e.b.q.n,e:e.e});continue}const n=io(e.b.q,e.e);t=t.mul(n.coef),s.push(...n.fs);continue}if("mul"===e.b.k&&Hi(e.e)&&e.e.q.isInteger){const n=ao(e.b,e.e);"mul"===n.k?(t=t.mul(n.c),s.push(...n.fs)):"num"===n.k?t=t.mul(n.q):s.push({b:n,e:Wi});continue}s.push(e)}for(const{n:e,e:n}of i.values()){const r=io(new Ti(e),n);t=t.mul(r.coef),s.push(...r.fs)}if(t.isZero)return Ui;const o=new Map;for(const e of s){const t=Qi(e.b),n=o.get(t);n?n.e=so([n.e,e.e]):o.set(t,{...e})}let a=[...o.values()].filter(e=>!(Hi(e.e)&&e.e.q.isZero));if(Zi.complex){a=a.flatMap(e=>{if(!Pi(e.b)||!Hi(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:Wi}]:[]});const e=a.filter(e=>"add"===e.b.k&&Hi(e.e)&&e.e.q.isInteger&&ho(e.b)),n=a.some(e=>Pi(e.b)),r=e.every(e=>(e.e.q.sign<0?-e.e.q.n:e.e.q.n)<=60n);if(e.length&&r&&(e.length>1||n||!e[0].e.q.isOne)){const r=a.filter(t=>!e.includes(t)&&!Pi(t.b));let s=n?[uo]:[Wi];for(const t of e){const e=t.e.q.sign<0?mo(t.b):t.b;for(let n=0n;n<(t.e.q.sign<0?-t.e.q.n:t.e.q.n);n++)s=po(s,To(e))}return oo([Di(t),so(s),...r.map(e=>lo(e.b,e.e))])}}if(a.some(e=>"num"===e.b.k&&Hi(e.e)&&e.e.q.compare(Ti.ONE)>=0))return oo([Di(t),...a.map(e=>"num"===e.b.k?ao(e.b,e.e):{k:"mul",c:Ti.ONE,fs:[e]})]);if(!a.length)return Di(t);if(1===a.length&&!t.isOne&&"add"===a[0].b.k&&Hi(a[0].e)&&a[0].e.q.isOne){const e=a[0].b;return so([Di(t.mul(e.c)),...e.terms.map(e=>no(t.mul(e.coef),e.x))])}return t.isOne&&1===a.length&&Hi(a[0].e)&&a[0].e.q.isOne?a[0].b:(a=a.sort((e,t)=>Yi(e.b,e.e)-Yi(t.b,t.e)||Ki(Qi(e.b),Qi(t.b))),{k:"mul",c:t,fs:a})}function ao(e,t){if(Zi.complex&&Hi(t)&&t.q.isInteger){if(Pi(e))return oo([{k:"mul",c:Ti.ONE,fs:[{b:e,e:t}]}]);if("add"===e.k&&ho(e)&&!t.q.isOne)return oo([{k:"mul",c:Ti.ONE,fs:[{b:e,e:t}]}])}if(Hi(t)){if(t.q.isZero){if(Hi(e)&&e.q.isZero)throw new Ai("0^0 is undefined");return Wi}if(t.q.isOne)return e}if(Hi(e)){const n=io(e.q,t);if(!n.fs.length)return Di(n.coef);if(n.fs.some(e=>Pi(e.b)))return oo([Di(n.coef),...n.fs.map(e=>({k:"mul",c:Ti.ONE,fs:[e]}))]);const r={k:"mul",c:n.coef,fs:n.fs};return n.coef.isOne&&1===n.fs.length&&Hi(n.fs[0].e)&&n.fs[0].e.q.isOne?n.fs[0].b:r}if(Zi.complex&&Hi(t)&&2n===t.q.d&&ho(e)){const n=fo(e);if(n&&Hi(n.im)&&!n.im.q.isZero){const e=e=>ao(e,Di(Ti.of(2))),r=ao(so([e(n.re),e(n.im)]),Vi),s=ao(oo([so([r,n.re]),Di(Ti.HALF)]),Vi),i=ao(oo([so([r,vo(n.re)]),Di(Ti.HALF)]),Vi);return ao(so([s,oo([Di(Ti.of(n.im.q.sign)),i,uo])]),Di(new Ti(t.q.n)))}}if("mul"===e.k){if(Hi(t)&&t.q.isInteger)return oo([Di(e.c.pow(t.q.n)),...e.fs.map(e=>lo(e.b,oo([e.e,t])))]);if(!e.c.isOne&&e.c.sign>0)return oo([ao(Di(e.c),t),ao({k:"mul",c:Ti.ONE,fs:e.fs},t)]);if(e.c.isOne&&1===e.fs.length){const[n]=e.fs;if(Hi(n.e)&&Hi(t)&&1n===n.e.q.n&&n.e.q.d%2n==1n)return lo(n.b,oo([n.e,t]))}}return{k:"mul",c:Ti.ONE,fs:[{b:e,e:t}]}}function lo(e,t){return Hi(t)&&t.q.isZero?Wi:Hi(e)?ao(e,t):Hi(t)&&t.q.isOne?e:{k:"mul",c:Ti.ONE,fs:[{b:e,e:t}]}}const uo=Gi(fi("i")),co=e=>Zi.complex&&Oo(e).s.split(" ").includes("i");function ho(e){return Zi.complex&&co(e)&&0===_o(Oo(e)).size}function po(e,t){const n=[];for(const r of e)for(const e of t)n.push(oo([r,e]));return To(so(n))}function fo(e){const t=[],n=[];for(const r of To(e)){const{coef:e,rest:s}=ro(r),i=s?jo(s):[],o=i.filter(e=>Pi(e)),a=i.filter(e=>!Pi(e));if(a.some(e=>co(e)))return null;(o.length?n:t).push(oo([Di(e),...a]))}return{re:so(t),im:so(n)}}function mo(e){const t=fo(e);if(!t)return ao(e,Di(Ti.MINUS_ONE));const n=so([ao(t.re,Di(Ti.of(2))),ao(t.im,Di(Ti.of(2)))]);return oo([so([t.re,oo([Di(Ti.MINUS_ONE),t.im,uo])]),ao(n,Di(Ti.MINUS_ONE))])}const go={re:([e])=>fo(e)?.re??null,im:([e])=>fo(e)?.im??null,conj:([e])=>{const t=fo(e);return t?so([t.re,oo([Di(Ti.MINUS_ONE),t.im,uo])]):null},arg:([e])=>{const t=fo(e);return t?$o("atan2",[t.im,t.re]):null},abs:([e])=>{const t=fo(e);return!t||Hi(t.im)&&t.im.q.isZero?null:ao(so([ao(t.re,Di(Ti.of(2))),ao(t.im,Di(Ti.of(2)))]),Vi)}},bo={Re:"re",re:"re",Im:"im",im:"im",conj:"conj",overline:"conj",bar:"conj",arg:"arg"},vo=e=>oo([Di(Ti.MINUS_ONE),e]),yo=(e,t)=>oo([e,ao(t,Di(Ti.MINUS_ONE))]),wo=3000n,xo={abs:([e])=>Hi(e)?Di(e.q.abs()):"mul"!==e.k||e.c.isOne?null:oo([Di(e.c.abs()),$o("abs",[ro(e).rest])]),floor:([e])=>Hi(e)?Di(e.q.floor()):null,ceil:([e])=>Hi(e)?Di(e.q.ceil()):null,"!":([e])=>{if(!Hi(e)||!e.q.isInteger||e.q.sign<0||e.q.n>wo)return null;let t=1n;for(let n=2n;n<=e.q.n;n++)t*=n;return Di(new Ti(t))},mod:([e,t])=>Hi(e)&&Hi(t)&&!t.q.isZero?Di(e.q.sub(t.q.mul(e.q.div(t.q).floor()))):null,max:e=>e.every(Hi)&&e.length?e.reduce((e,t)=>t.q.compare(e.q)>0?t:e):null,min:e=>e.every(Hi)&&e.length?e.reduce((e,t)=>t.q.compare(e.q)<0?t:e):null,gcd:e=>e.length&&e.every(e=>Hi(e)&&e.q.isInteger)?Di(new Ti(e.reduce((e,t)=>_i(e,t.q.n),0n))):null,log:([e,t])=>{if(!Hi(e)||!Hi(t)||e.q.sign<=0||t.q.sign<=0||e.q.isOne)return null;if(t.q.isOne)return Ui;const n=Math.log(t.q.toNumber())/Math.log(e.q.toNumber());if(!Number.isFinite(n))return null;for(let r=1;r<=12;r++){const s=Math.round(n*r);if(!(Math.abs(n*r-s)>1e-9||0===s)&&(Math.abs(s)<=256&&e.q.pow(BigInt(s)).equals(t.q.pow(BigInt(r)))))return Di(new Ti(BigInt(s),BigInt(r)))}return null},comb:([e,t])=>Hi(e)&&Hi(t)&&e.q.isInteger&&t.q.isInteger&&e.q.sign>=0&&t.q.sign>=0&&e.q.n<=wo?Di(function(e,t){if(t>e)return Ti.ZERO;t>e-t&&(t=e-t);let n=1n;for(let r=1n;r<=t;r++)n=n*(e-t+r)/r;return new Ti(n)}(e.q.n,t.q.n)):null,perm:([e,t])=>{if(!(Hi(e)&&Hi(t)&&e.q.isInteger&&t.q.isInteger&&e.q.sign>=0&&t.q.sign>=0&&e.q.n<=wo))return null;if(t.q.n>e.q.n)return Ui;let n=1n;for(let r=0n;r<t.q.n;r++)n*=e.q.n-r;return Di(new Ti(n))}};function $o(e,t){if(Zi.complex&&go[e]){const n=go[e](t);if(n)return n}const n=xo[e];if(n){const e=n(t);if(e)return e}return Gi(bi(e,t.map(Oo)))}const ko=new Map;function qo(e){const t=Zi.complex?`ℂ ${e.s}`:e.s,n=ko.get(t);if(n)return n;const r=function(e){if("num"===e.type){const t=ji(e.token);if(!t)throw new Ai(`not an exact number: ${e.token}`);return Di(t)}if("sym"===e.type)return"π"===e.token?Gi(fi("pi")):Gi(e);const t=e.args.map(qo);switch(e.op){case"+":return so(t);case"-":return((e,t)=>so([e,vo(t)]))(t[0],t[1]);case"neg":return vo(t[0]);case"*":return oo(t);case"/":return yo(t[0],t[1]);case"^":return ao(t[0],t[1]);case"sqrt":return ao(t[0],Vi);case"root":return ao(t[1],ao(t[0],Di(Ti.MINUS_ONE)));default:{const n=e.op.startsWith("\\:")?e.op.slice(2):null;return n&&Zi.complex&&bo[n]&&1===t.length?$o(bo[n],t):n&&si(n)&&ri(n).arity===t.length?$o(n,t):$o(e.op,t)}}}(e);return ko.size>2e4&&ko.clear(),ko.set(t,r),r}const Mo=e=>Oo(qo(e)),No=e=>mi(String(e));function So(e){return e.isInteger?No(e.n):bi("/",[No(e.n),No(e.d)])}const Ao=new WeakMap;function Oo(e){let t=Ao.get(e);return t||Ao.set(e,t=function(e){switch(e.k){case"num":return So(e.q);case"atom":return e.node;case"mul":return function(e,t){const n=[],r=[];for(const e of t)Hi(e.e)&&e.e.q.sign<0?r.push(Eo(e.b,Di(e.e.q.neg()))):n.push(Eo(e.b,e.e));let s=1n!==e.n&&-1n!==e.n||!n.length?Io([No(e.n),...n]):Io(n);-1n===e.n&&n.length&&(s=bi("neg",[s]));1n!==e.d&&r.unshift(No(e.d));return r.length?bi("/",[s,Io(r)]):s}(e.c,e.fs);case"add":return function(e){let t=null;const n=e=>Zi.complex&&co(e.x)&&0===_o(Oo(e.x)).size,r=[...e.terms.filter(e=>!n(e)),...e.terms.filter(n)],s=e.c,i=()=>{s.isZero||(t=t?s.sign<0?bi("-",[t,So(s.neg())]):bi("+",[t,So(s)]):So(s))};let o=!1;for(const e of r)!o&&n(e)&&(i(),o=!0),t=t?e.coef.sign<0?bi("-",[t,Oo(no(e.coef.neg(),e.x))]):bi("+",[t,Oo(no(e.coef,e.x))]):Oo(no(e.coef,e.x));o||i();return t}(e);default:throw new Error(`bad form ${e.k}`)}}(e)),t}function Eo(e,t){const n=Oo(e);if(Hi(t)){const e=t.q;if(e.isOne)return n;if(1n===e.n&&2n===e.d)return bi("sqrt",[n]);if(1n===e.n)return bi("root",[No(e.d),n])}return bi("^",[n,Oo(t)])}const Io=e=>e.reduce((e,t)=>e?bi("*",[e,t]):t,null);function _o(e,t=new Set){if("sym"===e.type)Bi(e.token)||t.add(e.token);else if(yi(e))for(const n of e.args)_o(n,t);return t}function To(e){if("add"!==e.k)return[e];const t=e.terms.map(e=>no(e.coef,e.x));return e.c.isZero||t.push(Di(e.c)),t}function jo(e){if("num"===e.k)return[e];if("mul"!==e.k)return[e];const t=e.c.isOne?[]:[Di(e.c)];for(const n of e.fs)t.push(lo(n.b,n.e));return t}const Co="_",zo=new WeakMap;function Lo(e,t){return[...t,...ri(e.op)?.arity===Ys?[String(e.args.length)]:[],e.op].join(" ")}function Ro(e,t){let n=zo.get(e);n||zo.set(e,n=new Map);const r=n.get(t);if(r)return r;const s=function(e,t){const n={key:Co,slots:[e]};if(e.type!==ui||t<=0)return[n];const r=e.args.map(e=>Ro(e,t-1)),s=[n],i=new Array(r.length).fill(0);for(;;){const t=[],n=[];for(let e=0;e<r.length;e++){const s=r[e][i[e]];t.push(s.key);for(const e of s.slots)n.push(e)}if(s.push({key:Lo(e,t),slots:n}),s.length>=4096)break;let o=r.length-1;for(;o>=0&&!(++i[o]<r[o].length);o--)i[o]=0;if(o<0)break}return s}(e,t);return n.set(t,s),s}function Zo(e){return e.type!==ui?Co:Lo(e,e.args.map(Zo))}function Fo(e,t=[]){if(e.type!==ui)t.push(e);else for(const n of e.args)Fo(n,t);return t}const Bo=new Map,Po=new Map;class Do extends Error{constructor(e){super(e),this.name="RequirementError"}}function Wo(e,t,n=""){Bo.set(e,{name:e,fn:t,doc:n,arity:Math.max(0,t.length-1)})}function Uo(e,t,n=""){Po.set(e,{name:e,fn:t,doc:n})}function Vo(e){return Bo.get(e)||null}function Ho(e){return Po.get(e)||null}const Go=e=>e.type===ai;function Xo(e,t){return e.type===ui&&(e.op===t||e.args.some(e=>Xo(e,t)))}Wo("always",()=>!0,"matches anything"),Wo("never",()=>!1,"matches nothing"),Wo("isLeaf",e=>e.type!==ui,"a bare operand, not an operation"),Wo("isCompound",e=>e.type===ui,"an operation, not a bare operand"),Wo("isSymbol",e=>e.type===li,"a non-numeric operand such as x"),Wo("isOperation",(e,t)=>e.type===ui&&e.op===t,"is this specific operation"),Wo("notOperation",(e,t)=>!(e.type===ui&&e.op===t),"is anything except this operation"),Wo("isNumber",Go,"a numeric literal"),Wo("isInteger",e=>Go(e)&&Number.isInteger(e.value),"a whole number"),Wo("isPositive",e=>Go(e)&&e.value>0,"greater than zero"),Wo("isNegative",e=>Go(e)&&e.value<0,"less than zero"),Wo("isNonNegative",e=>Go(e)&&e.value>=0,"zero or greater"),Wo("isZero",e=>Go(e)&&0===e.value,"exactly 0"),Wo("isOne",e=>Go(e)&&1===e.value,"exactly 1"),Wo("isNonZero",e=>Go(e)&&0!==e.value,"a number that is provably not 0"),Wo("isNotZeroLiteral",e=>!(Go(e)&&0===e.value),"anything except a literal 0"),Wo("isPositiveInteger",e=>Go(e)&&Number.isInteger(e.value)&&e.value>0,"a whole number above 0"),Wo("isNegativeInteger",e=>Go(e)&&Number.isInteger(e.value)&&e.value<0,"a whole number below 0"),Wo("isEven",e=>Go(e)&&Number.isInteger(e.value)&&e.value%2==0,"a whole even number"),Wo("isOdd",e=>Go(e)&&Number.isInteger(e.value)&&1===Math.abs(e.value%2),"a whole odd number"),Wo("greaterThan",(e,t)=>Go(e)&&e.value>Number(t),"above a given value"),Wo("lessThan",(e,t)=>Go(e)&&e.value<Number(t),"below a given value"),Wo("isValue",(e,t)=>Go(e)&&e.value===Number(t),"equals a given number"),Wo("isNumeric",Mi,"contains no symbols: a constant (it need not fold to a number: 1 sin)"),Wo("hasSymbol",e=>!Mi(e),"mentions a symbol somewhere, so it is not just a number"),Wo("isVar",(e,t)=>e.type===li&&e.token===String(t),"is exactly this symbol"),Wo("contains",(e,t)=>qi(e).includes(String(t)),"mentions this operand somewhere"),Wo("isFree",(e,t)=>!qi(e).includes(String(t)),"never mentions this operand"),Wo("hasOperation",(e,t)=>Xo(e,String(t)),"uses this operation somewhere inside"),Wo("equals",(e,t)=>e.s===String(t),"is exactly this postfix expression");const Qo=e=>e.type===ui?null:e.token;function Jo(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 Do(`bad requirement: ${JSON.stringify(e)}`)}Uo("freeOf",(e,t)=>{const n=Qo(t);return null!==n&&!qi(e).includes(n)},"the first operand never mentions the second"),Uo("dependsOn",(e,t)=>{const n=Qo(t);return null!==n&&qi(e).includes(n)},"the first operand does mention the second"),Uo("sameAs",(...e)=>e.every(t=>t.s===e[0].s),"these operands are structurally identical"),Uo("differs",(...e)=>new Set(e.map(e=>e.s)).size===e.length,"these operands are all different"),Uo("sameValue",(...e)=>e.every(e=>Go(e))&&e.every(t=>t.value===e[0].value),"these operands are the same number");const Yo="simplify";class Ko extends Error{constructor(e,t){super(t?`rule "${t}": ${e}`:e),this.name="RuleError",this.ruleId=t}}const ea=/^[A-Za-z_][A-Za-z0-9_]*$/;function ta(e,t){if(vi(e))return{literal:e.value};const n=e.token;if(n.startsWith("=")){const e=n.slice(1);if(""===e)throw new Ko('"=" needs an operand after it',t);return{token:e}}if(!ea.test(n))throw new Ko(`"${n}" is not a usable slot name; use letters, digits and _`,t);if(si(n))throw new Ko(`slot name "${n}" collides with an operator`,t);return{name:n}}function na(e){if(!yi(e))return[e];const t=e.args.map(na),n=ri(e.op),r=[];for(const s of function(e){let t=[[]];for(const n of e){const e=[];for(const r of t)for(const t of n)e.push(r.concat([t]));if(t=e,t.length>64)return t.slice(0,64)}return t}(t))if(r.push(bi(e.op,s)),n.commutative&&2===s.length&&s[0].s!==s[1].s&&r.push(bi(e.op,[s[1],s[0]])),r.length>=64)break;return r}function ra(e,t=[]){return"op"===e.kind?e.args.forEach(e=>ra(e,t)):"const"===e.kind&&e.free&&t.push(e.node.token),t}function sa(e){if(!e||"object"!=typeof e)throw new Ko("rule must be a mapping");const t=e.id||e.name;if(!t)throw new Ko("rule needs an id");if(!e.pattern)throw new Ko("rule needs a pattern",t);if(void 0===e.output||null===e.output)throw new Ko("rule needs an output",t);let n;try{n=wi(String(e.pattern))}catch(e){if(e instanceof hi)throw new Ko(`bad pattern: ${e.message}`,t);throw e}const r=Fo(n).map(e=>ta(e,t)),s=new Set(r.filter(e=>e.name).map(e=>e.name)),i=function(e,t,n){const r=[],s=e.when||{};if("object"!=typeof s||Array.isArray(s))throw new Ko('"when" must map slot names to lists of requirements',n);for(const[e,i]of Object.entries(s)){if(!t.has(e))throw new Ko(`"when" mentions "${e}", which is not a slot in the pattern`,n);const s=Array.isArray(i)?i:[i];for(const t of s){const{name:s,args:i}=Jo(t),o=Vo(s);if(!o)throw new Ko(`unknown requirement "${s}"`,n);r.push({slot:e,name:s,args:i,fn:o.fn})}}return r}(e,s,t),o=function(e,t,n){const r=[],s=e.require||[];if(!Array.isArray(s))throw new Ko('"require" must be a list of relations',n);for(const e of s){const{name:s,args:i}=Jo(e),o=Ho(s);if(!o)throw new Ko(`unknown relation "${s}"`,n);if(i.length<2)throw new Ko(`relation "${s}" needs at least two operands`,n);for(const e of i)if("string"==typeof e&&!t.has(e)&&ea.test(e))throw new Ko(`relation "${s}" mentions "${e}", which is not a slot in the pattern`,n);r.push({name:s,args:i,fn:o.fn})}return r}(e,s,t),a=function(e,t,n){let r;try{r=wi(e)}catch(t){throw new Ko(`bad output "${e}": ${t.message}`,n)}const s=e=>yi(e)?{kind:"op",op:e.op,args:e.args.map(s)}:vi(e)?{kind:"const",node:e}:t.has(e.token)?{kind:"slot",name:e.token}:e.token.startsWith("=")?{kind:"const",node:fi(e.token.slice(1))}:{kind:"const",node:e,free:!0};return s(r)}(String(e.output),s,t),l=e.commutative?na(n):[n],u=[],c=new Set;for(const e of l){const n=Zo(e),r=Fo(e).map(e=>ta(e,t)),s=n+"\0"+r.map(e=>e.name??(void 0!==e.literal?`#${e.literal}`:`=${e.token}`)).join(",");c.has(s)||(c.add(s),u.push({key:n,slots:r}))}const h={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):Yo,tags:Array.isArray(e.tags)?e.tags.map(String):[],priority:Number.isFinite(e.priority)?e.priority:0,fold:!!e.fold,commutative:!!e.commutative,enabled:void 0===e.enabled||!!e.enabled,when:i,require:o,slots:[...s],depth:$i(n),bindings:u,freeSymbols:ra(a),source:e};for(const e of u)e.rule=h;return h}function ia(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!==Yo&&(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 oa extends Error{constructor(e,t){super(null==t?e:`${e} (line ${t+1})`),this.name="YamlError",this.line=t}}class aa{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 la=e=>"-"===e||e.startsWith("- ");function ua(e){let t=null,n=0;for(let r=0;r<e.length;r++){const s=e[r];if(t)s===t?"'"===t&&"'"===e[r+1]?r++:t=null:'"'===t&&"\\"===s&&r++;else if('"'===s||"'"===s)t=s;else if("["===s||"{"===s)n++;else if("]"===s||"}"===s)n--;else if(":"===s&&0===n&&(r+1===e.length||" "===e[r+1])){const t=e.slice(0,r).trim();return""===t?null:{key:ca(t),rest:e.slice(r+1).trim()}}}return null}function ca(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 ha(e){const t=new aa(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 r=function(e){let t=null;for(let n=0;n<e.length;n++){const r=e[n];if(t)r===t?"'"===t&&"'"===e[n+1]?n++:t=null:'"'===t&&"\\"===r&&n++;else if('"'===r||"'"===r)t=r;else if("#"===r&&(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:r,blank:""===r}})}(e));let n=t.peek();if(n&&"---"===n.text&&(t.next(),n=t.peek()),!n)return null;const r=fa(t,n.indent),s=t.peek();if(s&&"..."!==s.text&&"---"!==s.text)throw new oa(`unexpected content "${s.text}"`,s.n);return r}const pa=/^[|>][-+]?\d*$/;function fa(e,t){const n=e.peek();return!n||n.indent<t?null:la(n.text)?ma(e,n.indent):ua(n.text)?function(e,t){const n={};for(;;){const r=e.peek();if(!r||r.indent!==t)break;const s=ua(r.text);if(!s)break;e.next();const{key:i,rest:o}=s;if(""===o){const r=e.peek();r&&r.indent>t?n[i]=fa(e,r.indent):r&&r.indent===t&&la(r.text)?n[i]=ma(e,t):n[i]=null}else pa.test(o)?n[i]=da(e,o,t):n[i]=ga(o,r.n)}return n}(e,n.indent):(e.next(),pa.test(n.text)?da(e,n.text,n.indent-1):ga(n.text,n.n))}function ma(e,t){const n=[];for(;;){const r=e.peek();if(!r||r.indent!==t||!la(r.text))break;if(e.next(),"-"===r.text){const r=e.peek();n.push(r&&r.indent>t?fa(e,r.indent):null);continue}if(pa.test(r.text.slice(2).trim())){n.push(da(e,r.text.slice(2).trim(),t));continue}const s=r.text.slice(2),i=t+2+(s.length-s.trimStart().length);e.push({raw:r.raw,n:r.n,indent:i,text:s.trim(),blank:!1}),n.push(fa(e,i))}return n}function da(e,t,n){const r=t[0],s=(t.match(/[-+]/)||[""])[0],i=(t.match(/\d+/)||[null])[0];let o=i?n+Number(i):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 r=t.raw.search(/\S/);if(r<=n)break;if(null===o&&(o=r),r<o)break;a.push(t.raw.slice(o)),e.i++}for(;a.length&&""===a[a.length-1];)a.pop();let l;if("|"===r)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"-"===s?l:"+"===s?l+"\n":""===l?"":l+"\n"}function ga(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},r=va(n);if(ba(n),n.i<n.text.length)throw new oa(`unexpected "${n.text.slice(n.i)}" in flow value`,t);return r}(n,t):'"'===n[0]||"'"===n[0]?ca(n):/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(n)?Number(n):n)}const ba=e=>{for(;e.i<e.text.length&&/\s/.test(e.text[e.i]);)e.i++};function va(e){ba(e);const t=e.text[e.i];return"["===t?function(e){e.i++;const t=[];for(;;){if(ba(e),e.i>=e.text.length)throw new oa("unterminated [",e.line);if("]"===e.text[e.i])return e.i++,t;if(t.push(va(e)),ba(e),","===e.text[e.i])e.i++;else if("]"!==e.text[e.i])throw new oa(`expected , or ] near "${e.text.slice(e.i)}"`,e.line)}}(e):"{"===t?function(e){e.i++;const t={};for(;;){if(ba(e),e.i>=e.text.length)throw new oa("unterminated {",e.line);if("}"===e.text[e.i])return e.i++,t;const n=String(va(e));if(ba(e),":"!==e.text[e.i])throw new oa(`expected : after "${n}"`,e.line);if(e.i++,t[n]=va(e),ba(e),","===e.text[e.i])e.i++;else if("}"!==e.text[e.i])throw new oa(`expected , or } near "${e.text.slice(e.i)}"`,e.line)}}(e):ga(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 oa("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 ya=/^(true|false|null|yes|no|on|off|~)$/i;function wa(e){if(null==e)return"null";if("boolean"==typeof e)return e?"true":"false";if("number"==typeof e){if(!Number.isFinite(e))throw new oa(`cannot serialise ${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)||ya.test(e)||/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(e))}(t)?JSON.stringify(t):t}const xa=e=>null==e||"object"!=typeof e;function $a(e){return Array.isArray(e)?`[${e.map($a).join(", ")}]`:e&&"object"==typeof e?`{${Object.entries(e).map(([e,t])=>`${wa(e)}: ${$a(t)}`).join(", ")}}`:wa(e)}function ka(e){return Array.isArray(e)?!!e.every(e=>xa(e)||Array.isArray(e)&&e.every(xa))&&$a(e).length<=72:!(!e||"object"!=typeof e)&&(Object.values(e).every(e=>xa(e)||Array.isArray(e)&&e.every(xa))&&$a(e).length<=72)}function qa(e){const t=[];return Ma(e,0,t),t.length?t.join("\n")+"\n":""}function Ma(e,t,n){const r=" ".repeat(t);if(Array.isArray(e)){if(0===e.length)return void n.push(r+"[]");for(const r of e)Na(r,t,n)}else{if(e&&"object"==typeof e){const s=Object.entries(e).filter(([,e])=>void 0!==e);if(0===s.length)return void n.push(r+"{}");for(const[e,r]of s)Sa(e,r,t,n);return}!function(e,t,n){if("string"==typeof e&&e.includes("\n")){n.push(t+"|-");for(const r of e.replace(/\n+$/,"").split("\n"))n.push(t+" "+r);return}n.push(t+wa(e))}(e,r,n)}}function Na(e,t,n){const r=" ".repeat(t);if(null!==e&&"object"==typeof e&&!ka(e)){const s=[];if(Ma(e,t+2,s),0===s.length)return void n.push(r+"-");n.push(r+"- "+s[0].slice(t+2));for(let e=1;e<s.length;e++)n.push(s[e]);return}if(null===e||"object"!=typeof e)if("string"==typeof e&&e.includes("\n")){n.push(r+"- |-");for(const r of e.replace(/\n+$/,"").split("\n"))n.push(" ".repeat(t+4)+r)}else n.push(r+"- "+wa(e));else n.push(r+"- "+$a(e))}function Sa(e,t,n,r){const s=" ".repeat(n),i=wa(e);if("string"==typeof t&&t.includes("\n")){r.push(`${s}${i}: |-`);for(const e of t.replace(/\n+$/,"").split("\n"))r.push(" ".repeat(n+2)+e)}else{if(null!==t&&"object"==typeof t)return ka(t)?void r.push(`${s}${i}: ${$a(t)}`):(r.push(`${s}${i}:`),void Ma(t,Array.isArray(t)?n:n+2,r));r.push(`${s}${i}: ${wa(t)}`)}}class Aa{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:sa(e);if(this.rules.some(e=>e.id===t.id))throw new Ko(`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 Aa(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===Yo?-1:t===Yo?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=ha(e);return Aa.fromSpecs(n,{strict:t})}static fromSpecs(e,{strict:t=!0}={}){let n=e,r="";if(e&&!Array.isArray(e)&&"object"==typeof e&&(n=e.rules,r=e.name?String(e.name):""),!Array.isArray(n))throw new Ko('expected a list of rules, or a mapping with a "rules" list');const s=new Aa;s.name=r;const i=[];for(let e=0;e<n.length;e++)try{s.add(n[e])}catch(t){i.push(`#${e+1}: ${t.message}`)}if(i.length&&t)throw new Ko(`${i.length} rule(s) failed to compile:\n ${i.join("\n ")}`);return s.errors=i,s}toSpecs(){return this.rules.map(ia)}toYaml(){const e=this.toSpecs();return this.name?qa({name:this.name,rules:e}):qa(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 Oa(e,t){const n=Object.create(null),r=e.slots;for(let e=0;e<r.length;e++){const s=r[e],i=t[e];if(void 0!==s.literal){if(!vi(i)||i.value!==s.literal)return null;continue}if(void 0!==s.token){if(i.s!==s.token)return null;continue}const o=n[s.name];if(void 0!==o){if(o.s!==i.s)return null}else n[s.name]=i}return n}function Ea(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 Ia(e,t){return t.rule.priority-e.rule.priority||t.rule.depth-e.rule.depth}function _a(e,t){const n=[];if(0===t.maxDepth)return n;for(const{key:r,slots:s}of function(e,t){const n=Ro(e,t),r=[];for(const e of n)e.key!==Co&&r.push(e);return r}(e,t.maxDepth)){const e=t.candidates(r);if(e)for(const t of e){const e=Oa(t,s);e&&(Ea(t.rule,e)&&n.push({rule:t.rule,binding:t,key:r,bound:e}))}}return n.sort(Ia)}function Ta(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 bi(e.op,e.args.map(e=>Ta(e,t)));default:throw new Error(`bad output template: ${JSON.stringify(e)}`)}}const ja=4e5,Ca=()=>new Ai("a number too large to approximate"),za=e=>e<0n?-e:e;class La{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 Ai("division by zero");return e*this.S/t}sqrt(e){if(e<0n)throw new Ai("the square root of a negative number is not real");return Ci(e*this.S,2)}series(e,t){let n=0n,r=e;for(let e=1;0n!==r;e++)if(n+=r,r=t(r,e),e>1e5)throw new Ai("a series did not converge");return n}atanhInv(e){const t=BigInt(e),n=t*t;let r=this.S/t,s=0n;for(let e=1n;0n!==r;e+=2n)s+=r/e,r/=n;return s}atanInv(e){const t=BigInt(e),n=t*t;let r=this.S/t,s=0n;for(let e=1n,t=1n;0n!==r;e+=2n,t=-t)s+=t*r/e,r/=n;return s}get pi(){return this.memo("pi",()=>16n*this.atanInv(5)-4n*this.atanInv(239))}get ln2(){return this.memo("ln2",()=>2n*this.atanhInv(3))}get e(){return this.memo("e",()=>this.exp(this.S))}memo(e,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(ja))throw Ca();if(t<-BigInt(ja))return 0n;const n=e-t*this.ln2,r=this.series(this.S,(e,t)=>e*n/this.S/BigInt(t));return t>=0n?r<<t:r>>-t}ln(e){if(e<=0n)throw new Ai("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 r=this.div(n-this.S,n+this.S),s=this.mul(r,r);let i=r,o=0n;for(let e=1n;0n!==i;e+=2n)o+=i/e,i=this.mul(i,s);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 r=this.mul(n,n);return this.series(n,(e,t)=>-e*r/this.S/BigInt(2*t*(2*t+1)))}cos(e){return this.sin(e+this.pi/2n)}atan(e){if(za(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 r=t,s=0n;for(let e=1n,t=1n;0n!==r;e+=2n,t=-t)s+=t*r/e,r=this.mul(r,n);return 4n*s}asin(e){if(za(e)>this.S)throw new Ai("arcsin of a number beyond ±1 is not real");return za(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 Ra(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 Ai("the argument of 0 is undefined");return t>0n?e.pi/2n:-e.pi/2n}const Za={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 r=e.mul(n[0],n[0])+e.mul(n[1],n[1]);if(0n===r)throw new Ai("division by zero");return[e.div(e.mul(t[0],n[0])+e.mul(t[1],n[1]),r),e.div(e.mul(t[1],n[0])-e.mul(t[0],n[1]),r)]},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=Za.abs(e,t);if(0n===n)throw new Ai("the log of 0 is undefined");return[e.ln(n),Ra(e,t[1],t[0])]},pow(e,t,n,r){if(0n===t[0]&&0n===t[1])return[0n,0n];if(r&&r.isInteger){let n=r.n<0n?-r.n:r.n,s=[e.S,0n],i=t;for(;n>0n;)1n&n&&(s=Za.mul(e,s,i)),i=Za.mul(e,i,i),n>>=1n;return r.n<0n?Za.div(e,[e.S,0n],s):s}return Za.exp(e,Za.mul(e,n,Za.ln(e,t)))},sinh:(e,t)=>(e.exp(t)-e.exp(-t))/2n,cosh:(e,t)=>(e.exp(t)+e.exp(-t))/2n},Fa={sin:(e,[t,n])=>[e.mul(e.sin(t),Za.cosh(e,n)),e.mul(e.cos(t),Za.sinh(e,n))],cos:(e,[t,n])=>[e.mul(e.cos(t),Za.cosh(e,n)),-e.mul(e.sin(t),Za.sinh(e,n))],tan:(e,t)=>Za.div(e,Fa.sin(e,t),Fa.cos(e,t)),ln:(e,t)=>Za.ln(e,t),sqrt:(e,t)=>Za.exp(e,Za.mul(e,[e.S/2n,0n],Za.ln(e,t))),sinh:(e,[t,n])=>[e.mul(Za.sinh(e,t),e.cos(n)),e.mul(Za.cosh(e,t),e.sin(n))],cosh:(e,[t,n])=>[e.mul(Za.cosh(e,t),e.cos(n)),e.mul(Za.sinh(e,t),e.sin(n))]},Ba=e=>({q:e}),Pa=([e,t])=>0n===t?{f:e}:{z:[e,t]};function Da(e,t,n){const r=e=>((e,t)=>t.z??[Wa(e,t),0n])(n,t[e]);switch(e.op){case"+":return Pa(Za.add(r(0),r(1)));case"-":return Pa(Za.sub(r(0),r(1)));case"neg":return Pa([-r(0)[0],-r(0)[1]]);case"*":return Pa(Za.mul(n,r(0),r(1)));case"/":return Pa(Za.div(n,r(0),r(1)));case"^":return Pa(Za.pow(n,r(0),r(1),t[1].q));case"sqrt":return Pa(Fa.sqrt(n,r(0)));case"root":return Pa(Za.pow(n,r(1),Za.div(n,[n.S,0n],r(0)),t[0].q?.inv()));case"abs":return{f:Za.abs(n,r(0))};case"arg":return{f:Ra(n,r(0)[1],r(0)[0])};case"re":return{f:r(0)[0]};case"im":return{f:r(0)[1]};case"conj":return Pa([r(0)[0],-r(0)[1]]);case"log":return Pa(Za.div(n,Za.ln(n,r(1)),Za.ln(n,r(0))));default:{const s=Fa[e.op];if(!s||1!==t.length)throw new Ai(`no complex value for ${e.op}`);return Pa(s(n,r(0)))}}}function Wa(e,t){return t.q?e.fromQ(t.q):t.f}const Ua={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),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),r=e.exp(-t);return e.div(n-r,n+r)},arcsinh:(e,t)=>e.ln(t+e.sqrt(e.mul(t,t)+e.S)),arccosh:(e,t)=>{if(t<e.S)throw new Ai("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(za(t)>=e.S)throw new Ai("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 Va(e,t,n){if("num"===e.type)return Ba(ji(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&&Zi.complex)return{z:[0n,t.S]};if(n&&e.token in n){const t=n[e.token],r="number"==typeof t||"string"==typeof t||"bigint"==typeof t?ji(String(t)):null;if(!r)throw new Ai(`the value of ${e.token} is not a number`);return Ba(r)}throw new Ai(`${e.token} has no value`)}Zi.complex&&e.op.startsWith("\\:")&&bo[e.op.slice(2)]&&(e=bi(bo[e.op.slice(2)],e.args));const r=e.args.map(e=>Va(e,t,n));if(r.some(e=>e.z)||["re","im","conj","arg"].includes(e.op)||function(e,t){if(!Zi.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,r))return Da(e,r,t);const s=r.every(e=>e.q),i=e=>Wa(t,r[e]);switch(e.op){case"+":return s?Ba(r[0].q.add(r[1].q)):{f:i(0)+i(1)};case"-":return s?Ba(r[0].q.sub(r[1].q)):{f:i(0)-i(1)};case"neg":return r[0].q?Ba(r[0].q.neg()):{f:-r[0].f};case"*":return s?Ba(r[0].q.mul(r[1].q)):{f:t.mul(i(0),i(1))};case"/":return s?Ba(r[0].q.div(r[1].q)):{f:t.div(i(0),i(1))};case"^":return Ga(t,r[0],r[1]);case"sqrt":return Ga(t,r[0],Ba(Ti.HALF));case"root":return Ga(t,r[1],r[0].q?Ba(r[0].q.inv()):{f:t.div(t.S,r[0].f)});case"abs":return r[0].q?Ba(r[0].q.abs()):{f:za(r[0].f)};case"floor":return Ba(r[0].q?r[0].q.floor():new Ti(Ha(r[0].f,t.S)));case"ceil":return Ba(r[0].q?r[0].q.ceil():new Ti(-Ha(-r[0].f,t.S)));case"log":return{f:t.div(t.ln(i(1)),t.ln(i(0)))};case"atan2":return{f:Ra(t,i(0),i(1))};case"max":case"min":if(!r.length)throw new Ai(`${e.op} of nothing`);return s?Ba(r.map(e=>e.q).reduce((t,n)=>("max"===e.op?n.sub(t).sign>0:n.sub(t).sign<0)?n:t)):{f:r.map((e,t)=>i(t)).reduce((t,n)=>"max"===e.op?n>t?n:t:n<t?n:t)};case"sum":return s?Ba(r.reduce((e,t)=>e.add(t.q),Ti.ZERO)):{f:r.reduce((e,t,n)=>e+i(n),0n)};case"prod":return s?Ba(r.reduce((e,t)=>e.mul(t.q),Ti.ONE)):{f:r.reduce((e,n,r)=>t.mul(e,i(r)),t.S)};case"mean":if(!r.length)throw new Ai("mean of nothing");return s?Ba(r.reduce((e,t)=>e.add(t.q),Ti.ZERO).div(new Ti(BigInt(r.length)))):{f:r.reduce((e,t,n)=>e+i(n),0n)/BigInt(r.length)};case"mod":{if(s){if(r[1].q.isZero)throw new Ai("mod 0 is undefined");return Ba(r[0].q.sub(r[1].q.mul(r[0].q.div(r[1].q).floor())))}const e=i(1);if(0n===e)throw new Ai("mod 0 is undefined");return{f:i(0)-t.mul(e,Ha(t.div(i(0),e),t.S)*t.S)}}case"round":{if(!r[1].q?.isInteger)throw new Ai("round needs a whole number of places");const e=10n**za(r[1].q.n),n=r[0].q??new Ti(i(0),t.S),s=r[1].q.sign>=0,o=(s?n.mul(new Ti(e)):n.div(new Ti(e))).add(Ti.HALF).floor();return Ba(s?o.div(new Ti(e)):o.mul(new Ti(e)))}case"!":{if(!r[0].q?.isInteger||r[0].q.sign<0)throw new Ai("factorial is only worked out for whole numbers");let e=1n;for(let t=2n;t<=r[0].q.n;t++)if(e*=t,0n==(255n&t)&&Ii(e)>ja)throw Ca();return Ba(new Ti(e))}default:{const n=Ua[e.op];if(!n||1!==r.length)throw new Ai(`no numeric value for ${e.op}`);return{f:n(t,i(0))}}}}const Ha=(e,t)=>{const n=e/t;return e<0n&&n*t!==e?n-1n:n};function Ga(e,t,n){if(n.q&&n.q.isInteger){if(t.q)return Ba(t.q.pow(n.q.n));let r=n.q.n;const s=r<0n;s&&(r=-r);let i=e.S,o=t.f;for(;r>0n;){if(1n&r&&(i=e.mul(i,o)),o=e.mul(o,o),Ii(i)>ja+4*e.P||Ii(o)>8e5){if(s)return{f:0n};throw Ca()}r>>=1n}return{f:s?e.div(e.S,i):i}}const r=Wa(e,t);if(0n===r){if(n.q?n.q.sign>0:n.f>0n)return Ba(Ti.ZERO);throw new Ai("0 to a power that is not positive is undefined")}if(r<0n){if(n.q&&n.q.d%2n==1n){const t=Ga(e,{f:-r},n).f;return{f:n.q.n%2n==0n?t:-t}}throw new Ai("a negative number to a fractional power is not real")}if(n.q&&1n===za(n.q.n)&&n.q.d<=64n){const t=Ci(r*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(Wa(e,n),e.ln(r)))}}function Xa(e,t,n){const r=e<0n?"-":"",s=za(e);if(0n===s)return{sign:"",digits:"0",point:1};const i=s.toString(),o=i.length-t.P;let a=i.slice(0,n);i.length>n&&i[n]>="5"&&(a=(BigInt(a)+1n).toString());let l=o;return a.length>n&&(a=a.slice(0,n),l++),{sign:r,digits:a.replace(/0+$/,"")||"0",point:l}}function Qa({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 Ja(e){let t=0n,n=0n,r=e.d;for(;r%2n==0n;)r/=2n,t++;for(;r%5n==0n;)r/=5n,n++;const s=t>n?t:n;let i=za(e.n)*10n**s/e.d;if(0n===i)return 1;for(;i%10n==0n;)i/=10n;return i.toString().length}function Ya(e){let t=e.d;for(;t%2n==0n;)t/=2n;for(;t%5n==0n;)t/=5n;return 1n===t}function Ka(e){const t=/^(-?[\d.]+)e(-?\d+)$/.exec(e);return t?bi("*",[mi(t[1]),bi("^",[mi("10"),mi(t[2])])]):mi(e)}function el(e,{digits:t=15,scope:n}={}){if(!Number.isInteger(t)||t<1||t>1e5)throw new Ai("digits must be a whole number from 1 to 100000");let r=t+25,s=null;for(let i=0;i<4;i++){const o=new La(r),a=Va(e,o,n);if(a.z){const e=nl(a.z,o,t);if(e.retry&&i<3){r+=e.retry;continue}return void 0===e.real?e:tl(e.real,o,t,null)}if(a.q&&a.q.isInteger&&za(a.q.n).toString().length<=t)return{text:a.q.n.toString(),node:mi(a.q.n.toString()),number:Number(a.q.n),re:Number(a.q.n),im:0,exact:!0};const l=Wa(o,a);if(0n===l&&(!a.q||!a.q.isZero)&&i<3){s=null,r*=4;continue}const u=Xa(l,o,t);if(s&&u.point<-10&&s.point-u.point>=(r-s.P)/2)return{text:"0",node:mi("0"),number:0,re:0,im:0,exact:!1};if(!(u.point<-10&&i<3)||s&&s.point===u.point)return tl(l,o,t,a.q);s={point:u.point,P:r},r+=10-u.point}throw new Ai("could not approximate")}function tl(e,t,n,r){const s=Qa(Xa(e,t,n));return{text:s,node:Ka(s),number:Number(s),re:Number(s),im:0,exact:Boolean(r)&&Ya(r)&&Ja(r)<=n}}function nl([e,t],n,r){const s=10n**BigInt(Math.max(0,n.P-r-12)),i=e=>za(e)>s;if(!i(t))return{real:e};const o=Xa(t,n,r);if(o.point<-10&&i(t))return{retry:10-o.point};const a=Qa(o),l="1"===a?"i":"-1"===a?"-i":`${a}i`,u="1"===a?fi("i"):bi("*",[Ka(a.replace(/^-/,"")),fi("i")]);if(!i(e))return{text:l,node:a.startsWith("-")?bi("neg",[u]):u,number:NaN,re:0,im:Number(a),exact:!1};const c=Qa(Xa(e,n,r)),h=a.startsWith("-"),p="1"===a.replace(/^-/,"")?fi("i"):bi("*",[Ka(a.replace(/^-/,"")),fi("i")]);return{text:`${c} ${h?"-":"+"} ${l.replace(/^-/,"")}`,node:bi(h?"-":"+",[Ka(c),p]),number:NaN,re:Number(c),im:Number(a),exact:!1}}function rl(e,t={}){const n=e=>(e=>0===_o(e).size)(e)?"num"===e.type&&/^-?\d+$/.test(e.token)?e:el(e,t).node:yi(e)?bi(e.op,e.args.map(n)):e;return n(e)}const sl={variable:null},il=(e,t)=>null!==t&&_o(e).has(t);function ol(e){if("num"===e.type)return ji(e.token);if(yi(e)&&"/"===e.op&&e.args.every(e=>"num"===e.type)){const t=ji(e.args[0].token),n=ji(e.args[1].token);return t&&n&&!n.isZero?t.div(n):null}return null}const al=e=>0===_o(e).size;function ll(e,t,n){const r=function(e){const t=qo(e);return"num"===t.k?t.q.isZero?t.q:null:"atom"===t.k&&"sym"===t.node.type&&"pi"===t.node.token?ji("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(!r)return!1;const[s,i="1"]=String(t).split("/");return n(r.compare(ji(s).div(ji(i))))}function ul(e){if(!al(e))return NaN;try{const{number:t}=el(e,{digits:30});return Math.sign(t)}catch{return NaN}}function cl(){Vo("hasVariable")||(Wo("hasVariable",e=>il(e,sl.variable),"mentions the variable being solved for"),Wo("freeOfVariable",e=>null!==sl.variable&&!il(e,sl.variable),"does not mention the variable being solved for"),Wo("isRational",e=>null!==ol(e),"an exact number: 3, -2, 1/2"),Wo("isWhole",e=>ol(e)?.isInteger??!1,"a whole number (any size)"),Wo("isEvenWhole",e=>{const t=ol(e);return Boolean(t?.isInteger&&t.n%2n==0n)},"an even whole number"),Wo("isOddWhole",e=>{const t=ol(e);return Boolean(t?.isInteger&&t.n%2n!=0n)},"an odd whole number"),Wo("isPositiveRational",e=>(ol(e)?.sign??0)>0,"an exact number above 0"),Wo("isNegativeRational",e=>(ol(e)?.sign??0)<0,"an exact number below 0"),Wo("isConstant",al,"has no unknowns (numbers, π and e only)"),Wo("notOne",e=>{const t=ol(e);return!t||!t.isOne},"anything except the number 1"),Wo("notMinusOne",e=>{const t=ol(e);return!t||!t.equals(ji("-1"))},"anything except the number -1"),Wo("hasMinusSign",e=>function(e){const t=qo(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"),Wo("piMultipleAtLeast",(e,t)=>ll(e,t,e=>e>=0),"a multiple of π, at least k·π"),Wo("piMultipleAbove",(e,t)=>ll(e,t,e=>e>0),"a multiple of π, above k·π"),Wo("piMultipleBelow",(e,t)=>ll(e,t,e=>e<0),"a multiple of π, below k·π"),Wo("piMultipleAtMost",(e,t)=>ll(e,t,e=>e<=0),"a multiple of π, at most k·π"),Wo("isPositiveConstant",e=>ul(e)>0,"no unknowns, and above 0 (e, π, √2, 3)"),Wo("isNegativeConstant",e=>ul(e)<0,"no unknowns, and below 0"),Wo("hasImaginaryPart",e=>{if(!Zi.complex)return!1;const t=fo(qo(e));return Boolean(t)&&!("num"===t.im.k&&t.im.q.isZero)},"complex mode: has a nonzero imaginary part (unknowns count as real)"),Wo("isSymbolNode",e=>"sym"===e.type&&!Ri.has(e.token),"a single unknown such as x"))}function hl(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=wi(e),n=e=>"num"===e.type||("sym"===e.type?e.token.startsWith("="):e.args.every(n)),r=e=>"sym"===e.type?fi(e.token.slice(1)):"num"===e.type?e:bi(e.op,e.args.map(r)),s=e=>"sym"===e.type?fi(`=${e.token}`):"num"===e.type?e:bi(e.op,e.args.map(s)),i=e=>"op"!==e.type?e:n(e)?s(Mo(r(e))):bi(e.op,e.args.map(i));return i(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 Aa.fromSpecs(n,{strict:!0})}function pl(e,t,n,r){return e.explain?e.explain.replace(/\{(\w+)\}/g,(e,s)=>"result"===s?n?r(n):e:t[s]?r(t[s]):e).trim():""}const fl=e=>yi(e)&&("+"===e.op||"-"===e.op),ml=e=>yi(e)&&("*"===e.op||"/"===e.op);function*dl(e,t,{order:n="pre"}={}){for(const r of function(e,t,{order:n="post"}={}){const r=[];for(const{node:s,path:i}of Ni(e,n))for(const e of _a(s,t))r.push({...e,node:s,path:i});return r}(e,t,{order:n})){const t=Ta(r.rule.outputTemplate,r.bound);yield{rule:r.rule,bound:r.bound,path:r.path,before:r.node,after:t,next:()=>Mo(Si(e,r.path,t))}}for(const{node:r,path:s}of Ni(e,n)){const n=fl(r);if(!n&&!ml(r))continue;const i=n?To(qo(r)):jo(qo(r));if(i.length<3)continue;const o=n?so:oo;for(let n=0;n<i.length;n++)for(let r=n+1;r<i.length;r++){const a=Oo(o([i[n],i[r]]));for(const l of _a(a,t)){const t=Ta(l.rule.outputTemplate,l.bound),u=i.filter((e,t)=>t!==n&&t!==r);yield{rule:l.rule,bound:l.bound,path:s,before:a,after:t,next:()=>Mo(Si(e,s,Oo(o([qo(t),...u]))))}}}}}function gl(e,t,{format:n,order:r="pre",maxSteps:s=200,variable:i=null}={}){const o=sl.variable;sl.variable=i;try{let i=Mo(e);const o=new Set([i.s]),a=[];for(let e=0;e<s;e++){let e=null;for(const n of dl(i,t,{order:r})){const t=n.next();if(t.s!==i.s&&!o.has(t.s)){e={c:n,next:t};break}}if(!e)break;const{c:s,next:l}=e;a.push({id:s.rule.id,name:s.rule.name,tags:s.rule.tags,from:i.s,to:l.s,path:s.path,before:s.before.s,after:s.after.s,explanation:pl(s.rule,s.bound,Mo(s.after),n)}),i=l,o.add(i.s)}return{node:i,steps:a}}finally{sl.variable=o}}const bl={full:[],normal:["hidden"],brief:["hidden","tidy","identity","value","split","base","arithmetic"]},vl=(e,t)=>"all"===t||"*"===t||Array.isArray(t)&&t.some(t=>t===e.id||e.tags?.includes(t));function yl(e){if(!1===e)return null;if(void 0===e||!0===e)return{show:"all",hide:bl.normal,explain:!0};if("string"==typeof e){if(!bl[e])throw new Error(`steps: "${e}" is not one of ${Object.keys(bl).join(", ")}`);return{show:"all",hide:bl[e],explain:!0}}const t=e.detail??"normal";if(!bl[t])throw new Error(`steps.detail: "${t}" is not one of ${Object.keys(bl).join(", ")}`);return{show:e.show??"all",hide:[...bl[t],...e.hide??[]],explain:e.explain??!0}}function wl(e,t){if(!t)return[];const n=[];let r=null;for(const s of e){if(!(vl(s,t.show)&&!vl(s,t.hide))){r=r??{from:s.from,ids:[]},r.ids.push(s.id);continue}const e={...s};r&&(e.from=r.from,e.also=r.ids,e.path=null,r=null);!0===t.explain||!1!==t.explain&&vl(s,t.explain)||delete e.explanation,n.push(e)}if(r&&n.length){const t=n[n.length-1];t.to=e[e.length-1].to,t.also=[...t.also??[],...r.ids]}return n}const xl=Di(Ti.ONE),$l=(e,t)=>"atom"===e.k&&"sym"===e.node.type&&e.node.token===t;function kl(e){switch(e.k){case"num":default:return e;case"atom":return"op"===e.node.type?$o(e.node.op,e.node.args.map(e=>kl(qo(e)))):e;case"add":return so(To(e).map(kl));case"mul":{let t=[Di(e.c)];for(const n of e.fs){const e=kl(n.b);if("add"===e.k&&Hi(n.e)&&n.e.q.isInteger&&n.e.q.sign>0&&n.e.q.n<=BigInt(60))for(let r=0n;r<n.e.q.n;r++)t=ql(t,To(e));else t=ql(t,[lo(e,n.e)])}return so(t)}}}function ql(e,t){const n=[];for(const r of e)for(const e of t)n.push(oo([r,e]));return To(so(n))}function Ml(e,t){const n=new Map;for(const r of To(kl(e))){const{coef:e,rest:s}=ro(r);let i=0;const o=[Di(e)];for(const e of s?jo(s):[]){const{b:n,e:r}="mul"===e.k&&1===e.fs.length&&e.c.isOne?e.fs[0]:{b:e,e:xl};if($l(n,t)){if(!Hi(r)||!r.q.isInteger||r.q.sign<0)return null;i+=Number(r.q.n)}else{if(Nl(n,t)||Nl(r,t))return null;o.push(e)}}n.set(i,so([n.get(i)??Di(Ti.ZERO),oo(o)]))}for(const[e,t]of n)Hi(t)&&t.q.isZero&&n.delete(e);return n}const Nl=(e,t)=>_o(Oo(e)).has(t);function Sl(e){if(!e)return null;const t=Math.max(0,...e.keys());if(t>256)return null;const n=[];for(let r=0;r<=t;r++){const t=e.get(r)??Di(Ti.ZERO);if(!Hi(t))return null;n.push(t.q)}return n}function Al(e,t){const n=qo(fi(t));return so(e.map((e,t)=>oo([Di(e),ao(n,Di(Ti.of(t)))])))}const Ol=e=>{const t=e.slice();for(;t.length>1&&t[t.length-1].isZero;)t.pop();return t},El=(e,t)=>e.reduceRight((e,n)=>e.mul(t).add(n),Ti.ZERO);function Il(e,t){const n=e.length-1,r=new Array(n);let s=Ti.ZERO;for(let i=n;i>=1;i--)s=e[i].add(s.mul(t)),r[i-1]=s;return r}function _l(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 r=0;for(;n%e===0n;)n/=e,r++;t.push([e,r])}n>1n&&t.push([n,1]);let r=[1n];for(const[e,n]of t){const t=[];for(const s of r)for(let r=0,i=1n;r<=n;r++,i*=e)t.push(s*i);if(r=t,r.length>2e4)return null}return r.sort((e,t)=>e<t?-1:e>t?1:0)}function Tl(e){let t=Ol(e);const n=[];for(;t.length>1&&t[0].isZero;)n.push(Ti.ZERO),t=t.slice(1);if(t.length<=1)return{roots:n,rest:t};const r=t.reduce((e,t)=>e*t.d/_i(e,t.d),1n),s=t.map(e=>e.n*r/e.d),i=_l(s[0]),o=_l(s[s.length-1]);if(!i||!o)return{roots:n,rest:t};const a=new Map;for(const e of i)for(const t of o)for(const n of[1n,-1n]){const r=new Ti(n*e,t);a.set(r.toString(),r)}const l=[...a.values()].sort((e,t)=>e.compare(t));for(const e of l)for(;t.length>1&&El(t,e).isZero;)n.push(e),t=Il(t,e);return{roots:n.sort((e,t)=>e.compare(t)),rest:t}}function jl(e){if("num"===e.k)return{coef:e.q,factors:[],notes:[]};if("atom"===e.k)return{coef:Ti.ONE,factors:[{base:e,exp:xl}],notes:[]};if("mul"===e.k){let t=e.c;const n=[],r=[];for(const s of e.fs)if("add"===s.b.k&&Hi(s.e)&&s.e.q.isInteger){const e=jl(s.b);t=t.mul(e.coef.pow(s.e.q.n));for(const t of e.factors)n.push({base:t.base,exp:oo([t.exp,s.e])});r.push(...e.notes)}else n.push({base:s.b,exp:s.e});return Cl(t,n,r)}return function(e){const t=To(e),n=[],r=t.map(e=>{const{coef:t,rest:n}=ro(e);return{coef:t,fs:n?jo(n).map(Ll):[]}}),s=r.reduce((e,t)=>({n:_i(e.n,t.coef.n),d:e.d*t.coef.d/_i(e.d,t.coef.d)}),{n:0n,d:1n});let i=new Ti(s.n||1n,s.d);zl(e)<0&&(i=i.neg());const o=[];for(const e of r[0].fs){if(!Hi(e.e)||e.e.q.sign<=0)continue;let t=e.e.q;const n=Qi(e.b);let s=!0;for(const e of r.slice(1)){const r=e.fs.find(e=>Qi(e.b)===n&&Hi(e.e)&&e.e.q.sign>0);if(!r){s=!1;break}r.e.q.compare(t)<0&&(t=r.e.q)}s&&o.push({base:e.b,exp:Di(t)})}let a=e;if(!i.isOne||o.length){const e=oo([Di(i),...o.map(e=>lo(e.base,e.exp))]);a=so(t.map(t=>oo([t,ao(e,Di(Ti.MINUS_ONE))]))),n.push({id:"factor.common",values:{common:e}})}const l="add"===a.k?function(e,t){const n=[...Rl(e)];for(const r of n){const s=Sl(Ml(e,r));if(!s||s.length<3)continue;if(1!==n.length)break;const{roots:i,rest:o}=Tl(s);if(!i.length)break;const a=[];let l=o[o.length-1]??Ti.ONE;const u=o.map(e=>e.div(l)),c=[...i].sort((e,t)=>e.abs().compare(t.abs())||t.sign-e.sign);for(const e of c){const n=Al([new Ti(-e.n),new Ti(e.d)],r);a.push({base:n,exp:xl}),l=l.div(new Ti(e.d)),t.push({id:"factor.root",values:{root:Di(e),factor:n}})}if(u.length>1){const e=u.reduce((e,t)=>e*t.d/_i(e,t.d),1n),t=u.map(t=>t.mul(new Ti(e))),n=t.reduce((e,t)=>_i(e,t.n),0n)||1n;l=l.mul(new Ti(n,e)),a.push({base:Al(t.map(e=>e.div(new Ti(n))),r),exp:xl})}return Cl(l,a,[])}const r=To(e);if(2===r.length){const[e,n]=r;for(const r of[2,3]){const s=Zl(e,r),i=Zl(vo(n),r),o=3===r?Zl(n,r):null;if(s&&i&&2===r){t.push({id:"factor.squares",values:{a:s,b:i}});const e=jl(so([s,vo(i)])),n=jl(so([s,i]));return Cl(e.coef.mul(n.coef),[...e.factors,...n.factors],[...e.notes,...n.notes])}if(3===r&&s&&(i||o)){const e=i??o,n=i?-1:1;t.push({id:n<0?"factor.cubes-difference":"factor.cubes-sum",values:{a:s,b:e}});const r=so(n<0?[s,vo(e)]:[s,e]),a=so([ao(s,Di(Ti.of(2))),n<0?oo([s,e]):vo(oo([s,e])),ao(e,Di(Ti.of(2)))]),l=jl(r);return Cl(l.coef,[...l.factors,{base:a,exp:xl}],l.notes)}}}return{coef:Ti.ONE,factors:[{base:e,exp:xl}],notes:[]}}(a,n):jl(a);return Cl(i.mul(l.coef),[...o,...l.factors],[...n,...l.notes.filter(e=>!n.includes(e))])}(e)}function Cl(e,t,n){const r=new Map;for(const e of t){const t=Qi(e.base),n=r.get(t);n?n.exp=so([n.exp,e.exp]):r.set(t,{...e})}return{coef:e,factors:[...r.values()].filter(e=>!(Hi(e.exp)&&e.exp.q.isZero)),notes:n}}const zl=e=>ro(To(e)[0]).coef.sign;const Ll=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length?{b:e.fs[0].b,e:e.fs[0].e}:{b:e,e:xl},Rl=e=>_o(Oo(e));function Zl(e,t){const{coef:n,rest:r}=ro(e);if(n.sign<0)return null;const s=function(e,t){const n=e=>{if(e<0n)return null;let n=0n,r=1n;for(;r**BigInt(t)<=e;)r*=2n;for(;n<r-1n;){const s=(n+r)/2n;s**BigInt(t)<=e?n=s:r=s}return n**BigInt(t)===e?n:null},r=n(e.n),s=n(e.d);return null!==r&&null!==s?new Ti(r,s):null}(n,t);if(!s)return null;const i=[Di(s)];for(const e of r?jo(r).map(Ll):[]){if(!Hi(e.e))return null;const n=e.e.q.div(Ti.of(t));if(!n.isInteger)return null;i.push(lo(e.b,Di(n)))}return oo(i)}function Fl({coef:e,factors:t}){const n=[],r=[];for(const e of t){const t=Hi(e.exp)&&e.exp.q.sign<0,s=t?Di(e.exp.q.neg()):e.exp,i=Oo(lo(e.base,s));(t?r:n).push(i)}const s=e=>e.reduce((e,t)=>e?bi("*",[e,t]):t,null),i=e.n<0n?-e.n:e.n;let o=n.length?s(1n===i?n:[Oo(Di(new Ti(i))),...n]):Oo(Di(new Ti(i)));return e.n<0n&&(o=bi("neg",[o])),1n!==e.d&&r.unshift(Oo(Di(new Ti(e.d)))),r.length?bi("/",[o,s(r)]):o}function Bl(e){if("mul"!==e.k)return{num:e,den:xl};const t=[Di(new Ti(e.c.n))],n=[Di(new Ti(e.c.d))];for(const r of e.fs)Hi(r.e)&&r.e.q.sign<0?n.push(lo(r.b,Di(r.e.q.neg()))):t.push(lo(r.b,r.e));return{num:oo(t),den:oo(n)}}function Pl(e){if("add"!==e.k)return Bl(e);const t=To(e).map(Bl),n=new Map;let r=1n;for(const e of t){const{coef:t,rest:s}=ro(e.den);r=r*t.n/_i(r,t.n);for(const e of s?jo(s).map(Ll):[]){const t=Qi(e.b),r=n.get(t);(!r||Hi(e.e)&&Hi(r.e)&&e.e.q.compare(r.e.q)>0)&&n.set(t,e)}}const s=oo([Di(new Ti(r)),...[...n.values()].map(e=>lo(e.b,e.e))]);if(Hi(s)&&s.q.isOne)return{num:e,den:xl};const i=kl(so(t.map(e=>oo([e.num,s,ao(e.den,Di(Ti.MINUS_ONE))]))));return{num:i,den:s}}function Dl(e){const{num:t,den:n}=Pl(e);if(Hi(n)&&n.q.isOne)return null;const r=jl(t),s=jl(n),i=new Set(r.factors.map(e=>Qi(e.base))),o=s.factors.filter(e=>i.has(Qi(e.base))),a=[...r.factors,...s.factors.map(e=>({base:e.base,exp:vo(e.exp)}))];return{...Cl(r.coef.div(s.coef),a,[...r.notes,...s.notes]),cancelled:o.map(e=>e.base)}}const Wl=(e,t)=>bi("=",[e,t]),Ul=Mo(bi("+",[fi("x"),bi("neg",[fi("x")])])),Vl=e=>yi(e)&&"="===e.op;function Hl(e,t,n,r={}){const s=[],i=(t,n,r,i,o,a={})=>s.push(e.step(t,n,r,i,o,a));i.raw=e=>s.push(e);const o=Vl(t)?t:Wl(t,Ul),a=Wl(Mo(o.args[0]),Mo(o.args[1]));a.s!==o.s&&i("normal","Work out each side",["tidy","arithmetic"],o,a);const l=[],u=[],c=new Set;l.numeric=c,Kl(e,a,n,r,i,l,u,0);const h=[],p=new Set;for(const t of l.map(t=>c.has(t)?t:(t=>gl(t,e.set.view("simplify"),{format:e.format}).node)(t))){const e=t.s;if(p.has(e))continue;p.add(e);const r=c.has(t)?null:Ql(o,n,t);r?i("solve.reject","Check the answer",["check"],Wl(fi(n),t),Wl(fi(n),t),{value:t,reason:r}):h.push(t)}return h.sort(Gl),{solutions:h,unsolved:u,steps:s,always:u.some(e=>e.always)}}function Gl(e,t){const n=Xl(e),r=Xl(t);return null===n||null===r?e.s<t.s?-1:1:(Math.abs(n.im)>0)-(Math.abs(r.im)>0)||n.re-r.re||n.im-r.im}function Xl(e){if(_o(e).size)return null;try{const{re:t,im:n}=el(e,{digits:20});return{re:t,im:n}}catch{return null}}function Ql(e,t,n){const[r,s]=e.args,i=new Set([..._o(r),..._o(s),..._o(n)]);if(i.delete(t),i.size)return null;const o=e=>Jl(e,t,n);try{const e=el(o(r),{digits:40}),t=el(o(s),{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 Jl(e,t,n){return"sym"===e.type?e.token===t?n:e:yi(e)?bi(e.op,e.args.map(e=>Jl(e,t,n))):e}const Yl=24;function Kl(e,t,n,r,s,i,o,a){if(a>Yl)return ou(e,t,n,r,s,i,o);const l=function(e){const t=[],n=e=>{if(yi(e)&&"|"===e.op)return void e.args.forEach(n);if(!Vl(e))return void t.push(e);const r=e.args[1],s=Ni(r,"pre").find(({node:e})=>yi(e)&&"pm"===e.op);if(!s)return void t.push(e);const i=s.node.args[0],o=Mo(Si(r,s.path,i)),a=Mo(Si(r,s.path,bi("neg",[i])));n(Wl(e.args[0],o)),a.s!==o.s&&n(Wl(e.args[0],a))};return n(e),t}(t);if(l.length>1){s("solve.split","Two cases",["split"],t,l.reduce((e,t)=>e?bi("|",[e,t]):t,null));for(const t of l)Kl(e,t,n,r,s,i,o,a+1);return}if(1===l.length&&l[0].s!==t.s)return Kl(e,l[0],n,r,s,i,o,a+1);const[u,c]=t.args;if("sym"===u.type&&u.token===n&&!Nl(qo(c),n))return void i.push(c);const h=so([qo(u),vo(qo(c))]);if(!Nl(h,n))return Hi(h)&&h.q.isZero?(s("solve.always","Always true",["check"],t,t,{v:n}),void o.push(Object.assign(Object.create(t),{always:!0}))):void s("solve.never","No solution",["check"],t,t,{v:n});const p=To(h).filter(e=>Nl(e,n)),f=To(h).filter(e=>!Nl(e,n)),m=so(p),d=vo(so(f));if(Zi.complex){const l=Ml(h,n);if(l&&[...l.values()].every(e=>!Nl(e,n))&&Math.max(...l.keys())>=2){const u=Wl(Oo(h),Ul);return u.s!==t.s&&s("solve.one-side","Everything on one side",["move"],t,u,{v:n}),su(e,h,l,n,r,s,i,o,a,u)}}if(1===p.length)return eu(e,t,m,d,n,r,s,i,o,a);const g=Wl(Oo(h),Ul),b=Ml(h,n);if(b&&[...b.values()].every(e=>!Nl(e,n))&&Math.max(...b.keys())>=2)return g.s!==t.s&&s("solve.one-side","Everything on one side",["move"],t,g,{v:n}),su(e,h,b,n,r,s,i,o,a,g);const v=jl(h),y=v.factors.filter(e=>Nl(e.base,n)&&!(Hi(e.exp)&&e.exp.q.sign<0));if(y.length>=2||1===y.length&&v.factors.length>1){const l=Wl(Fl(v),Ul);g.s!==t.s&&s("solve.one-side","Everything on one side",["move"],t,g,{v:n}),l.s!==g.s&&s("solve.factor","Factor",["factor"],g,l,{});const u=y.map(e=>Wl(Oo(e.base),Ul));u.length>1&&s("solve.zero-product","A product is zero when a factor is",["split"],l,u.reduce((e,t)=>e?bi("|",[e,t]):t,null),{});for(const t of u)Kl(e,t,n,r,s,i,o,a+1);return}const w=Pl(h);if(Nl(w.den,n)){const l=Wl(Oo(w.num),Ul);return s("solve.clear-denominator","Clear the denominator",["move"],t,l,{den:Oo(w.den)}),Kl(e,l,n,r,s,i,o,a+1)}const x=p.filter(e=>!ru(e,n));if(1===x.length&&/\b(sqrt|root|abs)\b/.test(Oo(x[0]).s))return eu(e,t,x[0],vo(so(To(h).filter(e=>e!==x[0]))),n,r,s,i,o,a);const $=function(e,t){const n=Oo(e),r=new Map;for(const{node:e}of Ni(n,"pre"))if(yi(e)&&_o(e).has(t))if("^"!==e.op||_o(e.args[0]).has(t))["sin","cos","tan","ln","sqrt","abs"].includes(e.op)&&e.args[0].s===t&&r.set(e.s,e);else{const n=qo(e.args[1]),{coef:s,rest:i}=ro(n);if(i&&s.isInteger&&Oo(i).s===t){const n=Oo(ao(qo(e.args[0]),qo(fi(t))));r.set(n.s,n)}}const s="u"===t?"w":"u";for(const e of r.values()){const r=iu(n,e,t,s);if(!r||_o(r).has(t))continue;const i=qo(r),o=Ml(i,s);if(o&&Math.max(...o.keys())>=1)return{kernel:qo(e),poly:i,symbol:s}}return null}(h,n);if($){const t=$.symbol;s("solve.substitute","Substitute",["substitute"],g,Wl(Oo($.poly),Ul),{u:fi(t),kernel:Oo($.kernel)});const l=[];Kl(e,Wl(Oo($.poly),Ul),t,r,s,l,o,a+1);for(const t of l)Kl(e,Wl(Oo($.kernel),t),n,r,s,i,o,a+1);return}return ou(e,g,n,r,s,i,o)}function eu(e,t,n,r,s,i,o,a,l,u){let c=Wl(Oo(n),Oo(r));c.s!==t.s&&o("solve.move","Move the terms",["move"],t,c,{v:s});const{coef:h,rest:p}=ro(n),f=p?jo(p):[],m=oo([Di(h),...f.filter(e=>!Nl(e,s))]);if(!Hi(m)||!m.q.isOne){const e=oo(f.filter(e=>Nl(e,s))),t=Wl(Oo(e),Oo(yo(r,m))),n=Hi(m)&&!m.q.isInteger&&(1n===m.q.n||-1n===m.q.n);o(n?"solve.multiply":"solve.divide",n?"Multiply both sides":"Divide both sides",["move"],c,t,{by:Oo(n?Di(m.q.inv()):m),v:s}),c=t}if("sym"===c.args[0].type&&c.args[0].token===s)return void a.push(c.args[1]);const d=qo(c.args[1]);if(Hi(d)&&d.q.isZero){const t=qo(c.args[0]),n=jo(t).filter(e=>Nl(e,s)&&!tu(e));if(n.length>1||n.length<jo(t).filter(e=>Nl(e,s)).length){const t=n.map(e=>Wl(Oo(nu(e)),Ul));o("solve.zero-product","A product is zero when a factor is",["split"],c,t.reduce((e,t)=>e?bi("|",[e,t]):t,null),{});for(const n of t)Kl(e,n,s,i,o,a,l,u+1);return}}const g=gl(c,e.set.view("isolate"),{format:e.format,maxSteps:1,variable:s});return g.steps.length?(function(e,t){for(const n of t)e.raw(n)}(o,g.steps),Kl(e,g.node,s,i,o,a,l,u+1)):ou(e,c,s,i,o,a,l)}const tu=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&Hi(e.fs[0].e)&&e.fs[0].e.q.sign<0,nu=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&Hi(e.fs[0].e)&&e.fs[0].e.q.sign>0?e.fs[0].b:e,ru=(e,t)=>{const n=Ml(e,t);return Boolean(n)&&[...n.values()].every(e=>!Nl(e,t))};function su(e,t,n,r,s,i,o,a,l,u){const c=Math.max(...n.keys()),h=Sl(n);if(Zi.complex&&c>=3&&c<=64&&h&&h.every((e,t)=>0===t||t===c||e.isZero)&&!h[0].isZero){const t=h[0].neg().div(h[c]),n=ao(Di(t.abs()),Di(new Ti(1n,BigInt(c)))),s=[];for(let r=0;r<c;r++){const i=oo([Di(new Ti(BigInt((t.sign<0?1:0)+2*r),BigInt(c))),qo(fi("pi"))]),o=bi("*",[Oo(n),bi("+",[bi("cos",[Oo(i)]),bi("*",[fi("i"),bi("sin",[Oo(i)])])])]);s.push(gl(o,e.set.view("simplify"),{format:e.format}).node)}return i("solve.roots","All n roots",["complex"],u,s.map(e=>Wl(fi(r),e)).reduce((e,t)=>e?bi("|",[e,t]):t),{v:r,n:String(c),last:String(c-1),r:Oo(Di(t))}),void o.push(...s)}if(h){const{roots:n}=Tl(h);if(n.length){const n=jl(t),c=Wl(Fl(n),Ul);if(n.factors.length>1||n.factors.some(e=>!(Hi(e.exp)&&e.exp.q.isOne))){i("solve.factor","Factor",["factor"],u,c,{});const t=n.factors.filter(e=>Nl(e.base,r)).map(e=>Wl(Oo(e.base),Ul));t.length>1&&i("solve.zero-product","A product is zero when a factor is",["split"],c,t.reduce((e,t)=>e?bi("|",[e,t]):t,null),{});for(const n of t)Kl(e,n,r,s,i,o,a,l+1);return}}}if(2===c){const e=n.get(2),t=n.get(1)??Di(Ti.ZERO),s=n.get(0)??Di(Ti.ZERO),a=so([ao(t,Di(Ti.of(2))),oo([Di(Ti.of(-4)),e,s])]);if(Hi(a)&&a.q.sign<0&&!Zi.complex)return void i("solve.no-real","No real solutions",["quadratic"],u,u,{D:Oo(a)});const l=oo([Di(Ti.of(2)),e]),c=ao(a,Di(Ti.HALF)),h=Oo(yo(so([vo(t),c]),l)),p=Oo(yo(so([vo(t),vo(c)]),l)),f=h.s===p.s?Wl(fi(r),h):bi("|",[Wl(fi(r),h),Wl(fi(r),p)]);return i(Zi.complex&&Hi(a)&&a.q.sign<0?"solve.quadratic-complex":"solve.quadratic","The quadratic formula",["quadratic"],u,f,{a:Oo(e),b:Oo(t),c:Oo(s),D:Oo(a),root:Oo(c),v:r}),o.push(h),void(p.s!==h.s&&o.push(p))}return ou(e,u,r,s,i,o,a)}function iu(e,t,n,r){if(e.s===t.s)return fi(r);if(!yi(e))return e;if("^"===e.op&&"^"===t.op&&e.args[0].s===t.args[0].s){const t=qo(e.args[1]),{coef:s,rest:i}=ro(t);if(i&&Oo(i).s===n&&s.isInteger)return bi("^",[fi(r),Oo(Di(s))])}return bi(e.op,e.args.map(e=>iu(e,t,n,r)))}function ou(e,t,n,r,s,i,o){if(r.approximate){const e="number"==typeof r.approximate?r.approximate:15,o=qo(bi("-",[t.args[0],t.args[1]])),a=Zi.complex?Sl(Ml(o,n)):null,l=a&&a.length>2?function(e,t){const n=e.length-1,r=e[n],s=e.map(e=>e/r),i=(e,t)=>{let r=1,i=0;for(let o=n-1;o>=0;o--)[r,i]=[r*e-i*t+s[o],r*t+i*e];return[r,i]};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,r],s)=>{let[a,l]=i(t,r);for(let e=0;e<n;e++){if(e===s)continue;const n=t-o[e][0],i=r-o[e][1],u=n*n+i*i;[a,l]=[(a*n+l*i)/u,(l*n-a*i)/u]}return e=Math.max(e,Math.hypot(a,l)),[t-a,r-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=au(e);if(0===t)return n;const r=bi("*",[au(Math.abs(t)),fi("i")]);return 0===e?t<0?bi("neg",[r]):r:bi(t<0?"-":"+",[n,r])})}(a.map(e=>e.toNumber()),Math.min(e,14)):function(e,t,n){const r=qo(bi("-",[e.args[0],e.args[1]])),s=Oo(r),i=e=>{try{return el(Jl(s,t,lu(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],r=a[e+1],s=i(t);const l=i(r);if(Number.isNaN(s)||Number.isNaN(l))continue;if(0===s){o.push(lu(t));continue}if(s*l>0)continue;for(let e=0;e<200&&r-t>1e-16*Math.abs(t);e++){const e=(t+r)/2,n=i(e);if(Number.isNaN(n))break;s*n<=0?r=e:(t=e,s=n)}const u=(t+r)/2;Math.abs(i(u))<1e-6&&o.push(lu(Number(u.toPrecision(Math.min(n,15)))))}return o}(t,n,e);for(const e of l)i.numeric?.add(e);return s("solve.numeric","Numeric solutions",["numeric"],t,l.length?l.map(e=>Wl(fi(n),e)).reduce((e,t)=>e?bi("|",[e,t]):t):t,{v:n,count:String(l.length)}),void i.push(...l)}s("solve.unsolved","No exact method",["unsolved"],t,t,{v:n}),o.push(t)}const au=e=>mi(String(e).includes("e")?e.toFixed(20):String(e)),lu=e=>mi(Number.isInteger(e)?String(e):e.toFixed(17));const uu=(e,t)=>bi("int",[e,"string"==typeof t?fi(t):t]);function cu(e,t,n,r=0){if(r>6)throw new Ai("integration went too deep");const s=[],i=e.set.view("integrate"),o=gl(t,e.set.view("simplify"),{format:e.format});s.push(...o.steps);let a=Mo(uu(o.node,n));for(let t=0;t<40;t++){const t=gl(a,i,{format:e.format});s.push(...t.steps),a=t.node;const n=Ni(a,"pre").find(({node:e})=>{return yi(t=e)&&"int"===t.op&&2===t.args.length;var t});if(!n)return{node:a,steps:s};const o=hu(e,n.node,r);if(!o)throw new Ai(`no rule for ∫ ${e.format(n.node.args[0])} d${n.node.args[1].token}`);s.push(...o.steps),a=Mo(Si(a,n.path,o.node))}throw new Ai("integration did not finish")}function hu(e,t,n){const[r,s]=t.args,i=s.token,o=qo(r),a=function(e,t){const{num:n,den:r}=Pl(e),s=jl(n),i=jl(r),o=s.coef.div(i.coef);if(o.isOne||!Nl(e,t))return null;const a=oo([...s.factors.map(e=>lo(e.base,e.exp)),...i.factors.map(e=>lo(e.base,vo(e.exp)))]);return{c:o,rest:a}}(o,i);if(a){const n=bi("*",[Oo(Di(a.c)),uu(Oo(a.rest),s)]);return{node:n,steps:[e.step("integrate.constant","Take the number out",["split"],t,n,{c:Oo(Di(a.c))})]}}const l=kl(o);if(Oo(l).s!==r.s&&"add"===l.k){const n=uu(Oo(l),s);return{node:n,steps:[e.step("integrate.expand","Multiply out",["expand"],t,n,{})]}}const u=function(e,t){const n=new Map;for(const{node:r}of Ni(e,"pre")){if(!yi(r))continue;const e="^"===r.op?r.args:"/"===r.op?[r.args[1]]:"der"===r.op||"int"===r.op?[]:1===r.args.length||"root"===r.op?[r.args[r.args.length-1]]:[];for(const r of e){if("sym"===r.type||!_o(r).has(t))continue;const e=Ml(qo(r),t);if(!e||1!==Math.max(...e.keys()))continue;const s=e.get(1);Nl(s,t)||Hi(s)&&s.q.isZero||n.set(r.s,{node:r,a:s})}}for(const r of n.values()){if(!_o(pu(e,r.node,fi("§"))).has(t))return r}return null}(r,i);if(u){const s="u"===i?"t":"u",o=pu(r,u.node,fi(s));if(!_o(o).has(i)){const r=cu(e,Mo(o),s,n+1),a=Mo(Jl(r.node,s,u.node)),l=Oo(yo(qo(a),u.a));return{node:l,steps:[e.step("integrate.substitute","Substitute",["substitute"],t,Mo(uu(o,s)),{u:fi(s),inside:u.node,a:Oo(u.a),v:i}),...r.steps,e.step("integrate.back","Substitute back",["substitute"],r.node,l,{u:fi(s),inside:u.node})]}}}const c=function(e,t,n,r){const{num:s,den:i}=Pl(n);if(!Nl(i,r))return null;const o=Sl(Ml(s,r)),a=Sl(Ml(i,r));if(!o||!a||a.length<2)return null;const l=qo(fi(r)),u=e=>Al(e,r);if(o.length>=a.length){const{q:n,r:s}=function(e,t){const n=Ol(t);let r=Ol(e);const s=n[n.length-1];if(s.isZero)throw new Ai("division by the zero polynomial");const i=new Array(Math.max(1,r.length-n.length+1)).fill(Ti.ZERO);for(;r.length>=n.length&&(1!==r.length||!r[0].isZero);){const e=r.length-n.length,t=r[r.length-1].div(s);if(i[e]=t,r=Ol(r.map((r,s)=>s>=e&&s-e<n.length?r.sub(t.mul(n[s-e])):r)),r.length-1<e+n.length-1&&r[r.length-1].isZero)break;if(r.length<n.length)break}return{q:Ol(i),r:r}}(o,a),i=uu(Oo(so([u(n),yo(u(s),u(a))])),fi(r));return{node:i,steps:[e.step("integrate.divide","Divide the polynomials",["divide"],t,i,{})]}}const{roots:c,rest:h}=Tl(a),p=new Set(c.map(String)).size===c.length;if(!c.length||!p||1!==h.length)return null;const f=(e=>e.length<=1?[Ti.ZERO]:e.slice(1).map((e,t)=>e.mul(Ti.of(t+1))))(a),m=c.map(e=>yo(Di(El(o,e).div(El(f,e))),so([l,Di(e.neg())]))),d=uu(Oo(so(m)),fi(r));return{node:d,steps:[e.step("integrate.partial-fractions","Partial fractions",["partial-fractions"],t,d,{})]}}(e,t,o,i);return c||function(e,t,n,r,s){if(s>=6)return null;const i=jo(n),o=i.filter(e=>fu(e,r)||!Nl(e,r)),a=i.filter(e=>!o.includes(e));if(1!==a.length)return null;const l=oo(o),u=a[0];if(!Nl(l,r))return null;const c=Oo(u),h=yi(c)?c.op:"";let p,f,m;"ln"===h||"arctan"===h||"arcsin"===h?(p=u,f=l):(p=l,f=u);try{m=cu(e,Oo(f),r,s+1)}catch{return null}const d=qo(e.differentiate(Oo(p),r)),g=oo([p,qo(m.node)]),b=uu(Oo(oo([d,qo(m.node)])),fi(r)),v=Mo(bi("-",[Oo(g),b]));return{node:v,steps:[e.step("integrate.parts","Integration by parts",["parts"],t,v,{u:Oo(p),dv:Oo(f),V:m.node,du:Oo(d),v:r})]}}(e,t,o,i,n)}function pu(e,t,n){return e.s===t.s?n:yi(e)?bi(e.op,e.args.map(e=>pu(e,t,n))):e}const fu=(e,t)=>{const n=Ml(e,t);return Boolean(n)&&[...n.values()].every(e=>!Nl(e,t))&&Math.max(...n.keys())>=1};function mu(e,t,n,r,s,i){for(const e of[r,s])if(_o(e).has("∞")||/∞|infinity/.test(e.s))throw new Ai("integrals to infinity need limits, which this CAS does not do yet");if(i&&!_o(r).size&&!_o(s).size){const o=el(r,{digits:20}).number,a=el(s,{digits:20}).number,l=[..._o(i)].filter(e=>e!==n);if(!l.length){const[r,s]=o<=a?[o,a]:[a,o];for(const o of function(e,t){const n=[],r={tan:"cos",sec:"cos",csc:"sin",cot:"sin"};return Ni(e,"pre").forEach(({node:e})=>{if(!yi(e))return;let s=null;"/"===e.op?s=e.args[1]:"^"===e.op&&"num"===e.args[1].type&&e.args[1].value<0||"^"===e.op&&yi(e.args[1])&&"neg"===e.args[1].op?s=e.args[0]:r[e.op]&&(s=bi(r[e.op],[e.args[0]])),s&&_o(s).has(t)&&!n.some(e=>e.s===s.s)&&n.push(s)}),n}(i,n)){let i=[];try{i=e.solve(bi("=",[o,mi("0")]),n,{steps:!1}).solutions}catch{continue}for(const o of i){const i=el(o,{digits:20});if(!Number.isFinite(i.number)||i.im||i.number<r||i.number>s)continue;if(i.number>r&&i.number<s)throw new Ai(`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=el(Mo(Jl(t,n,o)),{digits:15}).number}catch{}if(!Number.isFinite(a))throw new Ai(`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=el(Jl(i,n,mi(t.toFixed(15))),{digits:15}).number;if(!Number.isFinite(e))throw new Ai("not finite")}catch(e){throw new Ai(`the integrand has no value at ${n} = ${t.toPrecision(6)}, between the limits, so F(b) - F(a) would be wrong`)}}}const o=e=>Mo(Jl(t,n,e)),a=Mo(bi("-",[o(s),o(r)])),l=bi("-",[o(s),o(r)]);return{value:a,step:e.step("integrate.evaluate","Between the limits",["evaluate"],t,l,{a:r,b:s,F:t,v:n})}}const du={"=":1,"≠":1,"<":1,">":1,"≤":1,"≥":1,"+":2,"-":2,"±":2,"*":3,"/":3,neg:4,pm:4,"^":5},gu={pi:"π","≤":"≤","≥":"≥"};function bu(e){return $u(e).text}function vu(e,t,n=!1){return e.prec<t||n&&e.prec===t?`(${e.text})`:e.text}const yu=e=>"op"===e.type?e.op:null,wu=e=>e.text.startsWith("-"),xu={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]};function $u(e){if("num"===e.type)return{text:e.token,prec:e.token.startsWith("-")?4:9};if("sym"===e.type)return{text:gu[e.token]??e.token,prec:9};const t=e.args.map($u),n=du[e.op];switch(e.op){case"+":case"-":case"±":{const r="+"===e.op&&["+","-"].includes(yu(e.args[1])),s=wu(t[1])?`(${t[1].text})`:r?t[1].text:vu(t[1],n,!0);return{text:`${vu(t[0],n)} ${"±"===e.op?"±":e.op} ${s}`,prec:n}}case"*":{const r=vu(t[0],n),s=wu(t[1])?`(${t[1].text})`:"*"===yu(e.args[1])?t[1].text:vu(t[1],n,!0);return{text:"num"===e.args[0].type&&"num"!==e.args[1].type&&!/^[\d(-]/.test(s)||"sym"===e.args[1].type&&"i"===e.args[1].token&&!/[\dA-Za-z]$/.test(r)?`${r}${s}`:`${r}·${s}`,prec:n}}case"/":return{text:`${vu(t[0],n)}/${vu(t[1],n,!0)}`,prec:n};case"^":return{text:`${vu(t[0],n+1)}^${vu(t[1],n)}`,prec:n};case"neg":return{text:`-${vu(t[0],3)}`,prec:4};case"pm":return{text:`±${vu(t[0],4)}`,prec:4};case"!":return{text:`${vu(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{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:`${vu(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:`${xu[e.op][0]}${t.map(e=>e.text).join(", ")}${xu[e.op][1]}`,prec:9};case"&":return{text:`${t[0].text} and ${t[1].text}`,prec:0};default:return void 0!==n?{text:`${vu(t[0],n)} ${e.op} ${vu(t[1],n,!0)}`,prec:n}:{text:`${e.op.replace(/^\\:?/,"")}(${t.map(e=>e.text).join(", ")})`,prec:9}}}const ku=['name: Differentiation\n\n# `u v der` means d(u)/dv (MathZetta\'s postfix: mathzetta/docs/postfix.md). Every rule here rewrites one derivative into smaller\n# derivatives, so differentiating always terminates: the expressions sitting\n# under a `D` get strictly smaller at every step.\n#\n# The variable is a slot, not a fixed letter, so these rules work for d/dx,\n# d/dt or anything else. That is what freeOf and dependsOn are for: they ask\n# whether one operand mentions whatever the variable slot bound to.\n#\n# Where two rules share a structure key, requirements keep them apart and\n# priority picks the one that reads better. The constant-multiple rule outranks\n# the product rule for exactly that reason.\n\nrules:\n # ---- the two base cases ----------------------------------------------\n - id: d-constant\n name: Derivative of a constant\n mode: differentiate\n pattern: c v der\n require:\n - [freeOf, c, v]\n output: "0"\n priority: 10\n explain: "{c} does not change when {v} changes, so its rate of change is 0."\n tags: [base]\n\n - id: d-variable\n name: Derivative of the variable\n mode: differentiate\n pattern: u v der\n require:\n - [sameAs, u, v]\n output: "1"\n priority: 10\n explain: "{v} changes exactly as fast as itself, so the rate is 1."\n tags: [base]\n\n # ---- splitting a derivative into smaller ones ------------------------\n - id: d-sum\n name: Sum rule\n mode: differentiate\n pattern: u w + v der\n output: u v der w v der +\n explain: "Differentiate {u} and {w} separately, then add the two results."\n tags: [split]\n\n - id: d-difference\n name: Difference rule\n mode: differentiate\n pattern: u w - v der\n output: u v der w v der -\n explain: "Differentiate {u} and {w} separately, then subtract the second from the first."\n tags: [split]\n\n - id: d-negate\n name: Derivative of a negative\n mode: differentiate\n pattern: u neg v der\n output: u v der neg\n explain: "The minus sign just carries through to the derivative of {u}."\n tags: [split]\n\n - id: d-constant-multiple\n name: Constant multiple rule\n mode: differentiate\n pattern: c u * v der\n commutative: true\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n output: c u v der *\n priority: 5\n explain: "{c} is only a scale factor, so it comes along unchanged while {u} is differentiated."\n tags: [split]\n\n - id: d-constant-divisor\n name: Dividing by a constant\n mode: differentiate\n pattern: u c / v der\n require:\n - [freeOf, c, v]\n output: u v der c /\n priority: 5\n explain: "Dividing by {c} is only a scale factor, so differentiate {u} and keep the division."\n tags: [split]\n\n - id: d-product\n name: Product rule\n mode: differentiate\n pattern: u w * v der\n require:\n - [dependsOn, u, v]\n - [dependsOn, w, v]\n output: u v der w * u w v der * +\n explain: "Differentiate {u} and keep {w}, then keep {u} and differentiate {w}, and add the two."\n tags: [split]\n\n - id: d-quotient\n name: Quotient rule\n mode: differentiate\n pattern: u w / v der\n output: u v der w * u w v der * - w 2 ^ /\n explain: "Bottom times the derivative of the top, minus top times the derivative of the bottom, all over {w} squared."\n tags: [split]\n\n # ---- powers -----------------------------------------------------------\n - id: d-power-of-variable\n name: Power rule\n mode: differentiate\n pattern: u n ^ v der\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n output: n u n 1 - ^ *\n fold: true\n priority: 6\n explain: "Bring the {n} down in front and drop the power by one."\n tags: [power]\n\n - id: d-power-chain\n name: Power rule with the chain rule\n mode: differentiate\n pattern: u n ^ v der\n require:\n - [freeOf, n, v]\n - [dependsOn, u, v]\n output: n u n 1 - ^ * u v der *\n fold: true\n explain: "Bring the {n} down and drop the power by one, then multiply by the derivative of {u}."\n tags: [power, chain]\n\n - id: d-exponential-base\n name: Derivative of a constant to a power\n mode: differentiate\n pattern: a u ^ v der\n require:\n - [freeOf, a, v]\n - [dependsOn, u, v]\n output: a u ^ a ln * u v der *\n explain: "A constant base gives itself back, multiplied by the natural log of {a} and the derivative of {u}."\n tags: [power, chain]\n\n # ---- the standard functions, each with its chain-rule factor ---------\n # e^u is `=e u ^`: the base is the literal symbol e. Outranks the general\n # a^u rule (which would give e^u · ln e · u\').\n - id: d-exp\n name: Derivative of e to a power\n mode: differentiate\n pattern: =e u ^ v der\n require:\n - [dependsOn, u, v]\n output: =e u ^ u v der *\n priority: 7\n explain: "e to a power is its own derivative, times the derivative of {u}."\n tags: [chain]\n\n - id: d-ln\n name: Derivative of a natural log\n mode: differentiate\n pattern: u ln v der\n output: u v der u /\n explain: "The derivative of {u} over {u} itself."\n tags: [chain]\n\n - id: d-sqrt\n name: Derivative of a square root\n mode: differentiate\n pattern: u sqrt v der\n output: u v der 2 u sqrt * /\n explain: "The derivative of {u}, over twice the square root of {u}."\n tags: [chain]\n\n - id: d-sin\n name: Derivative of sine\n mode: differentiate\n pattern: u sin v der\n output: u cos u v der *\n explain: "Sine differentiates to cosine, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-cos\n name: Derivative of cosine\n mode: differentiate\n pattern: u cos v der\n output: u sin u v der * neg\n explain: "Cosine differentiates to minus sine, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-tan\n name: Derivative of tangent\n mode: differentiate\n pattern: u tan v der\n output: u v der u cos 2 ^ /\n explain: "The derivative of {u}, over cosine squared of {u}."\n tags: [chain, trig]\n\n # ---- the rest of the standard functions -----------------------------\n - id: d-csc\n name: Derivative of cosecant\n mode: differentiate\n pattern: u csc v der\n output: u csc u cot * u v der * neg\n explain: "Cosecant differentiates to minus cosecant times cotangent, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-sec\n name: Derivative of secant\n mode: differentiate\n pattern: u sec v der\n output: u sec u tan * u v der *\n explain: "Secant differentiates to secant times tangent, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-cot\n name: Derivative of cotangent\n mode: differentiate\n pattern: u cot v der\n output: u v der u sin 2 ^ / neg\n explain: "Minus the derivative of {u}, over sine squared of {u}."\n tags: [chain, trig]\n\n - id: d-arcsin\n name: Derivative of arcsine\n mode: differentiate\n pattern: u arcsin v der\n output: u v der 1 u 2 ^ - sqrt /\n explain: "The derivative of {u}, over the square root of 1 minus {u} squared."\n tags: [chain, trig]\n\n - id: d-arccos\n name: Derivative of arccosine\n mode: differentiate\n pattern: u arccos v der\n output: u v der 1 u 2 ^ - sqrt / neg\n explain: "Minus the derivative of {u}, over the square root of 1 minus {u} squared."\n tags: [chain, trig]\n\n - id: d-arctan\n name: Derivative of arctangent\n mode: differentiate\n pattern: u arctan v der\n output: u v der 1 u 2 ^ + /\n explain: "The derivative of {u}, over 1 plus {u} squared."\n tags: [chain, trig]\n\n - id: d-sinh\n name: Derivative of hyperbolic sine\n mode: differentiate\n pattern: u sinh v der\n output: u cosh u v der *\n explain: "Hyperbolic sine differentiates to hyperbolic cosine, times the derivative of {u}."\n tags: [chain, hyperbolic]\n\n - id: d-cosh\n name: Derivative of hyperbolic cosine\n mode: differentiate\n pattern: u cosh v der\n output: u sinh u v der *\n explain: "Hyperbolic cosine differentiates to hyperbolic sine — no minus sign, unlike cosine — times the derivative of {u}."\n tags: [chain, hyperbolic]\n\n - id: d-tanh\n name: Derivative of hyperbolic tangent\n mode: differentiate\n pattern: u tanh v der\n output: u v der u cosh 2 ^ /\n explain: "The derivative of {u}, over hyperbolic cosine squared of {u}."\n tags: [chain, hyperbolic]\n\n - id: d-arcsinh\n name: Derivative of inverse hyperbolic sine\n mode: differentiate\n pattern: u arcsinh v der\n output: u v der u 2 ^ 1 + sqrt /\n explain: "The derivative of {u}, over the square root of {u} squared plus 1."\n tags: [chain, hyperbolic]\n\n - id: d-arccosh\n name: Derivative of inverse hyperbolic cosine\n mode: differentiate\n pattern: u arccosh v der\n output: u v der u 2 ^ 1 - sqrt /\n explain: "The derivative of {u}, over the square root of {u} squared minus 1."\n tags: [chain, hyperbolic]\n\n - id: d-arctanh\n name: Derivative of inverse hyperbolic tangent\n mode: differentiate\n pattern: u arctanh v der\n output: u v der 1 u 2 ^ - /\n explain: "The derivative of {u}, over 1 minus {u} squared."\n tags: [chain, hyperbolic]\n\n # log base a: `a u log` in MathZetta\'s postfix\n - id: d-log\n name: Derivative of a logarithm\n mode: differentiate\n pattern: a u log v der\n require:\n - [freeOf, a, v]\n output: u v der u a ln * /\n explain: "The derivative of {u}, over {u} times the natural log of {a}."\n tags: [chain]\n\n - id: d-abs\n name: Derivative of an absolute value\n mode: differentiate\n pattern: u abs v der\n output: u u abs / u v der *\n explain: "The absolute value keeps the sign of {u}: {u} over its absolute value, times the derivative of {u}."\n tags: [chain]\n\n # n-th root: `n u root`\n - id: d-root\n name: Derivative of a root\n mode: differentiate\n pattern: n u root v der\n require:\n - [freeOf, n, v]\n output: u v der n n u root n 1 - ^ * /\n fold: true\n explain: "The derivative of {u}, over {n} times the {n}th root of {u} to the power {n} minus 1."\n tags: [chain]\n','name: More derivatives\n\n# Derivative rules the CAS adds to rules/calculus.yaml (which calcvidnew also uses).\n\nrules:\n - id: d-general-power\n name: A power with the variable in both places\n mode: differentiate\n pattern: u w ^ v der\n require:\n - [dependsOn, u, v]\n - [dependsOn, w, v]\n output: u w ^ w v der u ln * w u v der * u / + *\n explain: "Write {u}^{w} as e^({w} ln {u}) and use the chain rule: the derivative is {u}^{w} times the derivative of {w} ln {u}."\n tags: [chain]\n','name: Integrals\n\n# mode: integrate. `f v 2 int` is ∫ f dv (MathZetta\'s postfix; the 2 counts f and v).\n# Each rule turns one integral into smaller ones, or into an answer. The CAS also\n# tries, when no rule fits: multiplying out, a linear substitution (∫ f(ax + b) dx\n# from the rule for ∫ f(u) du), and integration by parts for polynomial × e^, sin,\n# cos, ln, arctan. Definite integrals are the antiderivative between the limits.\n#\n# Patterns see the normal form: 1/x is "1 x /", x^-2 is "1 x 2 ^ /", √x is "x sqrt",\n# 1/√(1 - x²) is "1 x 2 ^ neg 1 + sqrt /".\n\nrules:\n # ---- splitting -----------------------------------------------------------\n - id: i-sum\n name: Sum rule\n mode: integrate\n pattern: u w + v 2 int\n output: u v 2 int w v 2 int +\n explain: "Integrate {u} and {w} separately, and add."\n tags: [split]\n\n - id: i-difference\n name: Difference rule\n mode: integrate\n pattern: u w - v 2 int\n output: u v 2 int w v 2 int -\n explain: "Integrate {u} and {w} separately, and subtract."\n tags: [split]\n\n - id: i-negate\n name: A minus sign\n mode: integrate\n pattern: u neg v 2 int\n output: u v 2 int neg\n explain: "The minus sign comes out of the integral."\n tags: [split]\n\n - id: i-constant-multiple\n name: Constant multiple\n mode: integrate\n pattern: c u * v 2 int\n commutative: true\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n output: c u v 2 int *\n priority: 5\n explain: "{c} doesn\'t change with {v}, so it comes out of the integral."\n tags: [split]\n\n - id: i-constant-divisor\n name: Dividing by a constant\n mode: integrate\n pattern: u c / v 2 int\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n output: u v 2 int c /\n priority: 5\n explain: "Dividing by {c} comes out of the integral."\n tags: [split]\n\n - id: i-constant-over\n name: A constant over something\n mode: integrate\n pattern: c u / v 2 int\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n when:\n c: [notOne]\n output: c 1 u / v 2 int *\n priority: 4\n explain: "{c} comes out of the integral, leaving ∫ 1/{u}."\n tags: [split]\n\n # ---- the table -----------------------------------------------------------\n - id: i-constant\n name: Integral of a constant\n mode: integrate\n pattern: c v 2 int\n require:\n - [freeOf, c, v]\n output: c v *\n priority: 10\n explain: "A constant {c} integrates to {c}·{v}."\n tags: [base]\n\n - id: i-variable\n name: Integral of the variable\n mode: integrate\n pattern: u v 2 int\n require:\n - [sameAs, u, v]\n output: v 2 ^ 2 /\n priority: 10\n explain: "∫ {v} d{v} = {v}²/2."\n tags: [base]\n\n - id: i-power\n name: Power rule\n mode: integrate\n pattern: u n ^ v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n when:\n n: [notMinusOne]\n output: v n 1 + ^ n 1 + /\n explain: "Add 1 to the power and divide by the new power: {result}."\n tags: [power]\n\n - id: i-reciprocal\n name: Integral of 1/x\n mode: integrate\n pattern: 1 u / v 2 int\n require:\n - [sameAs, u, v]\n output: v abs ln\n explain: "∫ 1/{v} d{v} = ln|{v}| (the power rule can\'t divide by 0 here)."\n tags: [log]\n\n - id: i-reciprocal-power\n name: Power rule (a power below)\n mode: integrate\n pattern: 1 u n ^ / v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n when:\n n: [notOne]\n output: v 1 n - ^ 1 n - /\n explain: "1/{v}^{n} is {v}^(-{n}): add 1 to the power and divide by it."\n tags: [power]\n\n - id: i-sqrt\n name: Integral of a square root\n mode: integrate\n pattern: u sqrt v 2 int\n require:\n - [sameAs, u, v]\n output: 2 v 3 2 / ^ * 3 /\n explain: "√{v} is {v}^(1/2): add 1 to the power and divide by 3/2."\n tags: [power]\n\n - id: i-reciprocal-sqrt\n name: Integral of 1/√x\n mode: integrate\n pattern: 1 u sqrt / v 2 int\n require:\n - [sameAs, u, v]\n output: 2 v sqrt *\n explain: "1/√{v} is {v}^(-1/2): add 1 to the power and divide by 1/2."\n tags: [power]\n\n - id: i-root\n name: Integral of a root\n mode: integrate\n pattern: n u root v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n output: v 1 n / 1 + ^ 1 n / 1 + /\n explain: "The {n}th root of {v} is {v}^(1/{n}): add 1 to the power and divide by it."\n tags: [power]\n\n - id: i-exp\n name: Integral of e^x\n mode: integrate\n pattern: =e u ^ v 2 int\n require:\n - [sameAs, u, v]\n output: =e v ^\n explain: "e^{v} is its own integral."\n tags: [exp]\n\n - id: i-exponential\n name: Integral of a^x\n mode: integrate\n pattern: a u ^ v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, a, v]\n output: a v ^ a ln /\n explain: "∫ {a}^{v} d{v} = {a}^{v} / ln {a}."\n tags: [exp]\n\n - id: i-ln\n name: Integral of ln x\n mode: integrate\n pattern: u ln v 2 int\n require:\n - [sameAs, u, v]\n output: v v ln * v -\n explain: "By parts: ∫ ln {v} d{v} = {v} ln {v} - {v}."\n tags: [log]\n\n - { id: i-sin, name: Integral of sin, mode: integrate, pattern: u sin v 2 int, require: [[sameAs, u, v]], output: v cos neg, tags: [trig], explain: "The derivative of -cos {v} is sin {v}." }\n - { id: i-cos, name: Integral of cos, mode: integrate, pattern: u cos v 2 int, require: [[sameAs, u, v]], output: v sin, tags: [trig], explain: "The derivative of sin {v} is cos {v}." }\n - { id: i-tan, name: Integral of tan, mode: integrate, pattern: u tan v 2 int, require: [[sameAs, u, v]], output: v cos abs ln neg, tags: [trig], explain: "tan = sin/cos, and -ln|cos {v}| differentiates to it." }\n - { id: i-sec-squared, name: Integral of sec², mode: integrate, pattern: 1 u cos 2 ^ / v 2 int, require: [[sameAs, u, v]], output: v tan, tags: [trig], explain: "The derivative of tan {v} is 1/cos²{v}." }\n - { id: i-sec-squared-written, name: Integral of sec², mode: integrate, pattern: u sec 2 ^ v 2 int, require: [[sameAs, u, v]], output: v tan, tags: [trig], explain: "The derivative of tan {v} is sec²{v}." }\n - { id: i-csc-squared, name: Integral of csc², mode: integrate, pattern: 1 u sin 2 ^ / v 2 int, require: [[sameAs, u, v]], output: v cot neg, tags: [trig], explain: "The derivative of -cot {v} is 1/sin²{v}." }\n - { id: i-sin-squared, name: Integral of sin², mode: integrate, pattern: u sin 2 ^ v 2 int, require: [[sameAs, u, v]], output: v 2 / 2 v * sin 4 / -, tags: [trig], explain: "sin²{v} = (1 - cos 2{v})/2, which integrates term by term." }\n - { id: i-cos-squared, name: Integral of cos², mode: integrate, pattern: u cos 2 ^ v 2 int, require: [[sameAs, u, v]], output: v 2 / 2 v * sin 4 / +, tags: [trig], explain: "cos²{v} = (1 + cos 2{v})/2, which integrates term by term." }\n - { id: i-sinh, name: Integral of sinh, mode: integrate, pattern: u sinh v 2 int, require: [[sameAs, u, v]], output: v cosh, tags: [trig], explain: "The derivative of cosh {v} is sinh {v}." }\n - { id: i-cosh, name: Integral of cosh, mode: integrate, pattern: u cosh v 2 int, require: [[sameAs, u, v]], output: v sinh, tags: [trig], explain: "The derivative of sinh {v} is cosh {v}." }\n - { id: i-arctan, name: Integral of 1/(1 + x²), mode: integrate, pattern: 1 u 2 ^ 1 + / v 2 int, require: [[sameAs, u, v]], output: v arctan, tags: [trig], explain: "The derivative of arctan {v} is 1/(1 + {v}²)." }\n - { id: i-arcsin, name: Integral of 1/√(1 - x²), mode: integrate, pattern: 1 u 2 ^ neg 1 + sqrt / v 2 int, require: [[sameAs, u, v]], output: v arcsin, tags: [trig], explain: "The derivative of arcsin {v} is 1/√(1 - {v}²)." }\n','name: Values and identities\n\n# The CAS\'s simplify rules (mode: simplify). They see expressions in normal form\n# (src/cas/form.js), as drawn: x/2, 2x - 3, -x, √x is "x sqrt",\n# ∛x is "3 x root", π/6 is "=pi 6 /", 2π/3 is "2 =pi * 3 /", e^x is "=e x ^".\n#\n# - a word is a slot (u, v, n …); a fixed symbol is written =pi, =e\n# - a number is itself; "1 2 /" is ½\n# - arithmetic (2 + 3, x + x, √8 = 2√2) is done for you before and after every rule\n# - a rule for a sum or product of two parts also fires on any two parts of a longer one\n# - tags pick what a step list shows (steps: \'brief\' hides value, identity, tidy …)\n#\n# To change one: copy it into a file of your own with the same id and edit it;\n# to turn one off: give its id with enabled: false. createCAS({ rules: [yours] }).\n\nrules:\n # ---- logs and exponentials -------------------------------------------\n - id: ln-one\n name: Log of 1\n pattern: 1 ln\n output: "0"\n explain: "e^0 = 1, so ln 1 = 0."\n tags: [value]\n\n - id: ln-e\n name: Log of e\n pattern: =e ln\n output: "1"\n explain: "e^1 = e, so ln e = 1."\n tags: [value]\n\n - id: ln-exp\n name: Log undoes e to a power\n pattern: =e u ^ ln\n output: u\n explain: "ln and e^ undo each other: ln(e^{u}) = {u}."\n tags: [inverse]\n\n - id: exp-ln\n name: e to a power undoes the log\n pattern: =e u ln ^\n output: u\n explain: "e^ and ln undo each other: e^(ln {u}) = {u} (for {u} > 0)."\n tags: [inverse]\n\n - id: exp-multiple-ln\n name: A multiple of a log in a power\n pattern: =e n u ln * ^\n when:\n n: [isRational]\n output: u n ^\n explain: "e^({n} ln {u}) = (e^(ln {u}))^{n} = {result}."\n tags: [inverse]\n\n - id: log-same-base\n name: Log of its own base\n pattern: b b log\n output: "1"\n explain: "{b}^1 = {b}, so the log of {b} to base {b} is 1."\n tags: [value]\n\n - id: log-of-power\n name: Log undoes a power of its base\n pattern: b b u ^ log\n output: u\n explain: "log base {b} and {b}^ undo each other."\n tags: [inverse]\n\n - id: power-of-log\n name: A power undoes the log to its base\n pattern: b b u log ^\n output: u\n explain: "{b}^(log base {b} of {u}) = {u}."\n tags: [inverse]\n\n # ---- roots and absolute value --------------------------------------------\n - id: sqrt-of-square\n name: Square root of a square\n pattern: u 2 ^ sqrt\n output: u abs\n explain: "√({u}²) is the size of {u}, whatever its sign: |{u}|."\n tags: [identity]\n\n - id: abs-squared\n name: Absolute value squared\n pattern: u abs 2 ^\n output: u 2 ^\n explain: "Squaring removes the sign anyway: |{u}|² = {u}²."\n tags: [identity]\n\n - id: abs-of-abs\n name: Absolute value twice\n pattern: u abs abs\n output: u abs\n explain: "|{u}| is never negative, so its absolute value is itself."\n tags: [identity]\n\n - id: abs-positive\n name: Absolute value of a positive number\n pattern: u abs\n when:\n u: [isPositiveConstant]\n output: u\n explain: "{u} is positive, so |{u}| = {u}."\n tags: [value]\n\n - id: abs-negative\n name: Absolute value of a negative number\n pattern: u abs\n when:\n u: [isNegativeConstant]\n output: u neg\n explain: "{u} is negative, so |{u}| = -({u})."\n tags: [value]\n\n - id: abs-of-exp\n name: e to a power is positive\n pattern: =e u ^ abs\n output: =e u ^\n explain: "e to any power is positive, so the absolute value changes nothing."\n tags: [identity]\n\n # ---- trigonometry: signs and turns ---------------------------------------\n - id: sin-odd\n name: Sine of a negative angle\n pattern: u sin\n when:\n u: [hasMinusSign]\n output: u neg sin neg\n explain: "sin(-θ) = -sin θ."\n tags: [symmetry]\n\n - id: cos-even\n name: Cosine of a negative angle\n pattern: u cos\n when:\n u: [hasMinusSign]\n output: u neg cos\n explain: "cos(-θ) = cos θ."\n tags: [symmetry]\n\n - id: tan-odd\n name: Tangent of a negative angle\n pattern: u tan\n when:\n u: [hasMinusSign]\n output: u neg tan neg\n explain: "tan(-θ) = -tan θ."\n tags: [symmetry]\n\n - id: sin-full-turn\n name: A full turn\n pattern: u sin\n when:\n u: [[piMultipleAtLeast, 2]]\n output: u 2 =pi * - sin\n explain: "Turning a full 2π brings you back: sin({u}) = sin({u} - 2π)."\n tags: [symmetry]\n\n - id: cos-full-turn\n name: A full turn\n pattern: u cos\n when:\n u: [[piMultipleAtLeast, 2]]\n output: u 2 =pi * - cos\n explain: "Turning a full 2π brings you back: cos({u}) = cos({u} - 2π)."\n tags: [symmetry]\n\n - id: tan-half-turn\n name: Tangent repeats every π\n pattern: u tan\n when:\n u: [[piMultipleAtLeast, 1]]\n output: u =pi - tan\n explain: "tan repeats every π: tan({u}) = tan({u} - π)."\n tags: [symmetry]\n\n - id: sin-half-turn\n name: A half turn\n pattern: u sin\n when:\n u: [[piMultipleAbove, 1], [piMultipleBelow, 2]]\n output: u =pi - sin neg\n explain: "Half a turn flips the sign: sin({u}) = -sin({u} - π)."\n tags: [symmetry]\n\n - id: cos-half-turn\n name: A half turn\n pattern: u cos\n when:\n u: [[piMultipleAbove, 1], [piMultipleBelow, 2]]\n output: u =pi - cos neg\n explain: "Half a turn flips the sign: cos({u}) = -cos({u} - π)."\n tags: [symmetry]\n\n - id: sin-second-quarter\n name: The second quarter turn\n pattern: u sin\n when:\n u: [[piMultipleAbove, 1/2], [piMultipleAtMost, 1]]\n output: =pi u - sin\n explain: "sin({u}) = sin(π - {u})."\n tags: [symmetry]\n\n - id: cos-second-quarter\n name: The second quarter turn\n pattern: u cos\n when:\n u: [[piMultipleAbove, 1/2], [piMultipleAtMost, 1]]\n output: =pi u - cos neg\n explain: "cos({u}) = -cos(π - {u})."\n tags: [symmetry]\n\n - id: tan-second-quarter\n name: The second quarter turn\n pattern: u tan\n when:\n u: [[piMultipleAbove, 1/2], [piMultipleBelow, 1]]\n output: =pi u - tan neg\n explain: "tan({u}) = -tan(π - {u})."\n tags: [symmetry]\n\n # ---- trigonometry: the standard angles -------------------------------------\n - { id: sin-0, name: Sine of 0, pattern: 0 sin, output: "0", tags: [value], explain: "sin 0 = 0." }\n - { id: sin-pi-6, name: Sine of π/6, pattern: =pi 6 / sin, output: 1 2 /, tags: [value], explain: "sin(π/6) = 1/2." }\n - { id: sin-pi-4, name: Sine of π/4, pattern: =pi 4 / sin, output: 2 sqrt 2 /, tags: [value], explain: "sin(π/4) = √2/2." }\n - { id: sin-pi-3, name: Sine of π/3, pattern: =pi 3 / sin, output: 3 sqrt 2 /, tags: [value], explain: "sin(π/3) = √3/2." }\n - { id: sin-pi-2, name: Sine of π/2, pattern: =pi 2 / sin, output: "1", tags: [value], explain: "sin(π/2) = 1." }\n - { id: sin-pi, name: Sine of π, pattern: =pi sin, output: "0", tags: [value], explain: "sin π = 0." }\n - { id: cos-0, name: Cosine of 0, pattern: 0 cos, output: "1", tags: [value], explain: "cos 0 = 1." }\n - { id: cos-pi-6, name: Cosine of π/6, pattern: =pi 6 / cos, output: 3 sqrt 2 /, tags: [value], explain: "cos(π/6) = √3/2." }\n - { id: cos-pi-4, name: Cosine of π/4, pattern: =pi 4 / cos, output: 2 sqrt 2 /, tags: [value], explain: "cos(π/4) = √2/2." }\n - { id: cos-pi-3, name: Cosine of π/3, pattern: =pi 3 / cos, output: 1 2 /, tags: [value], explain: "cos(π/3) = 1/2." }\n - { id: cos-pi-2, name: Cosine of π/2, pattern: =pi 2 / cos, output: "0", tags: [value], explain: "cos(π/2) = 0." }\n - { id: cos-pi, name: Cosine of π, pattern: =pi cos, output: "-1", tags: [value], explain: "cos π = -1." }\n - { id: tan-0, name: Tangent of 0, pattern: 0 tan, output: "0", tags: [value], explain: "tan 0 = 0." }\n - { id: tan-pi-6, name: Tangent of π/6, pattern: =pi 6 / tan, output: 3 sqrt 3 /, tags: [value], explain: "tan(π/6) = √3/3." }\n - { id: tan-pi-4, name: Tangent of π/4, pattern: =pi 4 / tan, output: "1", tags: [value], explain: "tan(π/4) = 1." }\n - { id: tan-pi-3, name: Tangent of π/3, pattern: =pi 3 / tan, output: 3 sqrt, tags: [value], explain: "tan(π/3) = √3." }\n - { id: arcsin-0, name: Arcsine of 0, pattern: 0 arcsin, output: "0", tags: [value], explain: "sin 0 = 0, so arcsin 0 = 0." }\n - { id: arcsin-half, name: Arcsine of 1/2, pattern: 1 2 / arcsin, output: =pi 6 /, tags: [value], explain: "sin(π/6) = 1/2, so arcsin(1/2) = π/6." }\n - { id: arcsin-1, name: Arcsine of 1, pattern: 1 arcsin, output: =pi 2 /, tags: [value], explain: "sin(π/2) = 1, so arcsin 1 = π/2." }\n - { id: arccos-0, name: Arccosine of 0, pattern: 0 arccos, output: =pi 2 /, tags: [value], explain: "cos(π/2) = 0, so arccos 0 = π/2." }\n - { id: arccos-half, name: Arccosine of 1/2, pattern: 1 2 / arccos, output: =pi 3 /, tags: [value], explain: "cos(π/3) = 1/2, so arccos(1/2) = π/3." }\n - { id: arccos-1, name: Arccosine of 1, pattern: 1 arccos, output: "0", tags: [value], explain: "cos 0 = 1, so arccos 1 = 0." }\n - { id: arccos-minus-1, name: Arccosine of -1, pattern: -1 arccos, output: =pi, tags: [value], explain: "cos π = -1, so arccos(-1) = π." }\n - { id: arctan-0, name: Arctangent of 0, pattern: 0 arctan, output: "0", tags: [value], explain: "tan 0 = 0, so arctan 0 = 0." }\n - { id: arctan-1, name: Arctangent of 1, pattern: 1 arctan, output: =pi 4 /, tags: [value], explain: "tan(π/4) = 1, so arctan 1 = π/4." }\n - { id: sinh-0, name: sinh of 0, pattern: 0 sinh, output: "0", tags: [value], explain: "sinh 0 = 0." }\n - { id: cosh-0, name: cosh of 0, pattern: 0 cosh, output: "1", tags: [value], explain: "cosh 0 = 1." }\n - { id: tanh-0, name: tanh of 0, pattern: 0 tanh, output: "0", tags: [value], explain: "tanh 0 = 0." }\n\n - { id: arctan-sqrt3, name: Arctangent of √3, pattern: 3 sqrt arctan, output: =pi 3 /, tags: [value], explain: "tan(π/3) = √3, so arctan √3 = π/3." }\n - { id: arctan-sqrt3-over-3, name: Arctangent of √3/3, pattern: 3 sqrt 3 / arctan, output: =pi 6 /, tags: [value], explain: "tan(π/6) = √3/3, so arctan(√3/3) = π/6." }\n\n # atan2(y, x): the angle of the point (x, y), in (-π, π]\n - id: atan2-right\n name: The angle of a point to the right\n pattern: y x atan2\n when:\n x: [isPositiveConstant]\n output: y x / arctan\n explain: "For x > 0, atan2(y, x) = arctan(y/x)."\n tags: [value]\n - id: atan2-left-up\n name: The angle of a point to the left\n pattern: y x atan2\n when:\n x: [isNegativeConstant]\n y: [isPositiveConstant]\n output: y x / arctan =pi +\n explain: "For x < 0 and y > 0, atan2(y, x) = arctan(y/x) + π."\n tags: [value]\n - id: atan2-left-down\n name: The angle of a point to the left\n pattern: y x atan2\n when:\n x: [isNegativeConstant]\n y: [isNegativeConstant]\n output: y x / arctan =pi -\n explain: "For x < 0 and y < 0, atan2(y, x) = arctan(y/x) - π."\n tags: [value]\n - { id: atan2-negative-axis, name: The angle of a point on the negative axis, pattern: 0 x atan2, when: { x: [isNegativeConstant] }, output: =pi, tags: [value], explain: "A point on the negative x-axis is at angle π." }\n - { id: atan2-up, name: Straight up, pattern: y 0 atan2, when: { y: [isPositiveConstant] }, output: =pi 2 /, tags: [value], explain: "A point straight up is at angle π/2." }\n - { id: atan2-down, name: Straight down, pattern: y 0 atan2, when: { y: [isNegativeConstant] }, output: =pi 2 / neg, tags: [value], explain: "A point straight down is at angle -π/2." }\n\n # the odd inverses take the sign out; arccos(-u) = π - arccos u\n - id: arcsin-odd\n name: Arcsine of a negative\n pattern: u arcsin\n when:\n u: [hasMinusSign]\n output: u neg arcsin neg\n explain: "arcsin(-x) = -arcsin x."\n tags: [symmetry]\n\n - id: arctan-odd\n name: Arctangent of a negative\n pattern: u arctan\n when:\n u: [hasMinusSign]\n output: u neg arctan neg\n explain: "arctan(-x) = -arctan x."\n tags: [symmetry]\n\n - id: arccos-negative\n name: Arccosine of a negative\n pattern: u arccos\n when:\n u: [hasMinusSign]\n output: =pi u neg arccos -\n explain: "arccos(-x) = π - arccos x."\n tags: [symmetry]\n\n # ---- trigonometry: identities --------------------------------------------\n - id: pythagorean\n name: sin² + cos² = 1\n pattern: u sin 2 ^ u cos 2 ^ +\n commutative: true\n output: "1"\n explain: "sin²{u} + cos²{u} = 1 for every angle."\n tags: [identity]\n\n - id: pythagorean-multiple\n name: sin² + cos² = 1\n pattern: a u sin 2 ^ * a u cos 2 ^ * +\n commutative: true\n output: a\n explain: "{a}·sin²{u} + {a}·cos²{u} = {a}(sin²{u} + cos²{u}) = {a}."\n tags: [identity]\n\n - id: one-minus-sin-squared\n name: 1 - sin² = cos²\n pattern: u sin 2 ^ neg 1 +\n output: u cos 2 ^\n explain: "1 - sin²{u} = cos²{u}."\n tags: [identity]\n\n - id: one-minus-cos-squared\n name: 1 - cos² = sin²\n pattern: u cos 2 ^ neg 1 +\n output: u sin 2 ^\n explain: "1 - cos²{u} = sin²{u}."\n tags: [identity]\n\n - id: sin-over-cos\n name: sin/cos is tan\n pattern: u sin u cos /\n output: u tan\n explain: "sin {u} / cos {u} = tan {u}."\n tags: [identity]\n\n - id: cos-over-sin\n name: cos/sin is cot\n pattern: u cos u sin /\n output: u cot\n explain: "cos {u} / sin {u} = cot {u}."\n tags: [identity]\n\n - id: sin-arcsin\n name: sin undoes arcsin\n pattern: u arcsin sin\n output: u\n explain: "sin(arcsin {u}) = {u}."\n tags: [inverse]\n\n - id: cos-arccos\n name: cos undoes arccos\n pattern: u arccos cos\n output: u\n explain: "cos(arccos {u}) = {u}."\n tags: [inverse]\n\n - id: tan-arctan\n name: tan undoes arctan\n pattern: u arctan tan\n output: u\n explain: "tan(arctan {u}) = {u}."\n tags: [inverse]\n\n - id: cosh-squared-minus-sinh-squared\n name: cosh² - sinh² = 1\n pattern: u cosh 2 ^ u sinh 2 ^ -\n output: "1"\n explain: "cosh²{u} - sinh²{u} = 1."\n tags: [identity]\n\n # ---- logs: opt-in rewrites (run with cas.rewrite(x, \'expand-log\') or \'combine-log\') ----\n - id: ln-product\n name: Log of a product\n mode: expand-log\n pattern: a b * ln\n output: a ln b ln +\n explain: "ln({a}·{b}) = ln {a} + ln {b} (for positive {a}, {b})."\n tags: [log]\n\n - id: ln-quotient\n name: Log of a quotient\n mode: expand-log\n pattern: a b / ln\n output: a ln b ln -\n explain: "ln({a}/{b}) = ln {a} - ln {b} (for positive {a}, {b})."\n tags: [log]\n\n - id: ln-power\n name: Log of a power\n mode: expand-log\n pattern: a n ^ ln\n output: n a ln *\n explain: "ln({a}^{n}) = {n}·ln {a} (for positive {a})."\n tags: [log]\n\n - id: ln-root\n name: Log of a square root\n mode: expand-log\n pattern: a sqrt ln\n output: a ln 2 /\n explain: "ln √{a} = ½ ln {a}."\n tags: [log]\n\n - id: ln-sum-combine\n name: Sum of logs\n mode: combine-log\n pattern: a ln b ln +\n commutative: true\n output: a b * ln\n explain: "ln {a} + ln {b} = ln({a}·{b})."\n tags: [log]\n\n - id: ln-difference-combine\n name: Difference of logs\n mode: combine-log\n pattern: a ln b ln -\n output: a b / ln\n explain: "ln {a} - ln {b} = ln({a}/{b})."\n tags: [log]\n\n - id: ln-multiple-combine\n name: A multiple of a log\n mode: combine-log\n pattern: n a ln *\n when:\n n: [isRational]\n output: a n ^ ln\n explain: "{n}·ln {a} = ln({a}^{n})."\n tags: [log]\n','name: Solving by undoing\n\n# mode: isolate. Each rule undoes the outermost function on the side with the\n# unknown: ln u = r → u = e^r. The predicates hasVariable and freeOfVariable mean\n# "mentions / doesn\'t mention the unknown being solved for".\n#\n# The CAS does the rest itself: it moves terms without the unknown to the other\n# side, divides by a coefficient, and when the unknown appears in several places\n# it uses the polynomial methods (factoring, the quadratic formula) or splits a\n# product equal to 0. Every answer is checked in the original equation, so a\n# rule may give extra candidates (squaring both sides does): the wrong ones are\n# dropped, with a step saying so.\n#\n# An output can give several answers: `pm` (±) splits into two, and so does\n# `|` (or): "u r arcsin = u =pi r arcsin - = |".\n\nrules:\n - id: iso-swap\n name: Unknown on the left\n mode: isolate\n pattern: l r =\n when:\n l: [freeOfVariable]\n r: [hasVariable]\n output: r l =\n priority: 20\n explain: "Swap the sides so the unknown is on the left."\n tags: [tidy]\n\n - id: iso-ln\n name: Undo the log\n mode: isolate\n pattern: u ln r =\n when:\n u: [hasVariable]\n output: u =e r ^ =\n explain: "Raise e to each side: e^(ln {u}) = {u}."\n tags: [inverse]\n\n - id: iso-log\n name: Undo the log\n mode: isolate\n pattern: b u log r =\n when:\n u: [hasVariable]\n b: [freeOfVariable]\n output: u b r ^ =\n explain: "Raise {b} to each side: {b}^(log base {b} of {u}) = {u}."\n tags: [inverse]\n\n - id: iso-exp\n name: Undo e to a power\n mode: isolate\n pattern: =e u ^ r =\n when:\n u: [hasVariable]\n output: u r ln =\n explain: "Take ln of each side: ln(e^{u}) = {u}."\n tags: [inverse]\n\n - id: iso-exponential\n name: Undo a power of a number\n mode: isolate\n pattern: b u ^ r =\n when:\n u: [hasVariable]\n b: [freeOfVariable]\n output: u b r log =\n explain: "Take the log to base {b} of each side."\n tags: [inverse]\n\n - id: iso-square\n name: Undo the square\n mode: isolate\n pattern: u 2 ^ r =\n when:\n u: [hasVariable]\n output: u r sqrt pm =\n priority: 1\n explain: "Take the square root of each side; {u} can be positive or negative."\n tags: [inverse]\n\n - id: iso-even-power\n name: Undo an even power\n mode: isolate\n pattern: u n ^ r =\n when:\n u: [hasVariable]\n n: [isEvenWhole]\n output: u r 1 n / ^ pm =\n explain: "Take the root of each side (the {n}th root); {u} can be positive or negative."\n tags: [inverse]\n\n - id: iso-odd-power\n name: Undo an odd power\n mode: isolate\n pattern: u n ^ r =\n when:\n u: [hasVariable]\n n: [isOddWhole]\n output: u r 1 n / ^ =\n explain: "Take the root of each side (the {n}th root)."\n tags: [inverse]\n\n - id: iso-fractional-power\n name: Undo a power\n mode: isolate\n pattern: u n ^ r =\n when:\n u: [hasVariable]\n n: [isRational]\n output: u r 1 n / ^ =\n priority: -1\n explain: "Raise each side to the power 1/{n}."\n tags: [inverse]\n\n - id: iso-sqrt\n name: Undo the square root\n mode: isolate\n pattern: u sqrt r =\n when:\n u: [hasVariable]\n output: u r 2 ^ =\n explain: "Square each side (this can add answers, so each one is checked at the end)."\n tags: [inverse]\n\n - id: iso-root\n name: Undo the root\n mode: isolate\n pattern: n u root r =\n when:\n u: [hasVariable]\n n: [freeOfVariable]\n output: u r n ^ =\n explain: "Raise each side to the power {n}."\n tags: [inverse]\n\n - id: iso-reciprocal\n name: Undo the fraction\n mode: isolate\n pattern: c u / r =\n when:\n u: [hasVariable]\n c: [freeOfVariable]\n output: u c r / =\n explain: "{c}/{u} = {r}, so {u} = {c}/{r}."\n tags: [inverse]\n\n - id: iso-abs\n name: Undo the absolute value\n mode: isolate\n pattern: u abs r =\n when:\n u: [hasVariable]\n output: u r pm =\n explain: "|{u}| = {r} means {u} is {r} or -{r}."\n tags: [inverse]\n\n - id: iso-sin\n name: Undo the sine\n mode: isolate\n pattern: u sin r =\n when:\n u: [hasVariable]\n output: u r arcsin = u =pi r arcsin - = |\n explain: "Two angles in a turn have sine {r}: arcsin {r} and π - arcsin {r} (add any whole number of turns, 2πk, for the rest)."\n tags: [inverse, trig]\n\n - id: iso-cos\n name: Undo the cosine\n mode: isolate\n pattern: u cos r =\n when:\n u: [hasVariable]\n output: u r arccos pm =\n explain: "Two angles in a turn have cosine {r}: ±arccos {r} (add 2πk for the rest)."\n tags: [inverse, trig]\n\n - id: iso-tan\n name: Undo the tangent\n mode: isolate\n pattern: u tan r =\n when:\n u: [hasVariable]\n output: u r arctan =\n explain: "Take arctan of each side (add πk for the rest)."\n tags: [inverse, trig]\n\n - { id: iso-arcsin, name: Undo arcsin, mode: isolate, pattern: u arcsin r =, when: { u: [hasVariable] }, output: u r sin =, tags: [inverse], explain: "Take sin of each side." }\n - { id: iso-arccos, name: Undo arccos, mode: isolate, pattern: u arccos r =, when: { u: [hasVariable] }, output: u r cos =, tags: [inverse], explain: "Take cos of each side." }\n - { id: iso-arctan, name: Undo arctan, mode: isolate, pattern: u arctan r =, when: { u: [hasVariable] }, output: u r tan =, tags: [inverse], explain: "Take tan of each side." }\n - { id: iso-sinh, name: Undo sinh, mode: isolate, pattern: u sinh r =, when: { u: [hasVariable] }, output: u r arcsinh =, tags: [inverse], explain: "Take arcsinh of each side." }\n - { id: iso-tanh, name: Undo tanh, mode: isolate, pattern: u tanh r =, when: { u: [hasVariable] }, output: u r arctanh =, tags: [inverse], explain: "Take arctanh of each side." }\n - { id: iso-cosh, name: Undo cosh, mode: isolate, pattern: u cosh r =, when: { u: [hasVariable] }, output: u r arccosh pm =, tags: [inverse], explain: "Two numbers have cosh {r}: ±arccosh {r}." }\n - { id: iso-arcsinh, name: Undo arcsinh, mode: isolate, pattern: u arcsinh r =, when: { u: [hasVariable] }, output: u r sinh =, tags: [inverse], explain: "Take sinh of each side." }\n - { id: iso-arccosh, name: Undo arccosh, mode: isolate, pattern: u arccosh r =, when: { u: [hasVariable] }, output: u r cosh =, tags: [inverse], explain: "Take cosh of each side." }\n - { id: iso-arctanh, name: Undo arctanh, mode: isolate, pattern: u arctanh r =, when: { u: [hasVariable] }, output: u r tanh =, tags: [inverse], explain: "Take tanh of each side." }\n'],qu=['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'],Mu={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: {cancelled}.","solve.move":"Keep the terms with {v} on the left and move the others to the right.","solve.divide":"Divide both sides by {by}.","solve.multiply":"Multiply both sides by {by}.","solve.one-side":"Move everything to one side, so the equation reads … = 0.","solve.factor":"Factor the left side.","solve.zero-product":"A product is 0 exactly when one of its factors is 0.","solve.split":"There are two cases; solve each.","solve.quadratic":"The quadratic formula with a = {a}, b = {b}, c = {c}: {v} = (-b ± √(b² - 4ac)) / 2a, and b² - 4ac = {D}.","solve.no-real":"b² - 4ac = {D} is negative, so there are no real solutions.","solve.quadratic-complex":"The quadratic formula with a = {a}, b = {b}, c = {c}: {v} = (-b ± √(b² - 4ac)) / 2a. b² - 4ac = {D} is negative, so its square root is imaginary: √({D}) = {root}.","solve.roots":"{v}^{n} = {r} has {n} solutions, spaced evenly round a circle: |{r}|^(1/{n})·(cos θ + i sin θ), with θ = (arg {r} + 2πk)/{n} for k = 0 … {last}.","solve.clear-denominator":"Multiply both sides by {den} (an answer that makes it 0 is not allowed).","solve.substitute":"Write {u} for {kernel}: this is a polynomial in {u}.","solve.reject":"{value} is not a solution: {reason}.","solve.always":"This is true for every {v}.","solve.never":"This is never true, so there is no solution.","solve.unsolved":"There is no exact method here for solving for {v}; try { approximate: true }.","solve.numeric":"Found {count} solution(s) numerically.","system.eliminate":"Use one equation to remove {v} from the others.","integrate.expand":"Multiply out, then integrate term by term.","integrate.substitute":"Let {u} = {inside}, so d{u} = {a} d{v}.","integrate.back":"Put {inside} back for {u}.","integrate.parts":"By parts with u = {u} and dv = {dv} d{v}: ∫ u dv = u·v - ∫ v du, where v = {V} and du = {du} d{v}.","integrate.constant":"The number {c} comes out of the integral.","integrate.divide":"The top has at least the degree of the bottom: divide first.","integrate.partial-fractions":"Split the fraction into simple fractions, one for each factor below.","integrate.evaluate":"Evaluate {F} at {b} and at {a}, and subtract.",substitute:"Put in the values."},Nu=["normal","rewrite","simplify","expand","factor","cancel","diff","differentiate","integrate","solve","solveSystem","substitute","approximate","equivalent"];class Su{constructor(e,t,n,r,s){this.set=e,this.messages=t,this.format=n,this.read=r,this.complex=s;for(const e of Nu){const t=Su.prototype[e];this[e]=(...e)=>Fi(s,()=>t.apply(this,e))}}node(e){if(e&&"object"==typeof e&&!Array.isArray(e)&&e.type)return e;if(Array.isArray(e))return xi(e);if("string"!=typeof e)throw new Ai("expected an expression");if(this.read){const t=this.read(e);return Array.isArray(t)?xi(t):"string"==typeof t?wi(t):t}return wi(e)}step(e,t,n,r,s,i={}){return function(e,t,n,r,s,i,o,a,l=[]){const u=(i??"").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:r.s,to:s.s,path:l,before:r.s,after:s.s,explanation:u}}(e,t,n,r,s,this.messages[e]??"",i,this.format)}result(e,t,n,r={}){let s=e;if(n.approximate&&s){s=rl(s,{digits:"number"==typeof n.approximate?n.approximate:15})}return{result:s,text:s?this.format(s):"",steps:wl(t,yl(n.steps)),...r}}variable(e,t){if(t)return t;const n=[..._o(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 Mo(this.node(e))}rewrite(e,t,n={}){const r=this.node(e),s=this.set.view(t);if(!s.size)throw new Ai(`no rules in mode "${t}" (modes: ${this.set.modes().join(", ")})`);const i=gl(r,s,{format:this.format,order:n.order,variable:n.variable});return this.result(i.node,[...this.tidyStep(r,Mo(r)),...i.steps],n)}simplify(e,t={}){const n=this.node(e),r=[...this.tidyStep(n,Mo(n))],s=gl(n,this.set.view("simplify"),{format:this.format});r.push(...s.steps);let i=s.node,o=null;const a=qo(i),l=[],u=0===_o(i).size,c=u?null:Dl(a);c&&l.push({node:Fl(c),id:"simplify.cancel",name:"Cancel"});const h=gl(Oo(kl(a)),this.set.view("simplify"),{format:this.format});l.push({node:h.node,id:"simplify.expand",name:"Multiply out"}),"add"!==a.k||u||l.push({node:Fl(jl(a)),id:"simplify.factor",name:"Factor"});for(const e of l)ki(e.node)<ki(i)&&(o=this.step(e.id,e.name,["shorter"],i,e.node),i=e.node);return o&&r.push(o),this.result(i,r,t)}expand(e,t={}){const n=this.node(e),r=Oo(kl(qo(n)));return this.result(r,n.s===r.s?[]:[this.step("expand","Multiply out",["expand"],n,r)],t)}factor(e,t={}){const n=this.node(e),r=jl(qo(n)),s=Fl(r),i=[],o=r.notes.find(e=>"factor.common"===e.id);return s.s!==Mo(n).s&&i.push(this.step(o?"factor.common":"factor","Factor",["factor"],n,s,o?{common:Oo(o.values.common)}:{})),this.result(s,i,t)}cancel(e,t={}){const n=this.node(e),r=qo(n),s=Dl(r);if(!s)return this.result(Mo(n),this.tidyStep(n,Mo(n)),t);const i=Fl(s),o=Pl(r),a=bi("/",[Oo(o.num),Oo(o.den)]),l=[];return"/"===n.op&&a.s===Mo(n).s||l.push(this.step("together","One fraction",["together"],n,a)),i.s!==a.s&&l.push(this.step("cancel","Cancel",["cancel"],a,i,{cancelled:s.cancelled.length?s.cancelled.map(e=>this.format(Oo(e))).join(", "):"numbers"})),this.result(i,l,t)}diff(e,t,n={}){const r=this.node(e),s=this.variable(r,t);let i=r;const o=[];for(let e=0;e<(n.order??1);e++){const e=gl(bi("der",[i,fi(s)]),this.set.view("differentiate"),{format:this.format,order:"pre"}),t=gl(e.node,this.set.view("simplify"),{format:this.format});o.push(...e.steps,...t.steps),i=t.node}return this.result(i,o,n,{variable:s})}differentiate(e,t){const n=gl(bi("der",[e,fi(t)]),this.set.view("differentiate"),{format:this.format,order:"pre"});return gl(n.node,this.set.view("simplify"),{format:this.format}).node}integrate(e,t,n={}){let r=this.node(e);const s=e=>void 0===e?null:this.node("number"==typeof e?String(e):e);let i=s(n.from),o=s(n.to);if(yi(r)&&"int"===r.op){const[e,n,s,a]=r.args;t=n.token,s&&a&&(i=s,o=a),r=e}const a=this.variable(r,t),l=cu(this,r,a),u=gl(l.node,this.set.view("simplify"),{format:this.format}),c=[...l.steps,...u.steps];if(i&&o){const e=mu(this,u.node,a,i,o,r);c.push(e.step);const t=gl(e.value,this.set.view("simplify"),{format:this.format});return c.push(...t.steps),this.result(t.node,c,n,{antiderivative:u.node,variable:a})}let h=u.node;return n.constant&&(h=bi("+",[h,fi(String(n.constant))])),this.result(h,c,n,{variable:a})}solve(e,t,n={}){const r=this.node(e),s=this.variable(r,t),i=Hl(this,r,s,n);let o=i.solutions;if(n.approximate){const e="number"==typeof n.approximate?n.approximate:15;o=o.map(t=>rl(t,{digits:e}))}const a=o.map(e=>bi("=",[fi(s),e])),l=a.length?a.reduce((e,t)=>e?bi("|",[e,t]):t,null):null;return{solutions:o,result:l,variable:s,text:i.always?`true for every ${s}`:l?this.format(l):i.unsolved.length?`no exact solution found for ${s}`:"no solution",unsolved:i.unsolved.filter(e=>!e.always),always:i.always,steps:wl(i.steps,yl(n.steps))}}solveSystem(e,t,n={}){const r=e.map(e=>this.node(e)),s=t??[...new Set(r.flatMap(e=>[..._o(e)]))].sort(),i=function(e,t,n){const r=[],s=t.map(t=>{const r=Vl(t)?so([qo(t.args[0]),vo(qo(t.args[1]))]):qo(t),s=n.map(t=>{const n=Ml(r,t);if(!n||Math.max(0,...n.keys())>1)throw new Ai(`not linear in ${t}`);const s=n.get(1)??Di(Ti.ZERO);if(!Hi(s))throw new Ai(`the coefficient of ${t} must be a number (it is ${e.format(Oo(s))})`);return s.q});let i=r;for(let e=0;e<n.length;e++)i=so([i,oo([Di(s[e].neg()),qo(fi(n[e]))])]);for(const e of n)if(Nl(i,e))throw new Ai(`not linear in ${e}`);return{coeffs:s,rhs:vo(i)}}),i=()=>s.map(e=>Wl(Oo(so(e.coeffs.map((e,t)=>oo([Di(e),qo(fi(n[t]))])))),Oo(e.rhs))).reduce((e,t)=>e?bi("&",[e,t]):t,null);let o=0;const a=[];for(let t=0;t<n.length&&o<s.length;t++){const l=s.findIndex((e,n)=>n>=o&&!e.coeffs[t].isZero);if(l<0)continue;[s[o],s[l]]=[s[l],s[o]];const u=i(),c=s[o],h=c.coeffs[t];c.coeffs=c.coeffs.map(e=>e.div(h)),c.rhs=oo([Di(h.inv()),c.rhs]);for(let e=0;e<s.length;e++){if(e===o||s[e].coeffs[t].isZero)continue;const n=s[e].coeffs[t];s[e].coeffs=s[e].coeffs.map((e,t)=>e.sub(n.mul(c.coeffs[t]))),s[e].rhs=so([s[e].rhs,oo([Di(n.neg()),c.rhs])])}r.push(e.step("system.eliminate","Eliminate",["eliminate"],u,i(),{v:fi(n[t])})),a.push(t),o++}for(const e of s.slice(o))if(!Hi(e.rhs)||!e.rhs.q.isZero)return{solution:null,steps:r,status:"none"};if(a.length<n.length)return{solution:null,steps:r,status:"many"};const l=new Map;return a.forEach((e,t)=>l.set(n[e],Oo(s[t].rhs))),{solution:l,steps:r,status:"one"}}(this,r,s),o=i.solution?Object.fromEntries([...i.solution].map(([e,t])=>[e,t])):null,a="one"===i.status?s.map(e=>`${e} = ${this.format(o[e])}`).join(", "):"none"===i.status?"no solution":"infinitely many solutions";return{solution:o,status:i.status,text:a,steps:wl(i.steps,yl(n.steps))}}substitute(e,t,n={}){const r=this.node(e);let s=r;for(const[e,n]of Object.entries(t))s=Jl(s,e,"number"==typeof n?this.node(String(n)):this.node(n));const i=this.simplify(s,n),o=[this.step("substitute","Substitute",["substitute"],r,s)];return{...i,steps:[...wl(o,yl(n.steps)),...i.steps]}}defined(e){const t=this.set.view("define");return t.size?gl(e,t,{format:this.format}).node:e}approximate(e,t={}){const n=this.defined(this.node(e));if(_o(n).size&&!t.scope){const e=rl(Mo(n),t);return{result:e,text:this.format(e),number:null,exact:!1}}const r=el(n,t);return{result:r.node,text:r.text,number:r.number,re:r.re,im:r.im,exact:r.exact}}equivalent(e,t){const n=this.node(e),r=this.node(t),s=this.defined(bi("-",[n,r])),i=this.simplify(s,{steps:!1}).result;if("num"===i.type&&"0"===i.token)return{equal:!0,how:"exact"};const o=[..._o(s)];if(!o.length)try{return{equal:Math.abs(el(s,{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=el(s,{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 Au(e={}){const t=!1===e.defaults?[]:[...ku,...e.complex?qu:[]],{specs:n,messages:r}=function(e){cl();const t=[],n={};for(const r of e){const e="string"==typeof r?ha(r):r,s=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");si(t.symbol)||ti({symbol:String(t.symbol),arity:"any"===t.arity?Ys:Number(t.arity),label:t.label})}Object.assign(n,(Array.isArray(e)?null:e?.messages)??{});for(const e of s)t.push(e)}return{specs:t,messages:n}}([...t,...e.rules??[]]),s=Fi(e.complex,()=>hl(n));return new Su(s,{...Mu,...r},e.format??bu,e.read??null,Boolean(e.complex))}function Ou(e){const t=e=>function(e){if(e.length>1e6)throw new Error("The output would be too long");return e}("op"===e.type?function(e,t){const{op:n,args:r}=e,[s,i]=r,a=(e,r)=>c(n,_(e),r)?`(${t(e)})`:t(e),l=()=>r.map(t).join(", "),u=e=>j(n,e)?`(${t(e)})`:t(e);if("*"===n&&I(e))return"-"+t(i);if("+"===n&&I(i))return`${a(s,"left")} ${t(i)}`;if("-"===n&&I(i))return`${a(s,"left")} + ${t(i).slice(1)}`;if("^"===n){const e=a(s,"left");return`${e.startsWith("-")?`(${e})`:e}^${a(i,"right")}`}if(Eu[n])return`${a(s,"left")} ${Eu[n]} ${a(i,"right")}`;if(Iu[n])return Iu[n][0]+l()+Iu[n][1];if(o(n))return`${D(n)}(${l()})`;switch(n){case"neg":return"-"+u(s);case"pmod":return`${t(s)} (mod ${t(i)})`;case"pm":return"±"+u(s);case"!":return u(s)+"!";case"\\not":return"¬"+u(s);case"sqrt":return`√(${t(s)})`;case"root":{const e="number"===s.type?{3:"∛",4:"∜"}[s.value]:null;return e?`${e}(${t(i)})`:`root(${t(s)}, ${t(i)})`}case"abs":return`|${t(s)}|`;case"floor":return`⌊${t(s)}⌋`;case"ceil":return`⌈${t(s)}⌉`;case"log":return`log_${"op"===s.type?`(${t(s)})`:t(s)}(${t(i)})`;case"loglog":return`ln(ln(${t(s)}))`;case"logloglog":return`ln(ln(ln(${t(s)})))`;case"perm":return`perm(${t(s)}, ${t(i)})`;case"comb":return`comb(${t(s)}, ${t(i)})`;case"_":return`${t(s)}_${t(i)}`;case"?:":return`${t(s)} ? ${t(i)} : ${t(r[2])}`;case"sum":return r.map(t).join(" + ");case"prod":return r.map(t).join(" * ");case"der":{const{n:n,body:r,by:s,variable:i}=W(e),o=n>1?`^${n}`:"";return i?`d${o}${t(r)}/d${t(s)}${o}`:`d${o}/d${t(s)}${o}(${t(r)})`}case"int":return function(e,t){const[n,r,s,i]=e,o=e.length>=2&&P(r)?t(r):A(n)||"x",a=`${t(n)} d${o}`;switch(e.length){case 1:return`∫ ${a}`;case 2:return P(r)?`∫ ${a}`:`∫[${t(r)}] ${a}`;case 3:return P(r)?`∫[${t(s)}] ${a}`:`∫[${t(r)}, ${t(s)}] ${a}`;default:return`∫[${t(s)}, ${t(i)}] ${a}`}}(r,t);case"lim":return function(e,t){const[n,r,s,i]=e;switch(e.length){case 1:return`lim ${t(n)}`;case 2:return`lim[${t(r)}] ${t(n)}`;case 3:return`lim[${t(r)}→${t(s)}] ${t(n)}`;default:{const e=E(i).toLowerCase().startsWith("r")?"⁺":"⁻";return`lim[${t(r)}→${t(s)}${e}] ${t(n)}`}}}(r,t);case"\\sumidx":return _u("∑",r,t);case"\\prodidx":return _u("∏",r,t)}return`${n}(${l()})`}(e,t):function(e){const t=e.value;return"symbol"!==e.type?t:O[t]?O[t]:"\\+"===t||"\\-"===t?t[1]:t}(e));return t(e)}const Eu={"+":"+","-":"-","*":"*","/":"/","^":"^",mod:"mod","±":"±","=":"=","===":"===","≠":"≠","≠=":"≠","<":"<",">":">","≤":"≤","≥":"≥","∈":"∈","∉":"∉","→":"→","≈":"≈","∪":"∪","∩":"∩","≡":"≡","&":"∧","|":"∨","\\xor":"⊕","\\nand":"↑","\\nor":"↓"},Iu={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]};function _u(e,t,n){const[r,s,i]=t,o="∑"===e?"sum":"prod";return 3===t.length&&"op"===s.type&&"="===s.op?`${o}(${n(r)}, ${n(s)}, ${n(i)})`:2===t.length&&"op"===s.type&&"∈"===s.op?`${o}(${n(r)}, ${n(s)})`:1===t.length?`${e} ${n(r)}`:2===t.length?`${e}[${n(s)}] ${n(r)}`:`${e}[${n(s)}, ${n(i)}] ${n(r)}`}for(const e of[Eu,Iu])Object.setPrototypeOf(e,null);const Tu=new Map,ju={re:"Re",im:"Im",conj:"overline"},Cu=["Re","Im","re","im","conj","arg"];function zu(e){const t=[],n=e=>{"op"===e.type?(e.args.forEach(n),a(e.op)?(-1===a(e.op).arity&&t.push(String(e.args.length)),t.push(e.op)):t.push(String(e.args.length),`\\:${ju[e.op]??e.op}`)):t.push(e.token)};return n(e),t}function Lu(e={}){const t=e.rules||e.names?null:e.complex?"complex":"default";if(t&&Tu.has(t))return Tu.get(t);const n=[...e.names??[],...e.complex?Cu:[]],r=Au({...e,read:e=>function(e,t={}){const n=Ht(e,t);if(t.keepIntermediateSteps)return n;if(!n.error)return n.postfix;if(t.allowUnvalidated&&n.rawPostfix)return n.rawPostfix;throw new Error(`Failed to parse expression "${Gt(e)}": ${n.error}`)}(e,n.length?{names:n}:{}),format:bu});return t&&Tu.set(t,r),r}const Ru=new Set(["simplify","expand","factor","cancel","diff","integrate","solve","approx"]);const Zu=e=>String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");var Fu='/*\n * Inline Math stylesheet. Everything is under .mv; colours 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 colour\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 { 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-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-hook { display: inline-block; overflow: visible; margin-left: 0.05em; }\n.mv-radicand { display: inline-block; border-top: 0.06em solid currentColor; padding: 0.1em 0.1em 0 0.06em; }\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\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; border-top: 0.06em solid currentColor; padding-top: 0.08em; }\n.mv-underline { display: inline-block; border-bottom: 0.06em solid currentColor; padding-bottom: 0.06em; }\n.mv-cancel { display: inline-block; background: linear-gradient(to top right, transparent calc(50% - 0.04em), currentColor calc(50% - 0.03em), currentColor calc(50% + 0.03em), transparent calc(50% + 0.04em)); }\n.mv-accent { display: inline-block; position: relative; padding-top: 0.3em; }\n.mv-accent-mark { position: absolute; top: 0; left: 0; right: 0; text-align: center; font-size: 0.7em; line-height: 0.6; }\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.mv-clickable .mv-n { cursor: pointer; }\n.mv-clickable .mv-n:hover { outline: 1px dashed rgba(0, 0, 0, 0.25); }\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 maths (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';const Bu=Fu;if("undefined"!=typeof document&&!document.getElementById("inlinemath-css")){const e=document.createElement("style");e.id="inlinemath-css",e.textContent=Fu,document.head.append(e)}return e.CSS=Bu,e.DEFAULTS=ms,e.PATHS=Qr,e.View=Cs,e.casBlocks=function(e={}){const t=e.cas??Lu(),n=(e,r)=>{let s;try{s=t.read(e)}catch{return Fr(e,r)}const i=s[s.length-1],o=i?.startsWith("\\:")?i.slice(2):null,a=o&&Ru.has(o);if(!a&&!("der"===i||"int"===i))return Fr(e,r);const l=t.node(s),u=a?l.args:[l],c=e=>e?e.s:void 0;let h;try{switch(a?o:"der"===i?"derivative":"antiderivative"){case"simplify":h=t.simplify(u[0]);break;case"expand":h=t.expand(u[0]);break;case"factor":h=t.factor(u[0]);break;case"cancel":h=t.cancel(u[0]);break;case"diff":h=t.diff(u[0],c(u[1]),{order:u[2]?Number(u[2].s):1});break;case"integrate":h=t.integrate(u[0],c(u[1]),u[3]?{from:u[2].s,to:u[3].s}:{});break;case"solve":h=t.solve(u[0],c(u[1]));break;case"approx":h=t.approximate(u[0],{digits:u[1]?Number(u[1].s):15});break;case"derivative":h=t.diff(l.args[0],l.args[1].s);break;default:h=t.integrate(l)}}catch(t){return`(${e})`}if(n.last=h,!h.result)return`"${h.text}"`;const p=(f=zu(h.result),Jt(f)?"":Ou(Qt(f)));var f;return/^-?\d+(\.\d+)?$/.test(p)?p:`(${p})`};return n},e.extractMath=Ls,e.layout=ys,e.markdownToHTML=Qs,e.mathCAS=Lu,e.nodeAt=Ss,e.numberTree=Os,e.pathOf=As,e.render=function(e,t,n={}){return new Cs(e,t,n)},e.renderMarkdown=Xs,e.renderMarkdownInto=function(e,t,n={}){return e.innerHTML=Qs(t,n),e},e.select=Ms,e.signature=qs,e.stepsHTML=function(e,t={}){return`<ol class="mv-steps">${e.map(e=>{const n=js(zu(wi(e.from)),{...t,highlight:e.path&&e.path.length?{path:e.path}:void 0}),r=e.to===e.from?"":`<span class="mv-step-arrow" aria-label="becomes">⟶</span>${js(zu(wi(e.to)),t)}`,s=e.explanation?`<p class="mv-step-why">${Zu(e.explanation)}</p>`:"";return`<li class="mv-step" data-rule="${Zu(e.id)}"><span class="mv-step-name">${Zu(e.name)}</span><div class="mv-step-maths">${n}${r}</div>${s}</li>`}).join("")}</ol>`},e.toHTML=js,e.tokensOf=zu,e.treeOf=Ts,e}({});
|