@mathzetta/inlinemath 0.2.0 → 0.3.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.
Files changed (57) hide show
  1. package/README.md +37 -33
  2. package/dist/cas.external.js +2 -2
  3. package/dist/cas.js +2 -2
  4. package/dist/chunks/calculate-BGMEvf3f.js +2 -0
  5. package/dist/chunks/draw-q86mDDWm.js +2 -0
  6. package/dist/chunks/edit-CTMRUElt.js +2 -0
  7. package/dist/chunks/edit-D2RO7fg0.js +2 -0
  8. package/dist/chunks/html-1wCO6EpZ.js +2 -0
  9. package/dist/chunks/html-D5QiXGXD.js +2 -0
  10. package/dist/chunks/lite-Bo8THzyq.js +2 -0
  11. package/dist/fonts/README-inlinemath-greek.txt +15 -0
  12. package/dist/fonts/fonts.css +19 -1
  13. package/dist/fonts/inlinemath-greek-italic.woff2 +0 -0
  14. package/dist/fonts/inlinemath-greek-regular.woff2 +0 -0
  15. package/dist/inlinemath-cas.external.global.min.js +2 -2
  16. package/dist/inlinemath-cas.global.min.js +2 -2
  17. package/dist/inlinemath-lite-calc.global.min.js +2 -2
  18. package/dist/inlinemath-lite.external.global.min.js +2 -2
  19. package/dist/inlinemath-lite.global.min.js +2 -2
  20. package/dist/inlinemath.css +17 -7
  21. package/dist/inlinemath.external.global.min.js +2 -2
  22. package/dist/inlinemath.external.js +2 -2
  23. package/dist/inlinemath.global.min.js +2 -2
  24. package/dist/inlinemath.js +2 -2
  25. package/dist/lite-calc.js +2 -2
  26. package/dist/lite.external.js +2 -2
  27. package/dist/lite.js +2 -2
  28. package/dist/markdown.external.js +2 -2
  29. package/dist/markdown.js +2 -2
  30. package/fonts/README-inlinemath-greek.txt +15 -0
  31. package/fonts/fonts.css +19 -1
  32. package/fonts/inlinemath-greek-italic.woff2 +0 -0
  33. package/fonts/inlinemath-greek-regular.woff2 +0 -0
  34. package/inlinemath.css +17 -7
  35. package/package.json +6 -6
  36. package/src/cas.d.ts +1 -1
  37. package/src/cas.js +15 -4
  38. package/src/draw.js +13 -9
  39. package/src/edit.js +11 -4
  40. package/src/html.js +1 -1
  41. package/src/index.js +1 -1
  42. package/src/layout.js +89 -32
  43. package/src/lite.js +1 -1
  44. package/src/markdown.d.ts +1 -1
  45. package/src/markdown.js +139 -57
  46. package/src/mathzetta.js +2 -2
  47. package/src/select.js +7 -0
  48. package/src/types.d.ts +12 -10
  49. package/src/variables.js +44 -10
  50. package/src/view.js +69 -18
  51. package/dist/chunks/calculate-Cz87Lt0N.js +0 -2
  52. package/dist/chunks/draw-Bev17BJJ.js +0 -2
  53. package/dist/chunks/edit-C65xXzo8.js +0 -2
  54. package/dist/chunks/edit-M68aRA5o.js +0 -2
  55. package/dist/chunks/html-BimAqn7x.js +0 -2
  56. package/dist/chunks/html-CupluJSh.js +0 -2
  57. package/dist/chunks/lite-3Fb-OHbt.js +0 -2
@@ -1,2 +1,2 @@
1
- /* Inline Math 0.2.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),det: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),pmatrix:r(t),bmatrix:r(t),vmatrix:r(t),"()":i(),"[]":i(),"{}":i(),"(]":i(),"[)":i(),"=":{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 i(){return{prec:5,assoc:"left",arity:t,fixity:"none",group:!0}}const s="\\:",o=e=>"string"==typeof e&&e.startsWith(s)&&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),i=u(t);if(!r||!i)return!1;if(i!==r)return i<r;const s=a(e).assoc;return"left"===s?"right"===n:"right"===s&&"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,pmatrix:h,bmatrix:h,vmatrix:h,det: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),d=new Set(["^","?:","?","log"]),m=["(","{","["],g=[")","}","]"];function v(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 b=e=>({type:"number",value:String(e)}),y=e=>({type:"symbol",value:e}),x=(e,t)=>({type:"op",op:e,args:t}),w=['"',"'","`"];function $(e){return v(e,!0)?b(e):w.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,i)=>{const s=k[e]??String(e),o=a(s);if(!o)return n.push({...$(s),id:i}),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(`'${s}' takes a variable number of arguments, so it must follow a count`)}if(n.length<l)throw new Error(`'${s}' 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({...x(s,n.splice(n.length-l,l)),id:i})}),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 A(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 N(e,t,n=null){t(e,n),"op"===e.type&&e.args.forEach(n=>N(n,t,e))}function S(e){let t="";return N(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=new Set(["=","===","≠","≠=","<",">","≤","≥","≈","≡","→"]),j=(e,t,n)=>("op"!==t.type||"?:"!==t.op||!T.has(e.op))&&c(e.op,_(t),n);function z(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 L(e,t,n={}){const r=n.left?"bracket":F(e),i=n.right?"bracket":Z(t);return"digit"!==i&&"sign"!==i&&"word"!==r&&"word"!==i&&"other"!==r&&("frac"!==i||"digit"!==r&&"frac"!==r)}function C(e){return 1===e.length||Boolean(O[e])||/^Δ.$/.test(e)||/^.′+$/.test(e)}function R(e){return"op"===e.type&&!a(e.op)?.group&&(a(e.op)?.prec??100)<70&&!["sum","prod"].includes(e.op)}function Z(e){if("number"===e.type)return e.value.startsWith("-")?"sign":"digit";if("op"!==e.type)return"symbol"===e.type&&C(e.value)?"name":"word";const t=e.op;return"neg"===t||"pm"===t||I(e)?"sign":"/"===t?"frac":a(t)?.group||R(e)?"bracket":P(e)||["der","int","lim","comb"].includes(t)?"call":["^","!","_"].includes(t)?R(e.args[0])?"bracket":Z(e.args[0]):["*","sum","prod","perm"].includes(t)?Z(e.args[0]):"other"}function F(e){if("number"===e.type)return"digit";if("op"!==e.type)return"symbol"===e.type&&C(e.value)?"name":"word";const t=e.op;return"/"===t?"frac":"^"===t||"_"===t?"script":a(t)?.group||R(e)||P(e)||["der","int","lim","comb","perm"].includes(t)?"bracket":["*","neg","pm","sum","prod"].includes(t)?F(e.args[e.args.length-1]):"other"}function P(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&&!j(e,e.args[0],"left")&&B(e.args[0])}const D=e=>"symbol"===e.type&&1===e.value.length&&/[a-zA-Zʹ-Ͽ]/.test(e.value),W=e=>e.slice(2);function U(e){const t=e.args[1];let n=0,r=e;for(;"op"===r.type&&"der"===r.op&&V(r.args[1],t);)n++,r=r.args[0];return{n:n,body:r,by:t,variable:"symbol"===r.type&&C(r.value)}}const V=(e,t)=>e.type===t.type&&e.value===t.value&&"op"!==e.type,H=new Set(["<",">","≤","≥","=","≠"]);function G(e){if("op"!==e.type||!H.has(e.op)||2!==e.args.length)return null;const[t,n]=e.args;if("op"!==t.type||!H.has(t.op)||2!==t.args.length)return null;return{type:"op",op:"&",args:[G(t)??t,{type:"op",op:e.op,args:[t.args[1],n]}]}}for(const e of[O])Object.setPrototypeOf(e,null);const Q={pmatrix:["(",")"],bmatrix:["[","]"],vmatrix:["|","|"]};function X(e){if(!e||"op"!==e.type)return null;if(Object.prototype.hasOwnProperty.call(Q,e.op))return e.args.map(e=>"op"===e.type&&"[]"===e.op?e.args:[e]);if("[]"!==e.op||!e.args.length||!e.args.every(e=>"op"===e.type&&"[]"===e.op))return null;const t=e.args[0].args.length;return!t||!e.args.every(e=>e.args.length===t)||e.args.length<2&&t<2?null:e.args.map(e=>e.args)}function J(e){return Array.isArray(e)&&e.length>0&&e.every(t=>Array.isArray(t)&&t.length>0&&t.length===e[0].length&&!t.some(Array.isArray))}const Y=e=>Array.isArray(e)&&e.length>0&&!e.some(Array.isArray);function K(e){const t=e,n=t.make??(e=>e),r=t.size??(()=>1),i=e=>`${e.length} by ${e[0].length}`,s=(e,r)=>n(Array.from({length:e},(n,r)=>Array.from({length:e},(e,n)=>r===n?t.one():t.zero())),r);function o(e,r){return e[0].length!==r.length&&t.fail(`a ${i(e)} matrix times a ${i(r)} one`),n(e.map(e=>r[0].map((n,i)=>e.reduce((e,n,s)=>t.add(e,t.mul(n,r[s][i])),t.zero()))),e)}function a(e){const n=e.map(e=>e.slice()),i=n.length,s=n[0].length;let o=t.one(),a=0;for(let e=0;e<s&&a<i;e++){let s=-1;for(let o=a;o<i;o++)t.isZero(n[o][e])||(s<0||r(n[o][e])>r(n[s][e]))&&(s=o);if(s<0){o=t.zero();continue}s!==a&&([n[s],n[a]]=[n[a],n[s]],o=t.sub(t.zero(),o));const l=n[a][e];o=t.mul(o,l),n[a]=n[a].map(e=>t.div(e,l));for(let r=0;r<i;r++){if(r===a||t.isZero(n[r][e]))continue;const i=n[r][e];n[r]=n[r].map((e,r)=>t.sub(e,t.mul(i,n[a][r])))}a++}return a<i&&(o=t.zero()),{M:n,det:o,rank:a}}function l(e){const r=e.length;r!==e[0].length&&t.fail(`a ${i(e)} matrix has no inverse`);const o=s(r),{M:l,rank:u}=a(e.map((e,t)=>[...e,...o[t]]));return(u<r||l.some((e,n)=>t.isZero(e[n])))&&t.fail("the matrix has no inverse (its determinant is 0)"),n(l.map(e=>e.slice(r)),e)}return{identity:s,transpose:e=>n(e[0].map((t,n)=>e.map(e=>e[n])),e),times:o,det:function(e){return e.length!==e[0].length&&t.fail(`a ${i(e)} matrix has no determinant`),a(e).det},inverse:l,power:function(e,n){e.length!==e[0].length&&t.fail(`a ${i(e)} matrix has no powers`);let r=n<0n?l(e):e,a=n<0n?-n:n,u=s(e.length,e);for(;a>0n;)1n&a&&(u=o(u,r)),r=o(r,r),a>>=1n;return u},trace:e=>(e.length!==e[0].length&&t.fail(`a ${i(e)} matrix has no trace`),e.reduce((e,n,r)=>t.add(e,n[r]),t.zero())),dot:(e,n)=>(e.length!==n.length&&t.fail("vectors of different lengths"),e.reduce((e,r,i)=>t.add(e,t.mul(r,n[i])),t.zero())),cross:(e,n)=>(3===e.length&&3===n.length||t.fail("the cross product is for vectors of 3 numbers"),[t.sub(t.mul(e[1],n[2]),t.mul(e[2],n[1])),t.sub(t.mul(e[2],n[0]),t.mul(e[0],n[2])),t.sub(t.mul(e[0],n[1]),t.mul(e[1],n[0]))]),solve:function(e,t){return J(t)?o(l(e),t):o(l(e),t.map(e=>[e])).map(e=>e[0])},rank:e=>a(e).rank,rref:e=>n(a(e).M,e),timesVector:(e,t)=>o(e,t.map(e=>[e])).map(e=>e[0]),vectorTimes:(e,t)=>o([e],t)[0]}}function ee(e){const t=new Map;for(const[n,r,i]of e)if(n&&""!==n.trim()&&(t.set(n,r),!i))for(const e of ne(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="",i=0;for(;i<e.length;){const s=te(n,e,i);s?(r+=t.get(e.slice(i,i+s)),i+=s):r+=e[i++]}return r}}function te(e,t,n){let r=e,i=0;for(let e=n;e<t.length&&(r=r.get(t[e]),r);e++)r.end&&(i=e-n+1);return i}function ne(e){const t=new Set([e.toLowerCase(),e.toUpperCase(),re(e)]);return t.delete(e),t}function re(e){let t="",n=!1;for(const r of e){const e=r>="a"&&r<="z",i=r>="A"&&r<="Z";t+=!n&&e?r.toUpperCase():r,n=e||i}return t}const ie="({[",se=")}]";function oe(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 ae(e,t){const n=[];let r=0,i=0;for(let s=0;s<e.length;s++)ie.includes(e[s])?r++:se.includes(e[s])?r--:0===r&&e.startsWith(t,s)&&(n.push(e.slice(i,s)),s+=t.length-1,i=s+1);return n.push(e.slice(i)),n}function le(e,t,n){let r=0;const i=new RegExp(`\\b${n}\\b`,"iy");for(let n=t;n<e.length;n++)if(ie.includes(e[n]))r++;else if(se.includes(e[n])){if(--r<0)return-1}else if(0===r&&(i.lastIndex=n,i.test(e)))return n;return-1}function ue(e,t){let n=0;for(let r=t;r<e.length;r++)if(ie.includes(e[r]))n++;else if(se.includes(e[r])&&--n<0)return r;return e.length}function ce(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 he(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(ie.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,i="",s="",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?i+=e[a]:s+=e[a]}1===r&&(e=e.slice(0,t+1)+"_{"+s+"}("+i+")"+e.slice(o+1))}return e}function pe(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 fe(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),i=e[n+1];if("{"===i||"("===i)return i+r+","+e.slice(n+2);const s=/^[A-Za-z0-9.\u0370-\u03FF]+/.exec(e.slice(n+1))?.[0]??"";return"{"+r+","+s+"}"+e.slice(n+1+s.length)}return e}const de=new Set(["pmatrix","bmatrix","vmatrix"]);function me(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 i=e.indexOf("\\end{"+r+"}"),s=e.indexOf("\\begin{"+r+"}",t+1);if(i<0||-1!==s&&s<i)return!1;const o=e.slice(t+1,i).trim().split("\\\\").map(e=>e.trim()).filter(e=>e.length).map(e=>"["+e.replace(/&/g,", ")+"]"),a=e.slice(i+6+r.length);return de.has(r)?r+"("+o.join(", ")+")"+a:"["+o.join(", ")+"]"+a}function ge(e,t){if("{"!==e[t+1])return[e[t+1],t+2];let n=1,r="";for(let i=t+2;i<e.length;i++){if("{"===e[i])n++;else if("}"===e[i]&&0===--n)return[r,i+1];r+=e[i]}return[r,e.length]}function ve(e){const{lower:t,upper:n,next:r}=function(e){let t="",n="",r=0;return"_"===e[0]&&([t,r]=ge(e,0),"^"===e[r]&&([n,r]=ge(e,r))),{lower:t,upper:n,next:r}}(e),i=e.slice(r),s=e=>e.replace(/\\,/g,"").replace(/\\!/g,"");let o,a="",l="",u=i.indexOf("\\mathrm{d}");if(u>=0){o=i.slice(0,u);const e=/^\{([^{}]*)\}/.exec(i.slice(u+10));a=e?e[1]:i[u+10],l=i.slice(u+10+(e?e[0].length:1))}else(u=function(e){let t=0;for(let n=0;n<e.length;n++)if(ie.includes(e[n]))t++;else if(se.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}(i))>=0?(o=i.slice(0,u),a=i[u+1],l=i.slice(u+2)):o=i;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=[...s(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("+(s(o)||"1");return a&&(c+=","+a),(t||n)&&(c+=","+t+","+n),c+")"+l}function be(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(se.includes(n[e])?r--:ie.includes(n[e])&&r++,0===r)return"("+n.slice(0,e)+","+t+")"+n.slice(e+1);return!1}function ye(e){return"{"===e[0]||e.length<2?e:"{"+e[0]+"}{"+e[1]+"}"+e.slice(2)}const xe=/[A-Za-z\u0370-\u03FF]/;function we(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 $e(e,t){const n=/^\^(?:\{(\d+)\}|(\d))/.exec(e.slice(t));return n?[Number(n[1]??n[2]),t+n[0].length]:[1,t]}function ke(e,t){const n=e.replace(/\\mathrm\{d\}/g,"d"),r=t.replace(/\\mathrm\{d\}/g,"d"),i=/^d(?:\^\{?(\d+)\}?)?([A-Za-z\u0370-\u03FF]?)$/.exec(n),s=/^d([A-Za-z\u0370-\u03FF])(?:\^\{?(\d+)\}?)?$/.exec(r);return i&&s?{n:Number(i[1]??1),of:i[2],by:s[1]}:null}function qe(e,t){if(ie.includes(e[t])){let n=0;for(let r=t;r<e.length;r++)if(ie.includes(e[r]))n++;else if(se.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(ie.includes(e[r]))n++;else{if(se.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 Me=(e,t,n)=>`der(${e},${t}${n>1?","+n:""})`;const Ae="strtktk",Ne="ABCDEFGHIJ",Se=e=>Ae+[...String(e)].map(e=>Ne[e]).join("");function Oe(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 Ee(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 Ie={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[Ie])Object.setPrototypeOf(e,null);const _e="([{",Te=")]}";function je(e,t){let n=0;for(let r=t;r<e.length;r++)if(_e.includes(e[r]))n++;else if(Te.includes(e[r])&&0===--n)return r;return-1}function ze(e){if(!e.trim())return[];const t=[];let n=0,r=0;for(let i=0;i<e.length;i++)_e.includes(e[i])?n++:Te.includes(e[i])?n--:","===e[i]&&0===n&&(t.push(e.slice(r,i).trim()),r=i+1);return t.push(e.slice(r).trim()),t}function Le(e,t,n){const r=[...e.matchAll(t)];for(let t=r.length-1;t>=0;t--){const i=r[t],s=i.index+i[0].length-1,o=je(e,s);if(o<0)continue;const a=n(ze(e.slice(s+1,o)),i,e.slice(o+1));if(null==a)continue;const[l,u=0]=Array.isArray(a)?a:[a];if((e=e.slice(0,i.index)+l+e.slice(o+1+u)).length>1e5)throw new Error("The expression expands too much when read")}return e}const Ce=e=>new RegExp(`(?<![\\w.])(${e})\\s*\\(`,"g"),Re=e=>`(${e})`,Ze=e=>/^\[.*\]$/s.test(e.trim())?`{${e.trim().slice(1,-1)}}`:e;const Fe={IF:e=>e.length>=2&&`((${e[0]}) ? (${e[1]}) : (${e[2]??"false"}))`,AND:e=>e.length&&`(${e.map(Re).join(" & ")})`,OR:e=>e.length&&`(${e.map(Re).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 Pe={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"},Be="strtktk[A-J]+";function De(e){for(let t=!0;t;){const n=e;t=(e=e.replace(new RegExp(`(${Be})\\s*\\|\\|\\s*(${Be})`,"g"),"$1 + $2"))!==n}const t=new RegExp(`^\\(typeof\\(([^()]*)\\)\\s+IN\\s+\\(${Be},\\s*${Be}\\)\\s+AND\\s+(.*)\\)$`,"s");for(let n=e.lastIndexOf("(typeof(");n>=0;n=n>0?e.lastIndexOf("(typeof(",n-1):-1){const r=je(e,n),i=r>0&&t.exec(e.slice(n,r+1));if(!i)continue;const[,s,o]=i,a={[`${s} = TRUNC(${s})`]:"ℤ",[`${s} = TRUNC(${s}) AND ${s} > 0`]:"ℕ",[`ABS(${s}) < ∞`]:"ℝ"}[o.trim()];a&&(e=`${e.slice(0,n)}((${s}) ∈ ${a})${e.slice(r+1)}`)}e=Le(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=Le(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 i=e.slice(n+4,n+r.index).split(/\b(WHEN|THEN|ELSE)\b/i).map(e=>e.trim()),s=[];let o="null";for(let e=1;e<i.length;e+=2){const t=i[e].toUpperCase();"WHEN"===t?s.push([i[e+1],i[e+3]]):"ELSE"===t&&(o=i[e+1])}const a=s.reduceRight((e,[t,n])=>`((${t}) ? (${n}) : ${e})`,Re(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=>Pe[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 i=r.index+r[0].length-1,s=je(e,i);if(s<0)break;e=`${e.slice(0,r.index)}${n} {${e.slice(i+1,s)}}${e.slice(s+1)}`,t.lastIndex=0}return e.replace(/<>/g," ≠ ")}const We={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"},Ue={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 Ve(e){return e=(e=(e=(e=e.replace(/(?<![\w.])(?:np|numpy)\.random\.random\(\s*\)|(?<![\w.])random\.random\(\s*\)/g,"Math.random()")).replace(/(?<![\w.])(?:np|numpy)\.linalg\.(det|inv)\b/g,"$1")).replace(/(?<![\w.])(?:np|numpy)\.array\s*\(/g,"(")).replace(/(?<![\w.])(?:np|numpy)\.(\w+)/g,(e,t)=>We[t]?`Math.${We[t]}`:Ue[t]?Ue[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)=>Ge[t]??e),e=e.replace(/(?<![\w.])sympy\.(Reals|Integers|Naturals0?|Rationals|Complexes)\b/g,(e,t)=>Ge[t]),e.replace(/(?<![\w.])sympy\.(\w+)/g,(e,t)=>Qe[t]??He[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 He={pi:"π",E:"e",oo:"∞",true:"true",false:"false",nan:"NaN",I:"i"},Ge={Reals:"ℝ",Integers:"ℤ",Naturals:"ℕ",Naturals0:"ℕ",Rationals:"ℚ",Complexes:"ℂ"},Qe={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",Matrix:""},Xe={open:"()",Lopen:"(]",Ropen:"[)"};const Je=e=>{const t=/^\((.*)\)$/s.exec(e.trim());return t?ze(t[1]):null},Ye=e=>t=>2===t.length&&`${e[0]}${t[0]}, ${t[1]}${e[1]}`,Ke=e=>Je(e)??[e],et={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]}) ∈ ${Ze(e[1])})`,contains:e=>2===e.length&&`((${e[1]}) ∈ ${Ze(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(Re).join(" & ")})`,sympy_or:e=>e.length&&`(${e.map(Re).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(Je);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:Ye("[]"),sympy_interval_open:Ye("()"),sympy_interval_Lopen:Ye("(]"),sympy_interval_Ropen:Ye("[)"),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=Ke(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&&Ke(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&&Ke(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:tt("sum"),prod:tt("prod")};function tt(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=ze(n[3]),[i,s]=1===r.length?["0",r[0]]:r,o=/\s*\+\s*1$/.test(s)?s.replace(/\s*\+\s*1$/,""):`(${s}) - 1`;return`(\\${e}_{${n[2]}=${i}}^{${o}} (${n[1]}))`}}for(const e of[Fe,Pe,We,Ue,He,Ge,Qe,Xe,et])Object.setPrototypeOf(e,null);const nt=String.raw`(?:\([^()]*\)|\[[^\[\]]*\]|\{[^{}]*\}|(?<![\w.′^])[\w.′^]+)`,rt=e=>e.trim().split(/\s+/).join(String.raw`\s+`),it=e=>new RegExp(String.raw`(?<![\w.])${rt(e)}(?![\w.])`,"gi"),st=[["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","="]],ot="[<>≤≥=≠≈]",at=[["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 lt=ee([[" 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 ","→"],["===","=...="]]),ut=ee([["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"],["\\det","det"],["^{\\top}","^{T}",!0],["^\\top","^T",!0],["^{\\intercal}","^{T}",!0],["^\\intercal","^T",!0],["^{\\mathsf{T}}","^{T}",!0],["^{\\mathrm{T}}","^{T}",!0],["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,i="arc"+n+e;e&&(t("Math."+r,r),t("\\"+r,r));for(const n of["^-1","^{-1}","-1"])t("\\"+r+n,i),t(r+n,i),e||t("Math."+r+n,i);e||t("\\a"+r,i),t("\\arc"+r,i),t("Math.a"+r,i),t("Math.arc"+r,i)}return e}()]),ct=[["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 Le(e,/(?<![\w.])([A-Z][A-Z0-9]*(?:\.[A-Z]+)?)\s*\(/g,(e,t)=>Fe[t[1]]?.(e)||null)}(e)),e=function(e){e=Le(e,Ce("quad"),(e,t,n)=>{const r=/^lambda\s+(\w+)\s*:\s*(.*)$/s.exec(e[0]??"");if(!r||3!==e.length)return null;const i=/^\s*\[\s*0\s*\]/.exec(n);return[`int(${r[2]}, ${r[1]}, ${e[1]}, ${e[2]})`,i?i[0].length:0]}),e=Le(e,Ce(Object.keys(et).join("|")),(e,t)=>et[t[1]](e)||null);for(let t=(e=Le(e,Ce("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=je(e,n);let i=t;if(Te.includes(e[t-1])){let n=0;for(i=t-1;i>=0;i--)if(Te.includes(e[i]))n++;else if(_e.includes(e[i])&&0===--n)break}else for(;i>0&&/[\w.]/.test(e[i-1]);)i--;r<0||i<0||i===t||(e=`${e.slice(0,i)}((${e.slice(n+1,r)}) ∈ ${Ze(e.slice(i,t))})${e.slice(r+1)}`)}return e}(e=Ve(e=De(e=(e=(e=function(e){for(const[t,n]of Object.entries(Ie))for(let r=e.lastIndexOf(n);r>=0;r=r>0?e.lastIndexOf(n,r-1):-1){const i=r+n.length,s="("===e[i]?je(e,i):-1;if(s<0)continue;let o=e.slice(i+1,s);"gcd"===t&&(o=o.trim().replace(/^\[|\]$/g,""));const a="factorial"===t?`((${o})!)`:`${t}(${o})`;e=e.slice(0,r)+a+e.slice(s+1)}for(let t=e.lastIndexOf(").toFixed(");t>=0;t=t>0?e.lastIndexOf(").toFixed(",t-1):-1){const n=t+10-1,r=je(e,n),i=e.lastIndexOf("Number(",t);r<0||i<0||je(e,i+7-1)!==t||(e=e.slice(0,i)+`fixed(${e.slice(i+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,i,s)=>`(\\${"sum"===t?"sum":"prod"}_{${n}=${r}}^{${i}} (${s}))`)}(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 i=0,s=-1,o=e.length;for(let t=r+2;t<e.length;t++)if(_e.includes(e[t]))i++;else{if(Te.includes(e[t])&&--i<0){o=t;break}if(0===i&&","===e[t]){o=t;break}if(0===i&&/^then\b/.test(e.slice(t))&&/\W/.test(e[t-1])){s=-2;break}0===i&&s<0&&/^else\b/.test(e.slice(t))&&/\W/.test(e[t-1])&&(s=t)}if(s<0)continue;i=0;let a=0;for(let t=r-1;t>=0;t--)if(Te.includes(e[t]))i++;else{if(_e.includes(e[t])&&--i<0){a=t+1;break}if(0===i&&","===e[t]){a=t+1;break}}const l=e.slice(a,r).trim();if(!l)continue;const u=`((${e.slice(r+2,s).trim()}) ? (${l}) : (${e.slice(s+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,i="∈")=>{t=t.replace(new RegExp(String.raw`(?<![\w.])${rt(e)}\s+(${nt})\s+(?:and|to)\s+(${nt})(?:\s+(inclusive|exclusive))?(?![\w.])`,"gi"),(e,t,s,o)=>{const[a,l]="exclusive"===o?.toLowerCase()?["(",")"]:"inclusive"===o?.toLowerCase()?["[","]"]:[n,r];return` ${i} ${a}${t}, ${s}${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+(${nt})\s+to\s+(${nt})`,"gi"),(e,t,n,r,i)=>{const[s,o]={open:["(",")"],closed:["[","]"],"half-open":["[",")"]}[n.toLowerCase()];return` ${t?"∉":"∈"} ${s}${r}, ${i}${o} `});const r=String.raw`(${nt})\s+`;t=t.replace(new RegExp(r+String.raw`is\s+(not\s+)?within\s+(${nt})\s*(%|\s+percent)?\s+of\s+(${nt})`,"gi"),(e,t,n,r,i,s)=>`(abs((${t}) - (${s})) ${n?">":"≤"} ${i?`(${r})/100 * ${/^\d+(\.\d+)?$/.test(s)?s:`abs(${s})`}`:`(${r})`})`),t=t.replace(new RegExp(r+String.raw`is\s+(?:a\s+)?multiple\s+of\s+(${nt})`,"gi"),"(($1) mod ($2) = 0)"),t=t.replace(new RegExp(r+String.raw`is\s+(not\s+)?divisible\s+by\s+(${nt})`,"gi"),(e,t,n,r)=>`((${t}) mod (${r}) ${n?"≠":"="} 0)`),t=t.replace(new RegExp(String.raw`(${nt})\s+divides\s+(${nt})`,"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 at)t=t.replace(it(e),` ${n} `);t=t.replace(it("is not in")," ∉ ").replace(it("is in")," ∈ ").replace(it("is an element of")," ∈ ");for(const[e,n]of st)t=t.replace(it(e),` ${n} `);t=t.replace(it("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`(${nt})\s*(${ot})\s*(${nt})\s+(and|or)\s+(${ot})`,"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+(${nt})`,"gi"),"abs($1)"),t=t.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?square\s+root\s+of\s+(${nt})`,"gi"),"sqrt($1)"),t=t.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?cube\s+root\s+of\s+(${nt})`,"gi"),"root(3, $1)"),t=t.replace(new RegExp(String.raw`(${nt})\s+to\s+the\s+power\s+of\s+(${nt})`,"gi"),"($1)^($2)");const i={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`(${nt})\s+to\s+the\s+(${Object.keys(i).join("|")}|(\d+|n)(?:st|nd|rd|th))(?:\s+power)?(?![\w.])`,"gi"),(e,t,n,r)=>`(${t})^(${i[n.toLowerCase()]??r})`),t=t.replace(new RegExp(String.raw`(${nt})\s+to\s+the\s+(${nt})(?![\w.])`,"gi"),"($1)^($2)");const s={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(s).sort((e,t)=>t[0].length-e[0].length))t=t.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?${rt(e)}\s+of\s+(${nt})`,"gi"),`${n}($1)`);t=t.replace(new RegExp(String.raw`(${nt})\s+squared(?![\w.])`,"gi"),"($1)^2"),t=t.replace(new RegExp(String.raw`(${nt})\s+cubed(?![\w.])`,"gi"),"($1)^3"),t=t.replace(new RegExp(String.raw`(?<![\w.])half\s+of\s+(${nt})`,"gi"),"($1)/2"),t=t.replace(new RegExp(String.raw`(?<![\w.])twice\s+(${nt})`,"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+)${rt(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",lt],["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=le(e,n+2,"then");if(r<0)return e;const i=e.slice(n+2,r),s=le(e,r+4,"else"),o=ue(e,s<0?r+4:s+4),a=e.slice(r+4,s<0?o:s),l=s<0?"unchanged":e.slice(s+4,o).trim();e=`${e.slice(0,n)}((${i.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,i="";for(;n>0&&r<e.length;)"{"===e[r]?n++:"}"===e[r]?n--:i+=e[r],r++;e=e.slice(0,t-4)+i+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=he(e);for(let t=0;t<e.length-1;t++)if("?"===e[t]&&":"!==e[t+1])e=ce(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]??"",i=e[n+t.length]??"";return"Δ"===r?"":/[A-Za-z\u0370-\u03FF′]/.test(r)&&/[A-Za-z\u0370-\u03FF]/.test(i)?" ":""})}],["symbols",ut],["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 i=t;i>=0;i--)if(")"===e[i])n++;else if("("===e[i]&&0===--n){r=i;break}if(r<0)continue;for(;r>0&&/[A-Za-z\u0370-\u03FF′]/.test(e[r-1]);)r--;let i=0;for(;"′"===e[t+1+i];)i++;e=e.slice(0,r)+Me(e.slice(r,t+1),"x",i)+e.slice(t+1+i),t=r}return e}(e=(e=he(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&&xe.test(e[t-1]);let r,i=null,s=t;if(e.startsWith("frac{",t)){const n=we(e,t+4),r=n&&we(e,n[1]);i=r&&ke(n[0],r[0]),i&&(s=r[1])}else if("d"===e[t]&&!n){let[n,r]=$e(e,t+1),o="";if(xe.test(e[r]??"")&&"/"===e[r+1]&&(o=e[r++]),"/"===e[r]&&"d"===e[r+1]&&xe.test(e[r+2]??"")){const t=e[r+2],[,a]=$e(e,r+3);i={n:n,of:o,by:t},s=a}}if(i){if(i.of)r=Me(i.of,i.by,i.n);else{const[t,n]=qe(e,s);if(!t)continue;r=Me(t,i.by,i.n),s=n}e=e.slice(0,t)+r+e.slice(s),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),i=n=>e.slice(Math.max(0,t-n),t+1);if("{"===n){if("\\begin"===r(6)){const n=me(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"+fe(e.slice(t+1)):"sqrt"===r(4)&&(e=e.slice(0,t-4)+"sqrt"+fe(e.slice(t+1)));else if("⌊"===n||"⌈"===n)e=e.slice(0,t)+pe(e.slice(t));else if("t"===n)"\\int"===i(3)&&(e=e.slice(0,t-3)+ve(e.slice(t+1)));else if("m"===n)"\\binom"===i(5)&&(e=e.slice(0,t-5)+"\\binom"+ye(e.slice(t+1)));else if("d"===n&&"dd"===i(1)&&"("===e[t+2]){const n=be(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 ht(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 i=e[r];if('"'!==i&&"'"!==i&&"`"!==i){n+=e[r++];continue}let s=r+1,o="",a=!1;for(;s<e.length&&(a||e[s]!==i);)a=!a&&"\\"===e[s],o+=e[s++];const l=Se(t.size);t.set(l,i+o+i),n+=l,r=s+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=Oe(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=Oe(e,n);t+=e.slice(n,r+1),n=r}else t+=r}return t}(e));let i=n.replace(/\t/g," ");t.evaluate&&(i=function(e,t,n){let r=0;for(;;){const i=e.indexOf("{{",r);if(i<0)return e;const s=pt(e,i);if(s<0)return e;let o=e.slice(i+2,s).trim();for(const[e,n]of t)o=o.split(e).join(n);try{let a=n(o);if(/^["'`]/.test(a)){const e=Se(t.size);t.set(e,a),a=e}const l=e.slice(0,i).trimEnd(),u=e.slice(s+2).trimStart();/^[\d.]/.test(a)&&(/[\d.]$/.test(l)||/^[\d.]/.test(u))&&(a=`(${a})`),e=e.slice(0,i)+" "+a+" "+e.slice(s+2),r=0}catch{r=s+2}}}(i,r,t.evaluate));const s=[["strings",i]];for(const[e,t]of ct){if(i=t(i),i.length>1e5)throw new Error("The expression expands too much when read");s.push([e,i])}return{cleaned:i,stringMap:r,steps:s}}function pt(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 ft=Object.keys(p).filter(e=>100===p[e]&&/^[a-z]{2,}$/.test(e)),dt=["frac"],mt=[...Object.keys(O),"pi","tau","inf","infinity","exp"],gt="\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+/),vt=new Set([...mt,...gt,"true","false","null","undefined","unchanged","deg","mod","pmod","NaN","Infinity"]),bt=/^[a-zA-ZͰ-Ͽ]$/,yt=new Set(["f","g","h","u","v","F","G","H"]),xt=e=>ft.includes(e)||dt.includes(e),wt=[...ft,...dt,...mt].sort((e,t)=>t.length-e.length),$t=[...ft,...dt,"pi"].sort((e,t)=>t.length-e.length);function kt(e,t=wt){const n=[];let r=0;for(;r<e.length;){const i=t.find(t=>e.startsWith(t,r))??e[r];n.push(i),r+=i.length}return n}function qt(e){if(xt(e))return!0;const t=kt(e,$t);return t.length>1&&xt(t[t.length-1])&&!vt.has(e)}function Mt(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=>bt.test(e)))||1===e.length||vt.has(e)||xt(e))return[e];var r;if("Δ"===e[0]&&2===e.length)return[e];if("latex"===t)return At(kt(e),n);if(e.length<=2)return[...e];const i=At(kt(e,$t),n),s=i.findIndex(e=>e.length>1);if(s<0)return[e];if("pi"===i[s]&&!i.some(e=>ft.includes(e)))return 3===e.length?i:[e];const o=s;let a=0,l=0;for(const e of i.slice(s))a=1===e.length?a+1:0,l=Math.max(l,a);return o<=1&&l<=2?i:[e]}function At(e,t){const n=e[e.length-1];return t||!ft.includes(n)?e:[...e.slice(0,-1),...n]}const Nt="§",St=/[A-Za-zͰ-Ͽ′]/,Ot=e=>/^[A-Za-zͰ-Ͽ][A-Za-zͰ-Ͽ′]*$/.test(e);function Et(e,t="plain"){if("string"!=typeof e)throw new Error("Tokenizer input must be a string");const n=[];let r="";const i=e=>{r&&(Ot(r)?n.push(...function(e,t,n){if((e=>new RegExp(`^${Ae}[${Ne}]+$`).test(e))(e))return[e];if(m.includes(t))return function(e,t){if(/^[a-zA-Z]′+$/.test(e))return[s+e];if("if"===e.toLowerCase())return["\\:if"];if(1===e.length)return yt.has(e)?[s+e]:[e];if(f(e))return[e];const n=Mt(e,{mode:t,followed:!0});return n.length>1?n:e.length<=2?[...e]:[s+e]}(e,n);const r=void 0!==t&&!/[+\-*/=<>),\]}|!≤≥≠]/.test(t);return Mt(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===Nt){i(o);const r=e.indexOf(Nt,t+1),a=e.slice(t,r+1);n.push(m.includes(e[r+1])?s+a:a),t=r;continue}if(Ot(r)&&/[0-9]/.test(o)&&f(r+o)){const{op:i,end:s}=It(e,t,r+o);n.push(i),r="",t=s;continue}if(St.test(o)&&"′"!==o&&v(r)&&(n.push(r),r=""),St.test(o)&&(""===r?"′"!==o:Ot(r)))r+=o;else if(/[0-9]/.test(o)&&Ot(r)&&!qt(r))r+=o;else if(Ot(r)&&i(" "===o?e[t+1]:o),"(){}[]".includes(o))r&&n.push(..._t(r,o)),r="",n.push(o);else if("_"!==o&&" "!==o){if(f(r+o)){const{op:i,end:s}=It(e,t,r+o);n.push(i),r="",t=s;continue}if(f(o)){i(o);const{op:r,end:s}=It(e,t,o);n.push(r),t=s;continue}r+=o}else i(e[t+1]),"_"===o&&n.push("_")}if(i(void 0),n.some(e=>/^:/.test(e)))throw new Error("Unmatched ':'");return n}function It(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 _t(e,t){if(!m.includes(t))return[e];if("\\"===e[0]){const t=e.slice(1);return[f(t)?t:s+t]}return v(e)?[e,"*"]:f(e)||xt(e)||v(e[0])?[e]:[s+e]}const Tt=70,jt=100,zt="%mod",Lt=e=>m.includes(e),Ct=e=>g.includes(e),Rt=e=>o(e)||p[e]===jt&&"_"!==e,Zt=new Set(["\\comb","\\perm","comb","perm"]),Ft={frac:"/","\\binom":"\\binom"},Pt={"\\comb":"comb","\\perm":"perm",deg:"°","π":"pi","∨":"|"};class Bt{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(Ct(e)?`Unmatched '${e}'`:`Unexpected '${e}'`);return this.out}parseExpression(e,t=!1){for(this.parseOperand();;){const n=this.peek();if(void 0===n||Ct(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===zt)return{lbp:Tt,run:()=>{this.next(),this.parseExpression(Tt),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:jt,run:()=>{this.next(),this.parseScript(),this.emit("_")}};if(Zt.has(e))return{lbp:jt,run:()=>{this.next(),this.parseExpression(jt),this.emit(e)}};const n=p[e];if(void 0!==n&&!Rt(e)&&"\\not"!==e&&!(e in Ft)){const t=d.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&&!Rt(e)?71:Tt,run:()=>{this.parseExpression(Tt),this.emit("*")}}}startsOperand(e){return void 0===e||Ct(e)||"|"===e?"|"===e:e!==zt&&(!!(Lt(e)||Rt(e)||e in Ft)||!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(Tt,!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(Lt(e))return this.bracket(e,"{"===e&&("∈"===t||"∉"===t));if("|"===e)return this.absolute();if("-"===e||"+"===e){return"^"===t&&(void 0===n||Ct(n))||Lt(t)&&Ct(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 Ft)return this.parseScript(),this.parseScript(),this.emit(Ft[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(Rt(e))return this.functionCall(e);if(Ct(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||!v(t[0])&&"∞"!==t[0]?this.emit("neg"):this.out[e]="-"+t[0]}bracket(e,t=!1){if(Ct(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();Ct(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(Lt(e))return this.parseOperand();if("-"===e||"+"===e)return this.parseOperand();if(Rt(e))return this.parseOperand();if(this.next(),void 0===e||Ct(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&&!Lt(this.peek()))return this.emit(e);this.argument(),this.emit(e),t&&this.emit(...t,"^")}argument(){const e=this.peek();if(Lt(e))return this.next(),this.bracket(e);this.parseExpression(Tt,!0)}}function Dt(e,t){e=function(e){const t=[];for(let n=0;n<e.length;n++){const r=e[n],i=e=>"string"==typeof e&&/^[a-zA-Z]$/.test(e);if(yt.has(r)&&"^ { - 1 } ("===e.slice(n+1,n+7).join(" ")){t.push(s+r+"⁻¹"),n+=5;continue}const[o,a,l]=e.slice(n+1,n+4),u=i(a)?a!==r:v(a);i(r)&&"e"!==r&&"("===o&&u&&")"===l?t.push(s+r):t.push(r)}return t}(e);const n=[];for(const r of e)f(r)||Lt(r)||Ct(r)||"_"===r||o(r)||v(r)?n.push(r):n.push(...Wt(r,t));return n}function Wt(e,t){const n=e=>Dt(Et(e,t),t);let r=0;for(;r<e.length&&v(e.slice(0,r+1));)r++;if(0===r){if("%"===e[0])return[zt,...n(e.slice(1))];const r=e.indexOf("%");return r>0&&r<e.length-1?[...Wt(e.slice(0,r),t),zt,...n(e.slice(r+1))]:[e]}const i=e.slice(r);return"%"===i[0]?1===i.length?[e]:[e.slice(0,r),zt,...n(i.slice(1))]:[e.slice(0,r),...n(i)]}for(const e of[Ft,Pt])Object.setPrototypeOf(e,null);const Ut=new Set(["()","[]","{}","(]","[)"]),Vt={pow:"^",sqrtpow:"root","\\binom":"comb","\\comb":"comb","\\perm":"perm",frac:"/","==":"=","!==":"≠="},Ht=new Set(["round","fixed","der"]),Gt=e=>o(e)||100===p[e];function Qt(e){const n=[],r=e=>{if(!n.length)throw new Error(`'${e}' is missing an operand`);return n.pop()},i=e=>e.list?e.list:[e],s=(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:[...i(t),...i(e)]})}if(Ut.has(l)){const t=i(r(l));if(!t.length&&!Gt(e[u+1]))throw new Error("Empty brackets");return void n.push(x(l,t))}const c=Vt[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(Gt(l)&&Ut.has(e[u-1])&&n[n.length-1]?.op===e[u-1])p=n.pop().args;else{let e=h.arity===t||Ht.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=>s(e,l))}n.push(function(e,n){switch(e){case"sqrt":if(2===n.length)return x("root",n);break;case"round":if(1===n.length)return x("round",[n[0],b(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 x("sum"===e?"\\sumidx":"\\prodidx",n);break}case"det":if(n.length>1&&n.every(e=>"op"===e.type&&"[]"===e.op))return x("det",[x("[]",n)]);break;case"fixed":if(1===n.length)return x("fixed",[n[0],b(2)]);break;case"der":if(1===n.length)return x("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 i=e;for(let e=0;e<r;e++)i=x("der",[i,t]);return i}(n);break;case"log":if("symbol"===n[0].type&&"e"===n[0].value)return x("ln",[n[1]]);break;case"lim":return x("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,i]=e;if(2===e.length&&"op"===r.type&&"→"===r.op&&t(r.args[1])){const[e,i]=r.args;return[n,e,i.args[0],y(t(i))]}return 3===e.length&&t(i)?[n,r,i.args[0],y(t(i))]:e}(n));case"\\:if":if(2===n.length||3===n.length)return x("?:",[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),x(e,n)}(c,p))}),1!==n.length)throw new Error(n.length?"Some values are not connected by an operator":"Empty expression");return s(n[0],"end")}for(const e of[Vt])Object.setPrototypeOf(e,null);const Xt=/\\(?:text|textrm|textit|mathrm|mathit|operatorname)\{\s*([A-Za-z][A-Za-z0-9 ]*[A-Za-z0-9])\s*\}/g;const Jt=e=>/^[a-z][a-z0-9]*$/.test(e)&&f(e);function Yt(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=ae(e.slice(t+13,n),"\\\\").map(e=>ae(e,"&")).filter(e=>e.join("").trim());let i=null;for(let e=r.length-1;e>=0;e--){const t=r[e][0].trim(),n=oe(r[e].slice(1).join("&"));i=null!==i||n?`((${n||"true"}) ? (${t}) : ${i??"(unchanged)"})`:`(${t})`}e=e.slice(0,t)+(i??"")+e.slice(n+11)}return e}(e),e.replace(/\{\}\^\{([^{}]*)\}\s*\\mathrm\{P\}\s*_\{([^{}]*)\}/g,"\\perm($1,$2)")):e}let Kt=null;function en(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 i=/^\s*=(?!=)/.test(e);i&&(e=e.replace(/("(?:[^"]|"")*")|\$(?=[A-Za-z]{0,3}\d|[A-Za-z]{1,3}\$?\d)/g,(e,t)=>t??""));const s=i?[...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,i=e=>{const t=`${Nt}${r.size}${Nt}`;return r.set(t,e),t};e=e.replace(Xt,(e,t)=>Jt(t.trim())?` ${t.trim()}`:i(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"),()=>i(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)=>i(t)+(r?" * (":n))}return{text:e,protectedNames:r}}(Yt(e),t.names,[...t.values??[],...s]),l=(e=>/\\[A-Za-z]/.test(e)?"latex":"plain")(o),{cleaned:u,stringMap:c,steps:h}=((e,t={})=>{const n=void 0===t.blocks?Kt:t.blocks;return ht(e,{evaluate:n?e=>n(e,t.scope):void 0})})(o,{blocks:t.blocks,scope:t.scope}),p=e=>Ee(Ee(e,c),a);n.mode=l,n.cleaned=p([u])[0],n.cleanSteps=h,n.tokens=Et(u,l),n.rawPostfix=p(function(e,t="plain"){return new Bt(Dt(e,t)).parseAll().map(e=>Pt[e]??e)}(n.tokens,l));const f=M(Qt(n.rawPostfix));n.postfix=f,n.tree=q(f)}catch(e){n.error=e instanceof RangeError?"Nested too deeply":e.message}return n}const tn=e=>"string"==typeof e&&e.length>80?`${e.slice(0,77)}…`:e;function nn(e,t={}){const n=en(e,t);if(n.error)throw new Error(`Failed to parse expression "${tn(e)}": ${n.error}`);return n.tree}const rn=(e,t)=>"string"==typeof e?nn(e,t):A(e),sn=e=>Array.isArray(e)&&0===e.length,on=K({add:(e,t)=>e+t,sub:(e,t)=>e-t,mul:(e,t)=>e*t,div:(e,t)=>e/t,isZero:e=>Math.abs(e)<1e-12,zero:()=>0,one:()=>1,size:Math.abs,fail:e=>{throw new Error(e)}}),an=e=>J(e)&&(e.length>1||e[0].length>1),ln=e=>Y(e)&&!an(e),un=e=>{const t=(n,r)=>{if(Array.isArray(n)&&Array.isArray(r)){if(n.length!==r.length)throw new Error("Lists of different lengths");return n.map((e,n)=>t(e,r[n]))}return Array.isArray(n)?n.map(e=>t(e,r)):Array.isArray(r)?r.map(e=>t(n,e)):e(n,r)};return t},cn=(e,t)=>an(e)&&an(t)?on.times(e,t):an(e)&&ln(t)?on.timesVector(e,t):ln(e)&&an(t)?on.vectorTimes(e,t):un((e,t)=>e*t)(e,t),hn=e=>t=>e(t.length>1&&t.every(ln)?t:t[0]),pn={det:hn(on.det),inv:hn(on.inverse),inverse:hn(on.inverse),transpose:hn(on.transpose),trace:hn(on.trace),tr:hn(on.trace),rank:hn(on.rank),rref:hn(on.rref),identity:([e])=>on.identity(e),dot:([e,t])=>on.dot(e,t),cross:([e,t])=>on.cross(e,t),linsolve:([e,t])=>on.solve(e,t)},fn=(e,t)=>e.args.map(e=>"op"===e.type&&"[]"===e.op?e.args.map(e=>$n(e,t)):[$n(e,t)]),dn={pi:Math.PI,"π":Math.PI,e:Math.E,tau:2*Math.PI,"τ":2*Math.PI,"∞":1/0,"-∞":-1/0,true:!0,false:!1},mn=(e,t)=>t?mn(t,e%t):Math.abs(e),gn={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,det:e=>on.det(e),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},vn={"+":(e,t)=>Array.isArray(e)||Array.isArray(t)?un((e,t)=>e+t)(e,t):e+t,"-":(e,t)=>Array.isArray(e)||Array.isArray(t)?un((e,t)=>e-t)(e,t):e-t,"*":cn,"/":(e,t)=>an(t)?cn(e,on.inverse(t)):Array.isArray(e)||Array.isArray(t)?un((e,t)=>e/t)(e,t):e/t,"^":(e,t)=>{if(!an(e))return Array.isArray(e)?un((e,t)=>e**t)(e,t):e**t;if(!Number.isInteger(t))throw new Error("A matrix to a power that is not a whole number");return on.power(e,BigInt(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)},bn={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(mn),"()":e=>e,"[]":e=>e,"{}":e=>e};const yn=5e6;let xn=0,wn=0;function $n(e,t){if(++xn>yn)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(dn,e.value))return dn[e.value];throw new Error(`No value for '${e.value}'`)}const n=G(e);if(n)return $n(n,t);const{op:r,args:i}=e;if("?:"===r)return $n(i[0],t)?$n(i[1],t):$n(i[2],t);if("∈"===r||"∉"===r)return function(e,t){const[n,r]=e.args,i=$n(n,t);let s;if("symbol"===r.type&&kn[r.value])return s=kn[r.value](i),"∈"===e.op?s:!s;if("op"===r.type&&["()","[]","(]","[)"].includes(r.op)&&2===r.args.length){const[e,n]=r.args.map(e=>$n(e,t)),o="["===r.op[0]?i>=e:i>e,a="]"===r.op[1]?i<=n:i<n;s=o&&a}else{const e=$n(r,t);s=Array.isArray(e)&&e.includes(i)}return"∈"===e.op?s:!s}(e,t);if("random"===r)return Math.random();if(("\\sumidx"===r||"\\prodidx"===r)&&3===i.length&&"op"===i[1].type&&"="===i[1].op&&"symbol"===i[1].args[0].type){const[e,n,s]=[i[0],i[1].args[1],i[2]],o=i[1].args[0].value,a=$n(n,t),l=$n(s,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 i=$n(e,{...t,[o]:n});u="\\sumidx"===r?u+i:u*i}return u}if("pmod"===r){const[e,n]=i,r=$n(n,t);if("op"===e.type&&["≡","="].includes(e.op)){const[n,i]=e.args.map(e=>$n(e,t));return(n-i)%r===0}return $n(e,t)%r}if("pmatrix"===r||"bmatrix"===r)return fn(e,t);if("vmatrix"===r)return on.det(fn(e,t));if("^"===r&&"symbol"===i[1].type&&"T"===i[1].value&&!Object.prototype.hasOwnProperty.call(t,"T")){const e=$n(i[0],t);if(an(e))return on.transpose(e)}const s=i.map(e=>$n(e,t));if(r.startsWith("\\:")&&Object.prototype.hasOwnProperty.call(pn,r.slice(2)))return pn[r.slice(2)](s);if(gn[r]&&1===s.length)return gn[r](s[0]);if(vn[r]&&2===s.length)return vn[r](s[0],s[1]);if(bn[r])return bn[r](s);throw new Error(`Can't evaluate '${r}'`)}const kn={"ℝ":Number.isFinite,"ℤ":Number.isInteger,"ℕ":e=>Number.isInteger(e)&&e>0,"ℚ":Number.isFinite,"ℂ":e=>"number"==typeof e&&!Number.isNaN(e)};for(const e of[dn,gn,vn,bn,kn,pn])Object.setPrototypeOf(e,null);class qn extends Error{}class Mn extends Error{}const An={bits:2e5,factorial:2e4,terms:1e5,rootIndex:12,steps:5e6};let Nn=0,Sn=0;const On=e=>e<0n?-e:e,En=e=>0n===e?0:On(e).toString(2).length;function In(e,t){for(e=On(e),t=On(t);t;)[e,t]=[t,e%t];return e}function _n(e,t=1n){if(0n===t)throw new qn("division by zero");t<0n&&(e=-e,t=-t);const n=In(e,t)||1n;return{n:e/n,d:t/n}}const Tn=_n(0n),jn=_n(1n),zn=(e,t)=>_n(e.n*t.d+t.n*e.d,e.d*t.d),Ln=(e,t)=>_n(e.n*t.n,e.d*t.d),Cn=(e,t)=>_n(e.n*t.d,e.d*t.n),Rn=e=>({n:-e.n,d:e.d}),Zn=(e,t)=>{const n=e.n*t.d-t.n*e.d;return n<0n?-1:n>0n?1:0},Fn=e=>{const t=e.n/e.d;return e.n<0n&&t*e.d!==e.n?t-1n:t};function Pn(e){const t=En(e.n),n=En(e.d);if(t<1e3&&n<1e3)return Number(e.n)/Number(e.d);const r=BigInt(Math.max(t,n)-1e3),i=e.d>>r;return 0n===i?e.n<0n?-1/0:1/0:Number(e.n>>r)/Number(i)}function Bn(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 i=0;const s=t.search(/e/i);s>=0&&(i=Number(t.slice(s+1)),t=t.slice(0,s));const[o="",a=""]=t.split(".");if(!(/^\d*$/.test(o)&&/^\d*$/.test(a)&&o+a))throw new Mn(`'${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"),i=BigInt(n+t);l=zn(_n(BigInt(o||"0")),_n(i-r,(10n**BigInt(e)-1n)*10n**BigInt(n.length)))}else l=_n(BigInt(o+a||"0"),10n**BigInt(a.length));return i&&(l=i>0?Ln(l,_n(10n**BigInt(i))):Cn(l,_n(10n**BigInt(-i)))),n<0n?Rn(l):l}function Dn(e,t=0,n=0,r=null){return 0n===e.n?{kind:"x",c:Tn,pi:0,e:0,root:null}:{kind:"x",c:e,pi:t,e:n,root:r}}const Wn=(e,t=1n)=>Dn(_n(BigInt(e),BigInt(t))),Un=Dn(jn,1),Vn=Dn(jn,0,1),Hn=e=>null!==e&&"object"==typeof e&&"x"===e.kind,Gn=e=>Hn(e)&&!e.pi&&!e.e&&!e.root,Qn=e=>Hn(e)?0n===e.c.n:0===e,Xn=e=>Gn(e)&&1n===e.c.d?e.c.n:null,Jn=(e,t)=>Object.assign(e,{group:t}),Yn=e=>({kind:"s",text:e});function Kn(e,t){return e&&t?e.n===t.n&&e.r===t.r:e===t}const er=(e,t)=>0===Zn(e.c,t.c)&&e.pi===t.pi&&e.e===t.e&&Kn(e.root,t.root);function tr(e){if("number"==typeof e)return e;if(Hn(e)){let t=Pn(e.c);return e.pi&&(t*=Math.PI**e.pi),e.e&&(t*=Math.E**e.e),e.root&&(t*=Pn(_n(e.root.r))**(1/e.root.n)),t}if("boolean"==typeof e)return e?1:0;throw new Mn("not a number")}function nr(e,...t){if(Number.isNaN(e))throw new qn("undefined");if(!Number.isFinite(e)&&t.every(Number.isFinite))throw new Mn("too large to calculate");return e}const rr=e=>"boolean"==typeof e?e:Hn(e)?0n!==e.c.n:"number"==typeof e?0!==e:Boolean(e);function ir(e){if("bigint"==typeof e)return Dn(_n(e));if("number"==typeof e)return Number.isFinite(e)?Dn(Number.isInteger(e)&&Math.abs(e)<=Number.MAX_SAFE_INTEGER?_n(BigInt(e)):Bn(String(e))):e;if("boolean"==typeof e)return e;if("string"==typeof e)return/^-?(\d+\.?\d*|\.\d+)(\.\.)?$/.test(e.trim())?Dn(Bn(e)):Xr(nn(e),{});if(Array.isArray(e))return!e.group&&J(e)?Jn(e.map(e=>Jn(e.map(ir),"[]")),"[]"):Jn(e.map(ir),e.group||"()");if(Hn(e)||"function"==typeof e)return e;throw new Mn(`can't use ${typeof e} as a value`)}function sr(e){return Array.isArray(e)?e.map(sr):e&&"s"===e.kind?e.text:"boolean"==typeof e?e:tr(e)}function or(e,t){if(e<2n)return e;const n=BigInt(t);let r=1n<<BigInt(Math.ceil(En(e)/t));for(;;){const t=((n-1n)*r+e/r**(n-1n))/n;if(t>=r)return r;r=t}}function ar(e,t,n,r=0,i=0){if(0n===n)return Dn(Tn);const{coef:s,root:o}=function(e,t){let n=1n,r=t;const i=BigInt(e),s=r<10n**24n?1000000n:10000n;for(let e=2n;e<=s&&e*e<=r;e+=2n===e?1n:2n){const t=e**i;for(;r%t===0n;)r/=t,n*=e}const o=or(r,e);if(o**i===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 i=or(r,t);if(i**BigInt(t)===r)return{coef:n,root:{n:e/t,r:i}}}return{coef:n,root:{n:e,r:r}}}(t,n);return o&&1===o.n?Dn(Ln(e,_n(s*o.r)),r,i):Dn(Ln(e,_n(s)),r,i,o)}function lr(e,t){const n=Ln(e.c,t.c);if(En(n.n)+En(n.d)>An.bits)return null;const r=e.pi+t.pi,i=e.e+t.e;if(!e.root||!t.root)return Dn(n,r,i,e.root||t.root);const s=jr(e.root.n,t.root.n);if(s>An.rootIndex)return null;const o=e.root.r**BigInt(s/e.root.n)*t.root.r**BigInt(s/t.root.n);return En(o)>4e3?null:ar(n,s,o,r,i)}function ur(e){if(0n===e.c.n)throw new qn("division by zero");const t=Dn(Cn(jn,e.c),-e.pi,-e.e);if(!e.root)return t;const{n:n,r:r}=e.root;return lr(t,ar(_n(1n,r),n,r**BigInt(n-1)))}function cr(e,t){if(0n===t){if(0n===e.c.n)throw new qn("0^0 is undefined");return Dn(jn)}if(t<0n){const n=ur(e);return n&&cr(n,-t)}if((En(e.c.n)+En(e.c.d)+(e.root?En(e.root.r):0))*Number(t)>An.bits||t>100000n)return null;const n=_n(e.c.n**t,e.c.d**t),r=Number(t);if(!e.root)return Dn(n,e.pi*r,e.e*r);const{n:i,r:s}=e.root,o=s**(t/BigInt(i));return ar(Ln(n,_n(o)),i,s**(t%BigInt(i))||1n,e.pi*r,e.e*r)}function hr(e,t,n){if(!Gn(e)||n>1000n)return null;const r=cr(e,t);if(!r)return null;let{n:i,d:s}=r.c,o=!1;if(i<0n){if(n%2n==0n)throw new qn("not a real number");o=!0,i=-i}const a=function(e,t){const n=e.n*e.d**BigInt(t-1);return En(n)>4e3?null:ar(_n(1n,e.d),t,n)}({n:i,d:s},Number(n));return a?o?Dn(Rn(a.c),a.pi,a.e,a.root):a:null}function pr(e){return t=>Array.isArray(t)?Jn(t.map(t=>pr(e)(t)),t.group):e(t)}function fr(e){const t=(n,r)=>{const i=Array.isArray(n),s=Array.isArray(r);if(i&&s){if(n.length!==r.length)throw new qn("lists of different lengths");return Jn(n.map((e,n)=>t(e,r[n])),n.group)}return i?Jn(n.map(e=>t(e,r)),n.group):s?Jn(r.map(e=>t(n,e)),r.group):e(n,r)};return t}const dr=fr((e,t)=>Hn(e)&&Hn(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||!Kn(e.root,t.root))return null;const n=zn(e.c,t.c);return En(n.n)+En(n.d)>An.bits?null:Dn(n,e.pi,e.e,e.root)}(e,t)||nr(tr(e)+tr(t),tr(e),tr(t))),mr=pr(e=>Hn(e)?Dn(Rn(e.c),e.pi,e.e,e.root):-tr(e)),gr=(e,t)=>dr(e,mr(t)),vr=fr((e,t)=>Hn(e)&&Hn(t)&&lr(e,t)||nr(tr(e)*tr(t),tr(e),tr(t))),br=fr((e,t)=>{if(Qn(t))throw new qn("division by zero");if(Hn(e)&&Hn(t)){const n=ur(t),r=n&&lr(e,n);if(r)return r}return nr(tr(e)/tr(t),tr(e),tr(t))}),yr=fr((e,t)=>{if(Hn(e)&&Gn(t)){const{n:n,d:r}=t.c,i=1n===r?cr(e,n):hr(e,n,r);if(i)return i}const n=tr(e),r=tr(t);if(0===n&&0===r)throw new qn("0^0 is undefined");if(0===n&&r<0)throw new qn("division by zero");if(n<0&&!Number.isInteger(r))throw new qn("not a real number");return nr(n**r,n,r)});function xr(e,t){if(Gn(e)&&Gn(t))return Zn(e.c,t.c);if(Hn(e)&&Hn(t)&&er(e,t))return 0;const n=tr(e),r=tr(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 wr(e,t){return Array.isArray(e)||Array.isArray(t)?Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>wr(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===xr(e,t)}const $r={0:()=>Wn(0),2:()=>Wn(1,2),3:()=>ar(_n(1n,2n),2,2n),4:()=>ar(_n(1n,2n),2,3n),6:()=>Wn(1)};function kr(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=$r[t];return r?n<0?mr(r()):r():null}const qr=e=>kr(e+6),Mr=(e,t)=>Math.abs(e)<1e-15&&Math.abs(t)>1e-6?0:e;function Ar(e,t){const n=function(e){if(Qn(e))return 0;if(!Hn(e)||1!==e.pi||e.e||e.root)return null;const t=Ln(e.c,_n(12n));return 1n!==t.d?null:Number((t.n%24n+24n)%24n)}(t);if(null!==n){const t=kr(n),r=qr(n);if(t&&r)switch(e){case"sin":return t;case"cos":return r;case"tan":return br(t,r);case"cot":return br(r,t);case"sec":return br(Wn(1),r);case"csc":return br(Wn(1),t)}}const r=tr(t),i=Mr(Math.sin(r),r),s=Mr(Math.cos(r),r),o={sin:i,cos:s,tan:i/s,cot:s/i,sec:1/s,csc:1/i}[e];if(!Number.isFinite(o)&&Number.isFinite(r))throw new qn("undefined");return nr(o)}function Nr(e,t){const n={arcsin:[-6,6],arccos:[0,12],arctan:[-5,5]}[e],r=t=>"arcsin"===e?kr(t):"arccos"===e?qr(t):qr(t)&&!Qn(qr(t))?br(kr(t),qr(t)):null;if(Hn(t))for(let e=n[0];e<=n[1];e++){const n=r(e);if(n&&Hn(n)&&er(n,t))return Dn(_n(BigInt(e),12n),1)}const i=tr(t);if("arctan"!==e&&Math.abs(i)>1)throw new qn("not a real number");return{arcsin:Math.asin,arccos:Math.acos,arctan:Math.atan}[e](i)}function Sr(e){if(Hn(e)){if(0n===e.c.n)throw new qn("ln 0 is undefined");if(e.c.n<0n)throw new qn("not a real number");if(1n===e.c.n&&1n===e.c.d&&!e.pi&&!e.root)return Wn(e.e)}const t=tr(e);if(t<=0)throw new qn(0===t?"ln 0 is undefined":"not a real number");return Math.log(t)}function Or(e){if(e<.5)return Math.PI/(Math.sin(Math.PI*e)*Or(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 Er(e,t){const n=Xn(e)??("number"==typeof e&&Number.isInteger(e)?BigInt(e):null);if(null===n)throw new qn(`${t} needs whole numbers`);return n}const Ir=pr(e=>Gn(e)?Dn(_n(Fn(e.c))):ir(Math.floor(tr(e)))),_r=pr(e=>Gn(e)?Dn(_n(-Fn(Rn(e.c)))):ir(Math.ceil(tr(e))));function Tr(e,t){const n=Number(Er(t,"round"));if(Gn(e)){const t=_n(10n**BigInt(Math.abs(n))),r=n>=0?Ln(e.c,t):Cn(e.c,t),i=Fn(zn(Ln(_n(2n),_n(On(r.n),r.d)),jn))/2n,s=_n(r.n<0n?-i:i);return Dn(n>=0?Cn(s,t):Ln(s,t))}const r=10**n;return Math.sign(tr(e))*Math.round(Math.abs(tr(e))*r)/r}const jr=(e,t)=>e/zr(e,t)*t,zr=(e,t)=>t?zr(t,e%t):e,Lr={pi:()=>Un,"π":()=>Un,tau:()=>Dn(_n(2n),1),"τ":()=>Dn(_n(2n),1),e:()=>Vn,"∞":()=>1/0,"-∞":()=>-1/0,true:()=>!0,false:()=>!1},Cr={abs:e=>Hn(e)?Dn(_n(On(e.c.n),e.c.d),e.pi,e.e,e.root):Math.abs(tr(e)),floor:Ir,ceil:_r,sqrt:e=>yr(e,Wn(1,2)),ln:pr(Sr),loglog:pr(e=>Sr(Sr(e))),logloglog:pr(e=>Sr(Sr(Sr(e)))),expm1:pr(e=>Qn(e)?Wn(0):Math.expm1(tr(e))),sinh:pr(e=>Qn(e)?Wn(0):Math.sinh(tr(e))),cosh:pr(e=>Qn(e)?Wn(1):Math.cosh(tr(e))),tanh:pr(e=>Qn(e)?Wn(0):Math.tanh(tr(e))),arcsinh:pr(e=>Qn(e)?Wn(0):Math.asinh(tr(e))),arccosh:pr(e=>{const t=tr(e);if(t<1)throw new qn("not a real number");return 1===t?Wn(0):Math.acosh(t)}),arctanh:pr(e=>{const t=tr(e);if(Math.abs(t)>=1)throw new qn("undefined");return Qn(e)?Wn(0):Math.atanh(t)}),"!":pr(function(e){const t=Xn(e)??("number"==typeof e&&Number.isInteger(e)?BigInt(e):null);if(null!==t){if(t<0n)throw new qn("factorial of a negative number");if(t>BigInt(An.factorial))throw new Mn("too large to calculate");let e=1n;for(let n=2n;n<=t;n++)e*=n;return Dn(_n(e))}const n=tr(e);if(n<0&&Number.isInteger(n))throw new qn("factorial of a negative number");return nr(Or(n+1),n)}),neg:mr,pm:e=>Jn([e,mr(e)],"pm"),"\\not":e=>!rr(e),det:e=>Ur.det(e)};for(const e of["sin","cos","tan","csc","sec","cot"])Cr[e]=pr(t=>Ar(e,t));for(const e of["arcsin","arccos","arctan"])Cr[e]=pr(t=>Nr(e,t));const Rr=new Set(["pmatrix","bmatrix"]),Zr=e=>J(e)&&(Rr.has(e.group)||"[]"===e.group&&e.every(e=>"[]"===e.group)&&(e.length>1||e[0].length>1)),Fr=e=>Y(e)&&!Zr(e)&&"pm"!==e.group,Pr=K({add:dr,sub:gr,mul:vr,div:br,isZero:e=>Hn(e)?0n===e.c.n:Math.abs(tr(e))<1e-12,zero:()=>Wn(0),one:()=>Wn(1),size:e=>Math.abs(tr(e)),fail:e=>{throw new qn(e)},make:(e,t)=>Jn(e.map(e=>Jn(e,"[]")),t&&t.group?t.group:"bmatrix")}),Br=(e,t)=>Jn(e,t&&t.group?t.group:"[]"),Dr=(e,t)=>(...n)=>{const r=n.length>1&&n.every(Fr)?Jn(n.map(e=>Jn(e,"[]")),"[]"):n[0];if(n.length>1&&r===n[0])throw new Mn(`${e} of more than one thing`);if(!Zr(r))throw new Mn(`${e} of something that isn't a matrix`);return t(r)};function Wr(e,t){return Zr(e)&&Zr(t)?Pr.times(e,t):Zr(e)&&Fr(t)?Br(Pr.timesVector(e,t),t):Fr(e)&&Zr(t)?Br(Pr.vectorTimes(e,t),e):vr(e,t)}const Ur={det:Dr("det",Pr.det),inv:Dr("inv",Pr.inverse),inverse:Dr("inverse",Pr.inverse),transpose:Dr("transpose",Pr.transpose),trace:Dr("trace",Pr.trace),tr:Dr("tr",Pr.trace),rank:Dr("rank",e=>Wn(Pr.rank(e))),rref:Dr("rref",Pr.rref),identity:e=>{const t=Xn(e);if(null===t||t<1n||t>100n)throw new Mn("identity(n) needs a whole number n");return Pr.identity(Number(t))},dot:(e,t)=>{if(!Fr(e)||!Fr(t))throw new Mn("dot of something that isn't a vector");return Pr.dot(e,t)},cross:(e,t)=>{if(!Fr(e)||!Fr(t))throw new Mn("cross of something that isn't a vector");return Br(Pr.cross(e,t),e)},linsolve:(e,t)=>{if(!Zr(e)||!Zr(t)&&!Fr(t))throw new Mn("linsolve(A, b) needs a matrix and a vector");return Zr(t)?Pr.solve(e,t):Br(Pr.solve(e,t),t)}};function Vr(e,t){const n=e.args.map(e=>Jn("op"===e.type&&"[]"===e.op?e.args.map(t):[t(e)],"[]"));if(n.some(e=>e.length!==n[0].length))throw new qn("rows of different lengths");return Jn(n,"vmatrix"===e.op?"bmatrix":e.op)}const Hr={"+":dr,"-":gr,"*":Wr,"/":(e,t)=>Zr(t)?Wr(e,Pr.inverse(t)):br(e,t),"^":function(e,t){if(!Zr(e))return yr(e,t);const n=Xn(t);if(null===n)throw new Mn("a matrix to a power that is not a whole number");return Pr.power(e,n)},"±":(e,t)=>Jn([dr(e,t),gr(e,t)],"pm"),mod:fr(function(e,t){if(Qn(t))throw new qn("division by zero");if(Gn(e)&&Gn(t))return Dn(zn(e.c,Rn(Ln(t.c,_n(Fn(Cn(e.c,t.c)))))));const n=tr(e),r=tr(t);return nr((n%r+r)%r)}),log:fr(function(e,t){if(Hn(e)&&er(e,Vn))return Sr(t);const n=tr(e),r=tr(t);if(n<=0||1===n)throw new qn("not a valid base");if(r<=0)throw new qn(0===r?"log 0 is undefined":"not a real number");const i=Math.log(r)/Math.log(n);if(Gn(e)&&Gn(t))for(let n=1n;n<=12n;n++){const r=Math.round(i*Number(n));if(Math.abs(i*Number(n)-r)>1e-9)continue;const s=cr(e,BigInt(r)),o=cr(t,n);if(s&&o&&er(s,o))return Dn(_n(BigInt(r),n))}return i}),root:fr((e,t)=>yr(t,br(Wn(1),e))),atan2:(e,t)=>Math.atan2(tr(e),tr(t)),round:Tr,fixed:function(e,t){const n=Number(Er(t,"fixed"));if(n<0)throw new qn("fixed needs 0 or more decimal places");const r=Tr(e,t);if(Gn(r)){const e=r.c.n*10n**BigInt(n)/r.c.d,t=(e<0n?-e:e).toString().padStart(n+1,"0");return Yn(`${e<0n?"-":""}${t.slice(0,t.length-n)}${n?"."+t.slice(-n):""}`)}return Yn(Number(tr(r)).toFixed(n))},perm:function(e,t){const n=Er(e,"permutations"),r=Er(t,"permutations");if(r<0n||r>n)throw new qn("undefined");if(r>BigInt(An.terms))throw new Mn("too large to calculate");let i=1n;for(let e=n-r+1n;e<=n;e++)i*=e;return Dn(_n(i))},comb:function(e,t){const n=Er(e,"combinations");let r=Er(t,"combinations");if(r<0n||r>n)throw new qn("undefined");if(n-r<r&&(r=n-r),r>BigInt(An.terms))throw new Mn("too large to calculate");let i=1n;for(let e=1n;e<=r;e++)i=i*(n-r+e)/e;return Dn(_n(i))},"=":(e,t)=>wr(e,t),"===":(e,t)=>wr(e,t),"≠":(e,t)=>!wr(e,t),"≠=":(e,t)=>!wr(e,t),"≈":(e,t)=>Math.abs(tr(e)-tr(t))<=1e-9*Math.max(1,Math.abs(tr(e)),Math.abs(tr(t))),"<":(e,t)=>xr(e,t)<0,">":(e,t)=>xr(e,t)>0,"≤":(e,t)=>xr(e,t)<=0,"≥":(e,t)=>xr(e,t)>=0,"&":(e,t)=>rr(e)&&rr(t),"|":(e,t)=>rr(e)||rr(t),"\\xor":(e,t)=>rr(e)!==rr(t),"\\nor":(e,t)=>!(rr(e)||rr(t)),"\\nand":(e,t)=>!(rr(e)&&rr(t))},Gr={sum:e=>e.reduce((e,t)=>dr(e,t),Wn(0)),prod:e=>e.reduce((e,t)=>vr(e,t),Wn(1)),max:e=>e.reduce((e,t)=>xr(t,e)>0?t:e),min:e=>e.reduce((e,t)=>xr(t,e)<0?t:e),mean:e=>br(Gr.sum(e),Wn(e.length)),gcd:e=>Dn(_n(e.map(e=>Er(e,"gcd")).reduce(In)))},Qr=["∈","∉","∪","∩","pmod","random","(]","[)"];function Xr(e,t){if(++Nn>An.steps)throw new Mn("too much to work out");switch(e.type){case"number":return Dn(Bn(e.value));case"string":return Yn(e.value.slice(1,-1));case"symbol":return Jr(e.value,t)}const n=G(e);if(n)return Xr(n,t);const{op:r,args:i}=e,s=e=>Xr(e,t);if("?:"===r)return rr(s(i[0]))?s(i[1]):s(i[2]);if("_"===r){if(i.every(e=>"op"!==e.type))return Jr(`${i[0].value}_${i[1].value}`,t);throw new Mn("subscript")}if("der"===r)return function(e,t){const[n,r]=e.args,i=Kr(r);if(!i||!Object.prototype.hasOwnProperty.call(t,i))throw new Mn(`a derivative needs a value for ${i||"its variable"}`);const s=tr(t[i]),o=Yr(n,i,t);if(!Number.isFinite(o(s)))throw new qn("undefined");const a=1e-6*Math.max(1,Math.abs(s)),l=(o(s+a)-o(s))/a,u=(o(s)-o(s-a))/a;if(!Number.isFinite(l)||!Number.isFinite(u)||Math.abs(l-u)>.001*Math.max(1,Math.abs(l)))throw new qn("not differentiable here");let c=.1*Math.max(1,Math.abs(s));const h=1.4,p=[[(o(s+c)-o(s-c))/(2*c)]];let f=p[0][0],d=1/0;for(let e=1;e<12;e++){c/=h,p[e]=[(o(s+c)-o(s-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<=d&&(d=r,f=p[e][n])}if(Math.abs(p[e][e]-p[e-1][e-1])>=2*d)break}if(!Number.isFinite(f))throw new qn("not differentiable here");return ri(f,d)}(e,t);if("int"===r)return function(e,t){const[n,r,i,s]=e,o=e=>e&&"symbol"===e.type&&/^[a-zA-Zʹ-Ͽ]$/.test(e.value);let a,l,u;if(4===e.length)[a,l,u]=[Kr(r),i,s];else{if(3!==e.length||o(r))throw new Mn("an integral needs limits to be calculated");[a,l,u]=[S(n)||"x",r,i]}let c=tr(Xr(l,t)),h=tr(Xr(u,t));if(c===h)return Wn(0);let p=1;c>h&&([c,h]=[h,c],p=-1);const f=Yr(n,a,t),{value:d,error:m}=ei(f,c,h);return ri(p*d,m)}(i,t);if("lim"===r)return function(e,t){const[n,r,i,s]=e;let o,a,l=0;if(2===e.length&&"op"===r.type&&"→"===r.op)[o,a]=[Kr(r.args[0]),r.args[1]];else if(2===e.length)[o,a]=[S(n),r];else{if(!(e.length>=3))throw new Mn("a limit needs a point");[o,a]=[Kr(r),i]}if(4===e.length){const e="op"===s.type?"":String(s.value).toLowerCase();l=e.startsWith("r")||"+"===e?1:-1}if(!o)throw new Mn("a limit needs a variable");const u=Xr(a,t),c=tr(u),h=Yr(n,o,t);let p,f;if(Number.isFinite(c))if(l)({value:p,error:f}=ni(e=>h(c+l*e*Math.max(1,Math.abs(c)))));else{const e=ni(e=>h(c+e*Math.max(1,Math.abs(c)))),r=ni(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 qn("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=Xr(n,{...t,[o]:u});if(Math.abs(tr(e)-p)<=1e-6*Math.max(1,Math.abs(p)))return e}catch(e){if(!(e instanceof qn))throw e}}else({value:p,error:f}=ni(e=>h(Math.sign(c)/e)));return Number.isFinite(p)?ri(p,f):p}(i,t);if("\\sumidx"===r||"\\prodidx"===r)return function(e,t,n){const[r,i,s]=t;if(t.length<3)throw new Mn("a sum needs its limits");let o,a=i;"op"===i.type&&"="===i.op&&"symbol"===i.args[0].type?[o,a]=[i.args[0].value,i.args[1]]:o=S(r)||"n";const l=Er(Xr(a,n),"a sum"),u=Xr(s,n),c=e?dr:vr;if(u===1/0){if(!e)throw new Mn("an infinite product");return function(e,t){const n=[],r=[];let i=0,s=t;for(let o=4;o<=17;o++){const a=2**o;for(;s<t+a;s++){const t=e(s);if(!Number.isFinite(t))throw new qn("undefined");i+=t}if(n.push(a),r.push(i),o>=6&&r[r.length-1]===r[r.length-2])return ri(i,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 qn("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 ri(p,Math.abs(p-f))}(Yr(r,o,n),Number(l))}const h=Er(u,"a sum");if(h-l+1n>BigInt(An.terms))throw new Mn("too many terms to add one by one");let p=Wn(e?0:1);for(let e=l;e<=h;e++)p=c(p,Xr(r,{...n,[o]:Dn(_n(e))}));return p}("\\sumidx"===r,i,t);if(["()","[]","{}"].includes(r))return Jn(i.map(s),r);if("pmatrix"===r||"bmatrix"===r)return Vr(e,s);if("vmatrix"===r)return Pr.det(Vr(e,s));if("^"===r&&"symbol"===i[1].type&&"T"===i[1].value&&!Object.prototype.hasOwnProperty.call(t,"T")){const e=s(i[0]);if(Zr(e))return Pr.transpose(e)}if(Qr.includes(r))return function(e,t){const n={};for(const[e,r]of Object.entries(t))"function"!=typeof r&&(n[e]=sr(r));try{return ir(function(e,t={}){0===wn&&(xn=0),wn++;try{return $n(rn(e),t)}finally{wn--}}(e,n))}catch(e){throw new Mn(e.message)}}(e,t);if(r.startsWith("\\:")){const e=r.slice(2);if("function"!=typeof t[e]&&Object.prototype.hasOwnProperty.call(Ur,e))return Ur[e](...i.map(s));const n=t[e];if("function"!=typeof n)throw new Mn(`no function ${r.slice(2)}`);return ir(n(...i.map(e=>sr(s(e)))))}if(Cr[r]&&1===i.length)return Cr[r](s(i[0]));if(Hr[r]&&2===i.length)return Hr[r](s(i[0]),s(i[1]));if(Gr[r])return Gr[r](i.map(s));throw new Mn(`can't calculate '${r}'`)}function Jr(e,t){if(Object.prototype.hasOwnProperty.call(t,e))return t[e];if(Object.prototype.hasOwnProperty.call(Lr,e))return Lr[e]();throw new Mn(`no value for '${e}'`)}function Yr(e,t,n){return r=>{try{return tr(Xr(e,{...n,[t]:r}))}catch(e){if(e instanceof qn)return NaN;throw e}}}const Kr=e=>"symbol"===e.type?e.value:null;function ei(e,t,n){if(t===-1/0&&n===1/0){const t=ei(e,-1/0,0),n=ei(e,0,1/0);return{value:t.value+n.value,error:t.error+n.error}}return n===1/0?ti(n=>e(t+n/(1-n))/((1-n)*(1-n)),0,1):t===-1/0?ti(t=>e(n-t/(1-t))/((1-t)*(1-t)),0,1):ti(e,t,n)}function ti(e,t,n){const r=(n-t)/2;let i=1,s=0,o=NaN,a=NaN,l=0;const u=i=>{const s=Math.PI/2*Math.sinh(Math.abs(i)),o=Math.exp(-2*s),a=2*r*o/(1+o),u=r*(Math.PI/2)*Math.cosh(i)*(4*o)/((1+o)*(1+o));if(0===a||0===u)return 0;const c=i>0?n-a:t+a;if(0!==i&&(c<=t||c>=n))return 0;const h=e(0===i?(t+n)/2:c);if(!Number.isFinite(h)){if(a<1e-6*r)return 0;throw new qn("the integral diverges")}return Math.abs(i)>3.5&&(l=Math.max(l,Math.abs(u*h))),u*h};s=u(0);for(let e=i;e<=4;e+=i)s+=u(e)+u(-e);o=i*s;for(let e=1;e<=8;e++){i/=2;for(let e=i;e<=4;e+=2*i)s+=u(e)+u(-e);a=o,o=i*s;const t=Math.max(1,Math.abs(o));if(l>1e-8*t)throw new qn("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 qn("the integral does not converge");return{value:o,error:c}}function ni(e){const t=[],n=[];for(let r=0;r<30;r++){const i=.1/2**r,s=e(i);Number.isFinite(s)&&(t.push(i),n.push(s))}if(n.length<6)throw new qn("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 i=e=>{const r=t.slice(e,e+8),i=n.slice(e,e+8);for(let e=1;e<r.length;e++)for(let t=0;t<r.length-e;t++)i[t]=(r[t+e]*i[t]-r[t]*i[t+1])/(r[t+e]-r[t]);return i[0]};let s=null;for(let e=0;e+9<=n.length;e++){const t=i(e),n=i(e+1),r=Math.abs(t-n);Number.isFinite(t)&&(!s||r<s.error)&&(s={value:t,error:r})}const o=n[n.length-1],a=Math.abs(o-n[n.length-2]);if(!s||s.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 qn("the limit could not be found")}return s}function ri(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 Wn(0);const r=[[Wn(1),1e3],[Un,100],[Dn(jn,2),100],[Vn,100],...[2n,3n,5n,6n,7n].map(e=>[Dn(jn,0,0,{n:2,r:e}),100])];for(const[t,i]of r){const r=e/tr(t),s=ii(r,i);if(s&&Math.abs(Number(s.n)/Number(s.d)-r)*tr(t)<=n)return lr(Dn(s),t)}return e}function ii(e,t){if(!Number.isFinite(e)||Math.abs(e)>1e12)return null;let[n,r,i,s]=[0,1,1,0],o=e;for(let e=0;e<40;e++){const e=Math.floor(o),a=e*r+n,l=e*s+i;if(l>t)break;if([n,r,i,s]=[r,a,s,l],Math.abs(o-e)<1e-15)break;o=1/(o-e)}return s?_n(BigInt(r),BigInt(s)):null}function si(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&&wr(e[1],mr(e[0])))return`±${oi(e[0],t)}`;if(Rr.has(e.group)&&J(e))return`${e.group}(${e.map(e=>`[${e.map(e=>si(e,t)).join(", ")}]`).join(", ")})`;const[n,r]={"()":"()","[]":"[]","{}":"{}"}[e.group]||"{}";return n+e.map(e=>si(e,t)).join(", ")+r}return"number"==typeof e?ai(e,t):t.decimal||null!==t.places?function(e,t){if(Gn(e)&&null===t.places){let n=e.c.d,r=0,i=0;for(;n%2n==0n;)n/=2n,r++;for(;n%5n==0n;)n/=5n,i++;const s=Math.max(r,i);if(1n===n&&s<=t.digits){const n=e.c.n*10n**BigInt(s)/e.c.d,r=n<0n,i=On(n).toString().padStart(s+1,"0"),o=s?`${i.slice(0,-s)}.${i.slice(-s)}`:i;if(i.length<=t.maxDigits)return(r?"-":"")+li(o)}}return Gn(e)&&null!==t.places?si(Tr(e,Wn(t.places)),{...t,places:null,decimal:!0}):ai(tr(e),t)}(e,t):function(e,t){const{c:n}=e,r=On(n.n);if(r.toString().length>t.maxDigits||n.d.toString().length>t.maxDigits)return function(e,t){if(!Gn(e)||1n!==e.c.d)return ai(tr(e),t);const n=On(e.c.n).toString(),r=BigInt(n.slice(0,t.digits+1)),i=((r+5n)/10n).toString(),s=n.length-1+(i.length>t.digits?1:0),o=li(`${i[0]}.${i.slice(1,t.digits)}`);return`${e.c.n<0n?"-":""}${o}*10^(${s})`}(e,t);const i=(e,t)=>1===t?e:`${e}^${t}`,s=[],o=[];e.pi>0&&s.push(i("pi",e.pi));e.pi<0&&o.push(i("pi",-e.pi));e.e>0&&s.push(i("e",e.e));e.e<0&&o.push(i("e",-e.e));e.root&&s.push(2===e.root.n?`sqrt(${e.root.r})`:`root(${e.root.n}, ${e.root.r})`);1n===r&&s.length||s.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(s)}/${a(o)}`:s.join("*");return(n.n<0n?"-":"")+l}(e,t)}const oi=(e,t)=>{const n=si(e,t);return/^[\d.]+$|^[a-zπ]+$/i.test(n)?n:`(${n})`};function ai(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`${li(n)}*10^(${Number(r)})`}return String(Number(e.toPrecision(t.digits)))}const li=e=>e.includes(".")?e.replace(/\.?0+$/,""):e;function ui(e,t={},n={}){const r="string"==typeof e?nn(e):A(e),i={};for(const[e,n]of Object.entries(t))i[e]=ir(n);let s;0===Sn&&(Nn=0),Sn++;try{s=Xr(r,i)}finally{Sn--}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:sr(s),text:si(s,o),exact:a(s)}}function ci(e,t={}){let n=e.trim();const r={},i=/^(~|≈)\s*(\d+)?/.exec(n);i&&(r.decimal=!0,void 0!==i[2]&&(r.places=Number(i[2])),n=n.slice(i[0].length)),/\d\.\d|\.\d/.test(n)&&(r.decimal=!0);try{const{text:e}=ui(n,t,r);return e.startsWith('"')||/^\d+(\.\d+)?$/.test(e)?e:`(${e})`}catch(e){if(e instanceof qn)return'"undefined"';if(e instanceof Mn)return`(${n})`;throw e}}Kt=ci;for(const e of[An,$r,Lr,Cr,Hr,Gr])Object.setPrototypeOf(e,null);Object.setPrototypeOf(Ur,null);const hi={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",matrix:(e,t)=>`the ${e} by ${t} matrix`,row:e=>`row ${e}`,determinantOf:"the determinant 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",endQuantity:"end quantity",endFraction:"end fraction",endRoot:"end root",endExponent:"end exponent",endSub:"end sub",endAbsoluteValue:"end absolute value",endFloor:"end floor",endCeiling:"end ceiling",endLimit:"end limit",endSum:"end sum",endMatrix:"end matrix",endProduct:"end product",endDerivative:"end derivative",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"]},pi={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",det:"the determinant",atan2:"the arctangent",round:"round",fixed:"fixed",random:"random"},fi=Object.fromEntries(Object.entries(O).map(([e,t])=>[t,e]));function di(e,t={}){return gi(function(e,t={}){return mi(e,t,!0)}(e,t))}function mi(e,t,n){return function(e){let t=e.length;for(;t>0&&(e[t-1].close||!e[t-1].text.replace(/,/g,"").trim());)t--;const n=[];for(const{text:r,id:i}of e.slice(0,t)){const e=r.trim();if(!e)continue;const t=e.startsWith(","),s=t?e.slice(1).trim():e;t&&n.length&&!n[n.length-1].text.endsWith(",")&&(n[n.length-1].text+=","),s&&n.push({text:s,id:i})}n.length&&(n[n.length-1].text=n[n.length-1].text.replace(/,$/,""));return n}(new yi({...hi,...t.words},{...pi,...t.names},t.say||{},n).speak(e))}function gi(e){return e.map(e=>e.text).join(" ").replace(/\s+/g," ").replace(/ ,/g,",").replace(/,(\s*,)+/g,",").replace(/^,\s*/,"").replace(/,\s*$/,"").trim()}const vi={"=":"equals","===":"equals","≠":"notEqual","≠=":"notEqual","<":"lessThan",">":"greaterThan","≤":"lessOrEqual","≥":"greaterOrEqual","≈":"approx","≡":"congruent","→":"tendsTo","∈":"isIn","∉":"isNotIn","∪":"union","∩":"intersect","±":"plusOrMinus","&":"and","|":"or","\\xor":"xor","\\nand":"nand","\\nor":"nor"},bi={"ℝ":"reals","ℤ":"integers","ℕ":"naturals","ℚ":"rationals","ℂ":"complexes"};class yi{constructor(e,t,n,r=!1){this.w=e,this.names=t,this.say=n,this.audio=r}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=>gi(this.speak(e))):[e.value],e,e=>gi(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(bi[e])return t[bi[e]];if(fi[e])return fi[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,t="endQuantity"){return this.isCompound(e)?[this.seg(e,this.w.quantity),...this.speak(e),...this.closer(e,t)]:this.speak(e)}closer(e,t){const n=this.seg(e,this.w.comma);return this.audio&&t?[n,{text:this.w[t],id:e.id,close:!0},n]:[n]}contents(e,t){return this.audio&&this.isCompound(e)?this.quantity(e,t):[...this.speak(e),...this.pauseAfter(e)]}argument(e){return this.quantity(e)}operation(e){const{op:t,args:n}=e,[r,i]=n,s=this.w,a=t=>this.seg(e,t),l=()=>n.flatMap((e,t)=>t?[a(s.comma),...this.speak(e)]:this.speak(e));if(vi[t])return[...this.speak(r),a(s[vi[t]]),...this.speak(i)];if(o(t)){const e=this.symbol(W(t));return n.length?[a(`${e} ${s.of}`),...this.arguments(n)]:[a(e)]}if(this.names[t]&&!["log","round","fixed","atan2","random","expm1"].includes(t))return[a(`${this.names[t]} ${s.of}`),...this.arguments(n)];switch(t){case"+":return I(i)?[...this.speak(r),a(s.minus),...this.speak(i.args[1])]:[...this.speak(r),a(s.plus),...this.speak(i)];case"-":return I(i)?[...this.speak(r),a(s.plus),...this.speak(i.args[1])]:[...this.speak(r),a(s.minus),...this.quantityIfSum(i)];case"*":return this.product(e);case"/":return this.fraction(e);case"^":return this.power(e);case"_":return[...this.speak(r),a(s.sub),...this.audio?this.quantity(i,"endSub"):this.speak(i)];case"neg":return this.isCompound(r)||"op"===r.type&&"neg"===r.op?[a(`${s.negative} ${s.quantity}`),...this.speak(r),...this.closer(r,"endQuantity")]:[a(s.negative),...this.speak(r)];case"pm":return[a(s.plusOrMinus),...this.speak(r)];case"!":return[...this.quantity(r),a(s.factorial)];case"\\not":return[a(s.not),...this.quantity(r)];case"sqrt":return[a(s.squareRoot),...this.contents(r,"endRoot")];case"root":{const e="number"===r.type?Number(r.value):NaN,t=3===e?s.cubeRoot:2===e?s.squareRoot:s.nthRoot(e?this.ordinal(e):gi(this.speak(r))+"th");return[a(t),...this.contents(i,"endRoot")]}case"abs":return[a(s.absoluteValue),...this.contents(r,"endAbsoluteValue")];case"floor":return[a(s.floor),...this.contents(r,"endFloor")];case"ceil":return[a(s.ceiling),...this.contents(r,"endCeiling")];case"log":return"symbol"===r.type&&"e"===r.value?[a(`${this.names.ln} ${s.of}`),...this.argument(i)]:[a(`${s.logBase}`),...this.speak(r),a(s.of),...this.argument(i)];case"mod":return[...this.quantity(r),a(s.mod),...this.quantity(i)];case"pmod":return[...this.speak(r),a(`${s.comma} ${s.mod}`),...this.speak(i)];case"perm":return[...this.quantity(r),a(s.permute),...this.quantity(i)];case"comb":return[...this.quantity(r),a(s.choose),...this.quantity(i)];case"round":{const e=0===("number"===i.type?Number(i.value):NaN)?s.nearestWholeNumber:`${gi(this.speak(i))} ${s.decimalPlaces}`;return[...this.speak(r),a(`${s.comma} ${s.rounded} ${e}`)]}case"fixed":return 0===("number"===i.type?Number(i.value):NaN)?[...this.speak(r),a(`${s.comma} ${s.asWholeNumber}`)]:[...this.speak(r),a(`${s.comma} ${s.writtenTo}`),...this.speak(i),a(s.decimalPlaces)];case"atan2":return[a(`${this.names.atan2} ${s.of}`),...this.speak(r),a(s.over),...this.speak(i)];case"random":return[a(s.randomNumber)];case"expm1":return[a(s.eToThe),...this.speak(r),a(`${s.comma} ${s.minus} 1`)];case"?:":{const e=[a(s.if),...this.speak(r),a(`${s.comma} ${s.then}`),...this.speak(i)];return(e=>"symbol"===e.type&&"unchanged"===e.value)(n[2])?e:[...e,a(`${s.comma} ${s.otherwise}`),...this.speak(n[2])]}case"sum":return n.flatMap((e,t)=>t?[a(s.plus),...this.speak(e)]:this.speak(e));case"prod":return n.flatMap((e,t)=>t?[a(s.times),...this.quantity(e)]:this.quantity(e));case"mean":case"max":case"min":case"gcd":return[a(`${this.names[t]} ${s.of}`),...l()];case"()":return 2===n.length?[a(s.openInterval),...this.speak(r),a(s.to),...this.speak(i)]:l();case"pmatrix":case"bmatrix":return this.matrix(e);case"vmatrix":return[a(s.determinantOf),...this.matrix(e)];case"[]":return X(e)?this.matrix(e):2===n.length?[a(s.closedInterval),...this.speak(r),a(s.to),...this.speak(i)]:[a(s.theList),...l()];case"(]":case"[)":return[a(s.halfOpenInterval),...this.speak(r),a(s.to),...this.speak(i)];case"{}":return[a(s.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,s.sumFrom,s.sumOver,s.sumOf,"endSum");case"\\prodidx":return this.bigOperator(e,s.productFrom,s.productOver,s.productOf,"endProduct")}throw new Error(`No speech for '${t}'`)}matrix(e){const t=this.w,n=X(e),r=[this.seg(e,t.matrix(n.length,n[0].length))];return n.forEach((n,i)=>{const s=e.args[i];r.push(this.seg(e,t.comma),this.seg("op"===s.type&&"[]"===s.op?s:e,`${t.row(i+1)}:`)),n.forEach((n,i)=>r.push(...i?[this.seg(e,t.comma)]:[],...this.speak(n)))}),[...r,...this.closer(e,"endMatrix")]}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 i=this.quantity(t),s=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)||s[0].text.startsWith("the ")?[...i,this.seg(e,r.times),...s]:[...i,...s]}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,i=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),s=Number(n.value),o=2===s?1===e?r.half:r.halves:r.ordinals[s]+(1===e?"":"s");return[i(`${r.numerators[e]} ${o}`)]}return[...this.quantity(t,null),...this.isCall(t)?[i(r.comma)]:[],i(r.over),...this.quantity(n,"endFraction")]}power(e){const[t,n]=e.args,r=this.w,i=t=>this.seg(e,t),s=this.isCompound(t)||this.isCall(t)||"number"===t.type&&t.value.startsWith("-")||"op"===t.type&&"/"===t.op||this.audio&&"op"===t.type&&"^"===t.op?[i(r.quantity),...this.speak(t),...this.closer(t,"endQuantity")]: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[i(`${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?[...s,i(r.powers[e])]:[...s,i(`${r.toThe} ${r.powers[e]}`)]}if("number"===n.type&&/^\d+$/.test(n.value))return[...s,i(`${r.toThe} ${this.ordinal(Number(n.value))}`)];return!(this.isCompound(n)||"op"===n.type&&"/"===n.op&&this.isCompound(n.args[0]))?[...s,i(r.toThe),...this.speak(n)]:this.audio?[...s,i(r.toThePowerOf),i(r.quantity),...this.speak(n),...this.closer(n,"endExponent")]:[...s,i(r.toThePowerOf),...this.speak(n),i(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:i}=U(e),s=this.w,o=t=>this.seg(e,t);if(i){return[o(1===t?s.d:`${s.d} ${2===t?s.squared:3===t?s.cubed:`${s.toThe} ${this.ordinal(t)}`}`),...this.speak(n),o(s.d),...this.speak(r),o(1===t?"":2===t?s.squared:3===t?s.cubed:`${s.toThe} ${this.ordinal(t)}`)]}return[o(`${1===t?s.derivative:2===t?s.secondDerivative:s.nthDerivative(this.ordinal(t))} ${s.withRespectTo}`),...this.speak(r),o(s.of),...this.contents(n,"endDerivative")]}integral(e){const{args:t}=e,[n,r,i,s]=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(S(n)||"x")];let c=[];4===t.length?c=[i,s]:3===t.length?c=l?[i]:[r,i]: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,i,s]=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(i)],4===t.length){const e=String(s.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=S(n);l=e?[a(e),a(o.approaches),...this.speak(r)]:this.speak(r)}}return[a(o.limitAs),...l,a(o.of),...this.contents(n,"endLimit")]}bigOperator(e,t,n,r,i){const{args:s}=e,[o,a,l]=s,u=this.w,c=t=>this.seg(e,t);let h;return h=3===s.length?[c(t),...this.speak(a),c(u.to),...this.speak(l),c(u.of)]:2===s.length?[c(n),...this.speak(a),c(u.of)]:[c(r)],[...h,...this.contents(o,i)]}}for(const e of[hi,pi,vi,bi,fi])Object.setPrototypeOf(e,null);function xi(e,t={}){return sn(e)?[]:function(e,t={}){return mi(e,t,!1)}(rn(e),t)}function wi(e,t={}){return sn(e)?"":di(rn(e),t)}const $i={"(":{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"},cancel:{stroke:"M0,1 L1,0"},int:{stroke:"M0.95,0.09 C0.9,0.01 0.72,0 0.66,0.12 C0.6,0.25 0.42,0.75 0.34,0.88 C0.28,0.99 0.1,0.99 0.05,0.91"},sum:{fill:"M0.04,0 L0.94,0 L0.98,0.24 L0.94,0.24 C0.9,0.1 0.8,0.07 0.62,0.07 L0.24,0.07 L0.58,0.5 L0.2,0.93 L0.64,0.93 C0.82,0.93 0.92,0.9 0.95,0.76 L0.99,0.76 L0.94,1 L0.02,1 L0.47,0.47 Z"},prod:{fill:"M0,0 L1,0 L1,0.04 L0.88,0.05 L0.88,0.95 L1,0.96 L1,1 L0.62,1 L0.62,0.96 L0.74,0.95 L0.74,0.06 L0.26,0.06 L0.26,0.95 L0.38,0.96 L0.38,1 L0,1 L0,0.96 L0.12,0.95 L0.12,0.05 L0,0.04 Z"}};function ki(e,t,n=""){const r=$i[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 qi=.8,Mi=.2,Ai=.25,Ni=.7,Si="−",Oi={"+":"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",pmatrix:"matrix",bmatrix:"matrix",vmatrix:"matrix"},Ei={"=":"=","===":"=","≠":"≠","≠=":"≠","<":"<",">":">","≤":"≤","≥":"≥","∈":"∈","∉":"∉","→":"→","≈":"≈","≡":"≡","&":"∧","|":"∨","\\xor":"⊕","\\nand":"↑","\\nor":"↓"},Ii={"±":"±","∪":"∪","∩":"∩",mod:"mod"},_i=["sin","cos","tan","csc","sec","cot","sinh","cosh","tanh"],Ti={arcsin:"sin",arccos:"cos",arctan:"tan",arcsinh:"sinh",arccosh:"cosh",arctanh:"tanh"},ji=[..._i,...Object.keys(Ti),"ln","det"],zi={atan2:"atan2",max:"max",min:"min",gcd:"gcd",mean:"mean",round:"round",fixed:"fixed",expm1:"expm1",random:"random"},Li={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]},Ci={"\\partial":"∂","\\nabla":"∇","\\ell":"ℓ","\\infty":"∞","\\emptyset":"∅"},Ri={vec:"→",hat:"ˆ",widehat:"ˆ",tilde:"˜",dot:"˙",ddot:"¨"},Zi=["boxed","overline","bar","underline","cancel",...Object.keys(Ri)],Fi={prefix:"mv",display:!0,fnParens:"auto",trigPowers:!0,inverseTrig:"arc",derivativeBrackets:"[",scriptFractions:"slash",cases:!0,label:!0,mathml:null,attributes:null,style:null},Pi=e=>String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),Bi=e=>+e.toFixed(3)+"em",Di=(e,t=qi,n=Mi)=>({html:e,h:t,d:n});function Wi(...e){const t=e.flat().filter(Boolean);return{html:t.map(e=>e.html).join(""),h:Math.max(qi,...t.map(e=>e.h)),d:Math.max(Mi,...t.map(e=>e.d))}}function Ui(e,t={}){const n=new Vi({...Fi,...t}),r=n.render(e,{level:0}),i=`${n.p}${n.o.display?` ${n.p}-display`:""}`,s="function"==typeof n.o.mathml?function(e,t,n,r){try{return String(e(t)).replace(/ id="mz-\d+"/g,"").replace(/^<math>/,`<math class="${n}-sr-math"${r?' display="block"':""}>`)}catch{return""}}(n.o.mathml,e,n.p,n.o.display):"",o=s?null:function(e,t){if(!1===t||null===t)return null;if("string"==typeof t)return t;try{return"function"==typeof t?t(e):wi(e)}catch{return null}}(e,n.o.label),a=null!==o||s?r.html.replace(/^<span /,'<span aria-hidden="true" '):r.html;return{html:`<span class="${i}"${null===o?"":` role="math" aria-label="${Pi(o)}"`}>${a}${s}</span>`,h:r.h,d:r.d}}class Vi{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=Di(this.el(e,Pi(t)));return n.leaf={kind:e,content:Pi(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="${Pi(e.op)}"`);const i=this.o.attributes&&this.o.attributes(e)||{};for(const[e,t]of Object.entries(i))"class"!==e&&"style"!==e&&(r+=` ${e}="${Pi(t)}"`);const s=[i.style,this.o.style&&this.o.style(e)].filter(Boolean).join(";"),o=(n.leaf?["n",...t,n.leaf.kind]:["n",...t]).map(e=>`${this.p}-${e}`).concat(i.class?[i.class]:[]).join(" "),a=n.leaf?n.leaf.content:n.html;return{html:`<span class="${o}"${s?` style="${Pi(s)}"`:""}${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(/^-/,Si)))}symbol(e){return O[e]&&(e=O[e]),Ci[e]?this.text("ord",Ci[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)?Di(this.el("var",Pi(e[0]))+this.el("prime",Pi(e.slice(1)))):/^Δ[A-Za-z]$/.test(e)?Di(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,[i,s]=r,a=(e,n={})=>this.render(e,{...t,...n,forceParens:n.forceParens||!1,before:n.before||!1}),l=Oi[n]??(/^[a-z0-9]+$/i.test(n)?n:"other"),u=t=>this.wrap(e,["op",`op-${l}`],t),c=(t,n)=>j(e,t,n)&&"/"!==t.op?this.fence(a(t)):a(t);if(ji.includes(n)||"log"===n)return u(this.named(e,t));if(zi[n])return u(Wi(this.word(zi[n]),this.fence(this.list(r,t))));if(o(n))return u(this.custom(e,t));const h=X(e);if(h)return u(this.matrix(e,h,t));if(Li[n])return u(this.fence(this.list(r,t),...Li[n]));if(Ei[n]&&2===r.length)return u(Wi(c(i,"left"),this.rel(Ei[n]),c(s,"right")));if(Ii[n]&&2===r.length)return u(Wi(c(i,"left"),this.bin(Ii[n]),c(s,"right")));switch(n){case"+":return I(s)?u(Wi(c(i,"left"),this.bin(Si),this.wrap(s,["op","op-mul"],this.render(s.args[1],t)))):"number"===s.type&&s.value.startsWith("-")?u(Wi(c(i,"left"),this.bin(Si),this.wrap(s,["number"],this.text("num",s.value.slice(1))))):u(Wi(c(i,"left"),this.bin("+"),this.signed(s,c(s,"right"))));case"-":return u(Wi(c(i,"left"),this.bin(Si),this.signed(s,c(s,"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(i,{forceParens:!0}),null,t,a(s,{level:t.level+1})));case"neg":return u(Wi(this.text("sign",Si),z(n,i)?this.fence(a(i)):a(i,{before:t.before})));case"pm":return u(Wi(this.text("sign","±"),z(n,i)?this.fence(a(i)):a(i)));case"!":return u(Wi(z(n,i)?this.fence(a(i)):a(i,{forceParens:!0}),this.text("ord","!")));case"\\not":return u(Wi(this.text("sign","¬"),z(n,i)?this.fence(a(i)):a(i)));case"pmod":return u(Wi(a(i),this.fence(Wi(this.word("mod"),this.text("space",""),a(s)))));case"sqrt":return u(this.radical(a(i)));case"root":return u(this.radical(a(s),this.render(i,{level:t.level+2})));case"abs":return u(this.fence(a(i),"|","|"));case"floor":return u(this.fence(a(i),"⌊","⌋"));case"ceil":return u(this.fence(a(i),"⌈","⌉"));case"loglog":return u(Wi(this.word("ln"),this.fence(Wi(this.word("ln"),this.fence(a(i))))));case"logloglog":return u(Wi(this.word("ln"),this.fence(Wi(this.word("ln"),this.fence(Wi(this.word("ln"),this.fence(a(i))))))));case"perm":return u(this.script(this.script(Di(""),this.render(i,{level:t.level+1}),t),null,t,this.render(s,{level:t.level+1}),this.word("P")));case"comb":return u(this.fence(this.stack(a(i),a(s),!1)));case"?:":return u(this.o.cases?this.cases(e,t):Wi(a(i),this.bin("?"),a(s),this.bin(":"),a(r[2])));case"sum":return u(Wi(r.map((e,t)=>t?[this.bin("+"),a(e)]:[a(e)]).flat()));case"prod":return u(Wi(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 Wi(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 Wi(this.text("sign",Si),this.render(r,t));const i=function(e){const[t,n]=e.args;return{left:j(e,t,"left")&&"/"!==t.op,right:j(e,n,"right")&&"/"!==n.op}}(e),s=L(n,r,i),a=function(e){for(;"op"===e.type;){if(ji.includes(e.op)||"log"===e.op||zi[e.op]||o(e.op))return!0;if("^"!==e.op&&"*"!==e.op)return!1;e=e.args[0]}return!1}(r),l=i.left?this.fence(this.render(n,t)):this.render(n,{...t,before:s&&!a}),u=i.right?this.fence(this.render(r,t)):this.render(r,{...t,before:t.before});return Wi(l,s?Di(this.el(a?"fnspace":"times","")):this.bin("·"),u)}named(e,t,n=null){const{op:r,args:i}=e,s="log"===r?i[1]:i[0];let o;o=Ti[r]&&"power"===this.o.inverseTrig?this.script(this.word(Ti[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(i[0],{level:t.level+1})));const a="auto"===this.o.fnParens&&!t.forceParens&&!t.before&&Hi(s),l=this.render(s,{...t,forceParens:!1,before:!1});return Wi(o,a?Wi(Di(this.el("fnspace","")),l):this.fence(l))}custom(e,t){const n=W(e.op),r=e.args;if(Zi.includes(n)&&1===r.length)return this.decorate(n,this.render(r[0],t));return Wi(/^[A-Za-z]′*(⁻¹)?$/.test(n)?this.symbol(n):this.word(n),Di(this.el("callgap","")),this.fence(this.list(r,t)))}decorate(e,t){switch(e){case"boxed":return Di(this.el("boxed",t.html),t.h+.22,t.d+.22);case"cancel":return Di(this.el("cancel",t.html+ki("cancel",`${this.p}-cancel-line`)),t.h,t.d);case"underline":return Di(this.el("underline",t.html),t.h,t.d+.12);case"overline":case"bar":return Di(this.el("over",t.html),t.h+.14,t.d);default:return Di(this.el("accent",this.el("accent-mark",Ri[e])+t.html),t.h+.3,t.d)}}fraction(e,t){const[n,r]=e.args;if(t.level>0&&"slash"===this.o.scriptFractions&&Hi(n,!0)&&Hi(r,!0)){const e=e=>"op"!==e.type||Hi(e)?this.render(e,t):this.fence(this.render(e,t));return Wi(e(n),this.text("ord","/"),e(r))}const i=t.level>0||t.inFraction||!this.o.display?.8:1,s={...t,inFraction:!0,forceParens:!1,before:!1};return this.stack(this.render(n,s),this.render(r,s),!0,i)}stack(e,t,n=!0,r=1){const i=e=>1===r?e.html:this.el("scaled",e.html,`font-size:${Bi(r)}`),s=n?.06:0,o=Ai+s/2+.1+Math.max(Mi,r*e.d),a=this.el("frac"+(n?"":" frac-nobar"),this.el("numer",i(e))+this.el("denom",i(t)),`vertical-align:${Bi(o)}`);return Di(a,o+Math.max(qi,r*e.h),Math.max(qi,r*t.h)+Math.max(Mi,r*t.d)+.1+s/2-Ai)}power(e,t){const[n,r]=e.args,i={...t,level:t.level+1,forceParens:!1,before:!1,inFraction:!1},s=()=>this.render(r,i);if(this.o.trigPowers&&_i.includes(n.op)&&Qi(r))return this.wrap(n,["op",`op-${n.op}`],this.named(n,t,s()));if("_"===n.op){const e=this.render(n.args[1],i);return this.wrap(n,["op","op-subscript"],this.script(this.render(n.args[0],{...t,forceParens:!0}),s(),t,e))}const o=j(e,n,"left")||"number"===n.type&&n.value.startsWith("-")||"/"===n.op||ji.includes(n.op)?this.fence(this.render(n,t)):this.render(n,{...t,forceParens:!0});return this.script(o,s(),t)}script(e,t,n,r=null,i=null){const s=n.level>0?.8:Ni,o=i?Wi(e,i):e;let a=t?Math.max(.42,e.h-.38,s*t.d+.12):0,l=r?Math.max(.2,e.d-.05,s*r.h-.45):0;if(t&&r){const e=.1-(a-s*t.d-(s*r.h-l));e>0&&(l+=e)}const u=e=>this.el("script",e.html,`font-size:${Bi(s)}`);if(t&&!r)return Di(e.html+this.el("sup",t.html,`font-size:${Bi(s)};vertical-align:${Bi(a/s)}`),Math.max(o.h,a+s*t.h),Math.max(o.d,s*t.d-a));if(r&&!t)return Di(o.html+this.el("sub",r.html,`font-size:${Bi(s)};vertical-align:${Bi(-l/s)}`),Math.max(o.h,s*r.h-l),Math.max(o.d,l+s*r.d));const c=a+s*t.h,h=l+s*r.d,p=this.el("subsup",u(t)+u(r),`vertical-align:${Bi(a)};height:${Bi(c+h)}`);return Di(o.html+p,Math.max(o.h,c),Math.max(o.d,h))}radical(e,t=null){const n=Math.max(e.h,qi)+.1+.06,r=Math.max(e.d,Mi),i=n+r,s=ki("sqrt",`${this.p}-hook`,`height:${Bi(i)};width:${Bi(.5+.06*(i-1))};vertical-align:${Bi(-r)}`);let o="";if(t){const e=.8*Ni;o=this.el("rootindex",t.html,`font-size:${Bi(e)};vertical-align:${Bi((.55*i-r)/e)}`)}return Di(this.el("sqrt",o+s+this.el("radicand",e.html)),n,r)}fence(e,t="(",n=")"){const r=Math.max(e.h,qi)+Math.max(e.d,Mi),i=r>1.25,s=i?.1:0,o=(e,t)=>{if(!e)return{html:"",w:0};const n={"(":.26,")":.26,"{":.36,"}":.36}[e];if(n){const s=n+(i?Math.min(.2,.05*(r-1)):0);return{html:ki(e,`${this.p}-delim ${this.p}-delim-${t}`,`width:${Bi(s)}`),w:s+.1}}const s={"[":"lbrack","]":"rbrack","|":"vert","⌊":"lfloor","⌋":"rfloor","⌈":"lceil","⌉":"rceil"}[e];return{html:this.el(`delim ${s} delim-${t}`,""),w:"|"===e?.18:.3}},a=o(t,"l"),l=o(n,"r"),u=`padding:${Bi(s)} ${Bi(l.w)} ${Bi(s)} ${Bi(a.w)}`,c=Di(this.el("fence",a.html+e.html+l.html,u),Math.max(e.h,qi)+s,Math.max(e.d,Mi)+s);return c.fenced=!0,c}derivative(e,t){const{n:n,body:r,by:i,variable:s}=U(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=Wi(a(),l()?this.script(this.render(i,c),l(),c):this.render(i,c)),p=e=>Wi(l()?this.script(a(),l(),c):a(),e||[]),f=t.level>0||t.inFraction||!this.o.display?.8:1;if(s)return this.stack(p(this.render(r,c)),h,!0,f);const d=_(r)&&u(_(r))<100,[m,g]="("===this.o.derivativeBrackets?["(",")"]:["[","]"],v=d?this.fence(this.render(r,t),m,g):this.render(r,t);return Wi(this.stack(p(),h,!0,f),v)}integral(e,t){const[n,r,i,s]=e,o=e=>this.render(e,t),a=e=>e?this.render(e,{...t,level:t.level+1}):null,l=()=>this.text("var",S(n)||"x");let u,c=null,h=null;switch(e.length){case 1:u=l();break;case 2:D(r)?u=o(r):(u=l(),c=a(r));break;case 3:D(r)?(u=o(r),c=a(i)):(u=l(),c=a(r),h=a(i));break;default:u=o(r),c=a(i),h=a(s)}const p=o(n),f=Di(this.el("dx",this.el("d","d")+u.html),u.h,u.d);return Wi(this.bigSign("int",p,c,h,t),p,f)}bigSign(e,t,n,r,i){const s=!this.o.display||i.level>0,o=Math.max(s?.6:.95,Math.max(t.h-Ai,t.d+Ai)+.12),a=ki(e,`${this.p}-bigsign ${this.p}-${e}sign`,`height:${Bi(2*o)};width:${Bi(s?.38:.5)};vertical-align:${Bi(Ai-o)}`);if(!n&&!r)return Di(a,Ai+o,o-Ai);const l=Ni,u=r||Di(""),c=n||Di(""),h=Ai+o-l*u.h;c.d;const p=this.el("limits",this.el("script",u.html,`font-size:${Bi(l)}`)+this.el("script lower",c.html,`font-size:${Bi(l)}`),`vertical-align:${Bi(h)};height:${Bi(2*o)}`);return Di(a+p,Ai+o,o-Ai)}limit(e,t){const[n,r,i,s]=e,o={...t,level:t.level+1},a=e=>this.render(e,o),l=()=>this.rel("→");let u;switch(e.length){case 1:return Wi(this.word("lim"),Di(this.el("fnspace","")),this.render(n,t));case 2:{const e=S(n),t="number"===r.type||"symbol"===r.type&&r.value.includes("∞");u=e&&t?Wi(this.text("var",e),l(),a(r)):a(r);break}case 3:u=Wi(a(r),l(),a(i));break;default:{const e=E(s).toLowerCase().startsWith("r")?"+":Si;u=Wi(a(r),l(),this.script(a(i),this.wrap(s,["symbol"],this.text("ord",e)),o))}}return Wi(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):Di(this.el("under",e.html+this.el("script",t.html,`font-size:${Bi(.7)}`)),e.h,Math.max(e.d,Mi)+.05+.7*(t.h+t.d))}bigOperator(e,t,n){const[r,i,s]=t,o={...n,level:n.level+1},a=i?this.render(i,o):null,l=s?this.render(s,o):null,u=this.render(r,n);if(!this.o.display||n.level>0){const t=.55,r=ki(e,`${this.p}-bigsign`,`height:${Bi(2*t)};width:${Bi(.8)};vertical-align:${Bi(Ai-t)}`);return Wi(this.script(Di(r,Ai+t,t-Ai),l,n,a),u)}const c=.68,h=Ni,p=ki(e,`${this.p}-bigsign`,`height:${Bi(1.36)};width:${Bi("sum"===e?1:1.05)}`),f=l?1.01+h*l.d:Ai-c,d=e=>this.el("script",e.html,`font-size:${Bi(h)}`),m=this.el("bigop",(l?d(l):"")+p+(a?d(a):""),`vertical-align:${Bi(f)}`);return Wi(Di(m,.93+(l?.08+h*(l.h+l.d):0),c-Ai+(a?.08+h*(a.h+a.d):0)),u)}matrix(e,t,n){const r=t.map(e=>e.map(e=>this.render(e,n))),i=r.map(e=>({h:Math.max(qi,...e.map(e=>e.h)),d:Math.max(Mi,...e.map(e=>e.d))})),s=i.reduce((e,t)=>e+t.h+t.d,0)+.3*(t.length-1),o=Ai+s/2-i[0].h,a=r.map((t,n)=>{const r=t.map(e=>this.el("matrix-cell",e.html)).join(""),i=e.args[n];return i&&"op"===i.type&&"[]"===i.op?this.wrap(i,["op","op-list","matrix-row"],Di(r)).html:r}).join(""),l=t[0].length,u=Di(this.el("matrix",a,`grid-template-columns:repeat(${l},auto);vertical-align:${Bi(o)}`),Ai+s/2,s/2-Ai),[c,h]=Q[e.op]??["[","]"];return this.fence(u,c,h)}cases(e,t){const n=[];let r=e;for(;"op"===r.type&&"?:"===r.op;)n.push([this.render(r.args[1],t),Wi(this.word("if"),this.text("space",""),this.render(r.args[0],t))]),r=r.args[2];"symbol"===r.type&&"unchanged"===r.value||n.push([this.render(r,t),this.word("otherwise")]);const i=n.map(([e,t])=>({h:Math.max(e.h,t.h),d:Math.max(e.d,t.d)})),s=i.reduce((e,t)=>e+t.h+t.d,0)+.25*(n.length-1),o=Ai+s/2-i[0].h,a=n.map(([e,t])=>this.el("case-value",e.html)+this.el("case-cond",t.html)).join(""),l=Di(this.el("cases",a,`vertical-align:${Bi(o)}`),Ai+s/2,s/2-Ai);return this.fence(l,"{","")}}function Hi(e,t=!1){return"number"===e.type?!e.value.startsWith("-")||t:"symbol"===e.type||"op"===e.type&&("abs"===e.op||X(e)?!t:!t||"neg"!==e.op&&"^"!==e.op?"*"===e.op&&!I(e)&&e.args.every(e=>"number"===e.type&&!e.value.startsWith("-")||Gi(e)||"*"===e.op&&Hi(e,t)):Hi(e.args[0],!0)&&("neg"===e.op||Hi(e.args[1],!0)))}const Gi=e=>"symbol"===e.type&&(1===e.value.length||/^[α-ωΑ-Ω]$/.test(e.value)||Boolean(O[e.value])),Qi=e=>"number"===e.type&&/^[1-9]\d*$/.test(e.value)&&Number(e.value)<10;const Xi=e=>M(e).join(" ");function Ji(e,t){const n=new Set;Yi(e,t,n);const r=[];return N(e,e=>{n.has(e)&&r.push(e)}),r}function Yi(e,t,n){if(null!=t)if(Array.isArray(t))t.forEach(t=>Yi(e,t,n));else if("number"!=typeof t)if("function"!=typeof t){if("string"==typeof t){const r=Xi(nn(t));return void N(e,e=>{Xi(e)===r&&n.add(e)})}if(t.path){const r=Ki(e,t.path);return void(r&&n.add(r))}if(t.type){const r=Xi(t);N(e,e=>{e!==t&&Xi(e)!==r||n.add(e)})}}else N(e,(e,r)=>{t(e,r)&&n.add(e)});else N(e,e=>{e.id===t&&n.add(e)})}function Ki(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 es(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 ts(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 ns(e,t={}){const{blocks:n}=t;if("string"==typeof e)return nn(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?ts(structuredClone(e)):e;throw new Error("Inline Math needs an expression, standard postfix or a tree")}function rs(e,t){const{colors:n,highlight:r,scope:i,blocks:s,...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(is(r))for(const n of Ji(e,t))a.set(n,`color:${r}`);const l=new Set(void 0===r?[]:Ji(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 is(e){return"string"==typeof e&&/^[#\w\s.,%()/+-]+$/.test(e)&&!/url\s*\(|expression/i.test(e)}function ss(e,t={}){return ns(e,{...t,blocks:t.blocks??ci})}function os(e,t={}){return function(e,t={}){const n=ns(e,t);return Ui(n,rs(n,t)).html}(e,{...t,blocks:t.blocks??ci})}const as=Symbol.for("inlinemath.expressions"),ls=new Set(["symbol","number"]);function us(e){return e?"symbol"===e.type?e.value:"op"===e.type&&"_"===e.op&&2===e.args.length&&"symbol"===e.args[0].type&&ls.has(e.args[1].type)?`${e.args[0].value}_${e.args[1].value}`:null:null}function cs(e){const{id:t,from:n,...r}=e;return r.args&&(r.args=r.args.map(cs)),r}function hs(e){const{id:t,...n}=e;return n.args&&(n.args=n.args.map(hs)),n}function ps(e,t){const n=(e,r)=>{if(!r&&void 0!==e.from)return t(e.from);const{id:i,from:s,...o}=e;return o.args&&(o.args=o.args.map(e=>n(e,!1))),o};return n(e,!0)}function fs(e,t){let n=!1;const r=new Set,i=e=>{const s=us(e);if(null!==s){if(!r.has(s)){const e=t(s);if(e){n=!0,r.add(s);const t={...i(cs(e)),from:s};return r.delete(s),t}}return e}return e.args?{...e,args:e.args.map(i)}:e},s=i(e);return{tree:n?hs(s):e,changed:n}}const ds="[-+]?(?:\\d+\\.?\\d*|\\.\\d+)",ms=new RegExp(`^(${ds})\\s*\\.\\.\\s*(${ds})(?:\\s+step\\s+(${ds}))?(?:\\s*=\\s*(${ds}))?$`);function gs(e){const t=/^\s*\[\[([\s\S]*)\]\]\s*$/.exec(e);if(!t||/\]\s*,\s*\[/.test(t[1]))return null;const n=t[1].trim(),r=ms.exec(n);if(r){const e=Number(r[1]),t=Number(r[2]);if(!(t>e))return null;const n=void 0!==r[3]?Number(r[3]):Number.isInteger(e)&&Number.isInteger(t)?1:(t-e)/100;if(!(n>0))return null;const i=void 0!==r[4]?Math.min(t,Math.max(e,Number(r[4]))):e;return{kind:"slider",min:e,max:t,step:n,default:String(i)}}if(n.includes("|")){const e=n.split("|").map(e=>e.trim()).filter(Boolean);if(e.length)return{kind:"dropdown",options:e,default:e[0]}}return{kind:"textbox",default:n}}const vs=Symbol("set on the page");class bs{constructor(){this.owners=new Map,this.chosen=new Map,this.listeners=new Set}definitions(e){const t=new Map;for(const[n,r]of this.owners)if(n!==e)for(const[e,n]of r)t.delete(e),t.set(e,n);return t}textOf(e){const t=this.chosen.get(e.name);return t&&t.key===e.key?t.text:e.text}get(e){const t=this.definitions().get(e);return t?this.textOf(t):void 0}names(){return[...this.definitions().keys()]}set(e,t){t=String(t);const n=this.definitions().get(e);if(n&&n.input){const r=this.chosen.get(e);if(r&&r.key===n.key&&r.text===t)return this;this.chosen.set(e,{key:n.key,text:t})}else{const n=new Map(this.owners.get(vs));n.set(e,{name:e,text:t,key:`page:${t}`,input:null}),this.owners.delete(vs),this.owners.set(vs,n)}return this.notify(null,e),this}clear(e){return void 0===e?(this.owners.clear(),this.chosen.clear()):(this.owners.get(vs)?.delete(e),this.chosen.delete(e)),this.notify(null,e),this}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}own(e,t){const n=this.owners.get(e);var r,i;(r=n,i=t,(r?.size??0)===(i?.size??0)&&[...r??[]].every(([e,t])=>i?.get(e)?.key===t.key))?t&&this.owners.set(e,t):(t&&t.size?this.owners.set(e,t):this.owners.delete(e),this.notify(e))}notify(e,t){for(const n of[...this.listeners])n(e,t)}}function ys(){return new bs}const xs=ys();function ws(e,t,n){const r=(e,i)=>i===t.length?n:{...e,args:e.args.map((e,n)=>n===t[i]?r(e,i+1):e)};return cs(r(e,0))}function $s(e,t,{parse:n,commit:r,cancel:i,label:s="Edit"}){const o=e.ownerDocument;if(!o||!o.body)return null;const a=o.defaultView,l=e.getBoundingClientRect(),u=o.createElement("input");u.type="text",u.className="mv-edit",u.value=t,u.spellcheck=!1,u.autocomplete="off",u.setAttribute("aria-label",s);const c=()=>{u.style.width=`${Math.max(4,u.value.length+2)}ch`},h=a.getComputedStyle(e);Object.assign(u.style,{position:"absolute",left:`${l.left+a.scrollX}px`,top:`${l.top+a.scrollY+l.height/2}px`,minWidth:`${Math.max(l.width,32)}px`,fontSize:h.fontSize}),c(),o.body.appendChild(u),a.getSelection?.()?.removeAllRanges(),u.focus(),u.select();let p=!1;const f=()=>{p=!0,u.remove()},d=e=>{if(p)return!0;if(!e||u.value===t)return f(),i&&i(),!0;let s;try{s=n(u.value)}catch(e){return u.setAttribute("aria-invalid","true"),u.title=e.message,!1}return f(),r(s,u.value),!0};return u.addEventListener("keydown",e=>{e.stopPropagation(),"Enter"===e.key&&(e.preventDefault(),d(!0)),"Escape"===e.key&&(e.preventDefault(),d(!1))}),u.addEventListener("input",()=>{c(),u.removeAttribute("aria-invalid"),u.removeAttribute("title")}),u.addEventListener("blur",()=>{d(!0)||d(!1)}),u}class ks{constructor(e,t,n={}){this.element=e,this.options=n,this.p=n.prefix||"mv",this.handlers=[],this.clicks=[],this.active=null,this.live=qs(e,n.announce,this.p),this.set(t)}set(e,{animate:t=!1,duration:n=600,easing:r="ease-in-out"}={}){const i=Ms(t)&&this.tree?this.snapshot():null,s=void 0!==this.tree;return this.tree=ss(e,this.options),this.element.innerHTML=Ui(this.tree,rs(this.tree,this.options)).html,this.root=this.element.firstElementChild,this.handlers.length&&this.root.classList.add(`${this.p}-clickable`),this.editing&&this.root.classList.add(`${this.p}-editable`),this.active=null,(this.clicks.length||this.editing)&&this.focusable(),i&&this.morph(i,{duration:n,easing:r}),s&&this.live&&this.announce(this.spoken()),this}spoken(){const e=this.root&&this.root.getAttribute&&this.root.getAttribute("aria-label");if(e)return e;try{return wi(this.tree)}catch{return""}}announce(e){return this.say(this.live,e)}say(e,t){if(!e)return this;e.textContent="";const n=()=>{e.textContent=t};return"function"==typeof requestAnimationFrame?requestAnimationFrame(()=>requestAnimationFrame(n)):setTimeout(n,50),this}nodes(e){return Ji(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),i=Ji(this.tree,r)[0];t({node:i,id:r,path:es(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`),"click"===e&&(this.clicks.push(t),this.keyboard()),()=>{this.element.removeEventListener(e,n),this.clicks=this.clicks.filter(e=>e!==t)}}editable({toText:e,onEdit:t}={}){if("function"!=typeof e)throw new Error("editable needs { toText } (import { toText } from 'mathzetta/text')");return this.editing={toText:e,onEdit:t},this.root&&this.root.classList&&this.root.classList.add(`${this.p}-editable`),this.keyboard(),!this.editOn&&this.element.addEventListener&&(this.editOn=!0,this.element.addEventListener("dblclick",e=>{const t=e.target.closest?.("[data-node]");t&&this.root.contains(t)&&(e.preventDefault(),this.edit(Ji(this.tree,Number(t.dataset.node))[0]))})),this}edit(e=this.tree,{returnFocus:t=!1}={}){if(!this.editing)throw new Error("call editable({ toText }) first");const n="object"==typeof e&&e&&e.type?e:this.nodes(e)[0];if(!n)return null;const r=es(this.tree,n.id)||[],i=this.elementOf(n)||this.root;let s="Edit";try{s=`Edit ${wi(n)}`}catch{}const o=()=>{t&&this.root.focus&&this.root.focus()};return $s(i,this.editing.toText(n),{label:s,parse:e=>ss(e,this.options),commit:(e,n)=>{this.set(ws(this.tree,r,e),{animate:!0});const i=Ki(this.tree,r);t&&i&&this.focusPart(i===this.tree?null:i),o(),this.editing.onEdit&&this.editing.onEdit({tree:this.tree,text:this.editing.toText(this.tree),path:r,part:n})},cancel:o})}focusable(){this.root&&this.root.setAttribute&&(this.root.setAttribute("tabindex","0"),this.root.getAttribute("aria-label")||(this.root.setAttribute("role","math"),this.root.setAttribute("aria-label",this.spoken())),this.root.setAttribute("aria-description",this.editing?"Arrow keys move between parts, F2 edits one.":"Arrow keys move between parts, Enter selects one."))}keyboard(){this.focusable(),!this.keysOn&&this.element.addEventListener&&(this.keysOn=!0,this.partsLive=this.live||qs(this.element,!0,this.p),this.element.addEventListener("keydown",e=>this.key(e)))}key(e){if(!this.root||!this.root.contains(e.target))return;const t=this.active;let n;switch(e.key){case"ArrowDown":n=t?this.partsOf(t)[0]:this.partsOf(this.tree)[0];break;case"ArrowUp":n=t?this.outerOf(t):void 0;break;case"ArrowRight":n=t?this.neighbour(t,1):this.partsOf(this.tree)[0];break;case"ArrowLeft":n=t?this.neighbour(t,-1):void 0;break;case"Home":case"Escape":n=null;break;case"F2":if(!this.editing)return;return e.preventDefault(),void this.edit(t||this.tree,{returnFocus:!0});case"Enter":case" ":{e.preventDefault();const n=t||this.tree,r=this.elementOf(n)||this.root,i={node:n,id:n.id,path:es(this.tree,n.id),element:r,event:e};for(const e of this.clicks)e(i);return}default:return}e.preventDefault(),void 0!==n&&this.focusPart(n)}focusPart(e){const t=`${this.p}-focus`;this.root.querySelectorAll(`.${t}`).forEach(e=>e.classList.remove(t)),this.active=e;const n=e&&this.elementOf(e);n&&n.classList.add(t);let r="";try{r=e?wi(e):this.spoken()}catch{r=""}return this.say(this.partsLive,r),this}partsOf(e){const t=[],n=e=>{this.elementOf(e)?t.push(e):"op"===e.type&&e.args.forEach(n)};return e&&"op"===e.type&&e.args.forEach(n),t}outerOf(e){const t=es(this.tree,e.id);for(let e=t?t.length-1:-1;e>0;e--){const n=Ki(this.tree,t.slice(0,e));if(n&&this.elementOf(n))return n}return null}neighbour(e,t){const n=this.partsOf(this.outerOf(e)||this.tree),r=n.indexOf(e);return r<0?void 0:n[r+t]}segments(e={}){return xi(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=Xi(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=i=>{const s=this.elementOf(i),o=s&&e.get(Xi(i));if(o&&o.length){const e=o.shift(),r=s.getBoundingClientRect(),i=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(i)+Math.abs(a)>.5||Math.abs(l-1)+Math.abs(u-1)>.01)&&s.animate([{transformOrigin:"0 0",transform:`translate(${i}px, ${a}px) scale(${l}, ${u})`},{transformOrigin:"0 0",transform:"none"}],{duration:t,easing:n}))}"op"===i.type?i.args.forEach(r):s&&s.animate([{opacity:0},{opacity:0},{opacity:1}],{duration:t,easing:n})};r(this.tree)}}function qs(e,t,n){if(!t)return null;if("object"==typeof t&&1===t.nodeType)return t;if("undefined"==typeof document||!e.insertAdjacentElement)return null;const r=document.createElement("span");return r.className=`${n}-sr-only`,r.setAttribute("aria-live","polite"),r.setAttribute("aria-atomic","true"),e.insertAdjacentElement("afterend",r),r}function Ms(e){return!!e&&("always"===e||!("function"==typeof matchMedia&&matchMedia("(prefers-reduced-motion: reduce)").matches))}const As=new RegExp("(\\d+)","g");function Ns(e,{delimiters:t=["$$","$","\\[","\\("]}={}){const n=[];let r="",i=0;const s=String(e),o=e=>0===e||"\n"===s[e-1],a=(e,t,r)=>(n.push({source:e,display:t,raw:r,start:i,end:i+r.length}),`${n.length-1}`);for(;i<s.length;){if(o(i)){const e=/^( {0,3})(`{3,}|~{3,})([^\n]*)\n?/.exec(s.slice(i));if(e){const t=e[2],n=new RegExp(`\\n {0,3}${"`"===t[0]?"`":"~"}{${t.length},}[ \\t]*(?=\\n|$)`),o=s.slice(i+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=s.slice(i,i+c);"math"===e[3].trim()?r+=a(u,!0,h):r+=h,i+=c;continue}}const e=s[i];if("`"===e){const e=/^`+/.exec(s.slice(i))[0],t=s.indexOf(e,i+e.length);if(t>-1){r+=s.slice(i,t+e.length),i=t+e.length;continue}r+=e,i+=e.length;continue}if("\\"===e){const e=s.slice(i,i+2),n="\\["===e?"\\]":"\\("===e?"\\)":null;if(n&&t.includes(e)){const t=s.indexOf(n,i+2);if(t>-1){r+=a(s.slice(i+2,t),"\\["===e,s.slice(i,t+2)),i=t+2;continue}}r+=e,i+=2;continue}if("$"===e)if("$"===s[i+1]&&t.includes("$$")){const e=s.indexOf("$$",i+2);if(e>-1){r+=a(s.slice(i+2,e),!0,s.slice(i,e+2)),i=e+2;continue}}else if(t.includes("$")&&s[i+1]&&!/\s/.test(s[i+1])){const e=Ss(s,i+1);if(e>-1){r+=a(s.slice(i+1,e),!1,s.slice(i,e+1)),i=e+1;continue}}r+=e,i++}return{text:r,math:n}}function Ss(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 Os=e=>String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),Es=/^\s*([A-Za-z\u0370-\u03ff](?:_\{?\w+\}?)?)\s*=\s*([^=<>≤≥]+)$/;function Is(e,t,n,r){const{text:i,math:s}=Ns(e,t),o=n?n.definitions(r):new Map,a=e=>n?n.textOf(e):e.text,l={...t.scope??{}},u={},c=new Map,h=new Set,p=[],f=()=>{for(const e of Object.keys(u))delete u[e];Object.assign(u,l);for(const e of o.keys())delete u[e];let e=[...o.values()];for(;e.length;){const t=e.filter(e=>{try{const t=ui(a(e),u);if("number"==typeof t.value||"bigint"==typeof t.value||Array.isArray(t.value))return u[e.name]=t.exact?t.text:t.value,!1}catch{}return!0});if(t.length===e.length)break;e=t}const t={},n=d({});for(const e of o.keys()){const r=n(e);if(r)try{t[e]=M(fs(r,t=>t===e?null:n(t)).tree)}catch{}}u[as]=t},d=e=>{const t=new Map;return n=>{const r=o.get(n);if(!r)return null;if(!t.has(n)){let i=null;try{i=ss(a(r),e)}catch{}t.set(n,i)}return t.get(n)}};f();const m=s.map((e,n)=>{const{source:r,display:i}=e,s=i?"mv-md-display":"mv-md-math",m=(e,t="")=>`<span class="${s}${t}" data-mv-md="${n}">${e}</span>`;try{const s={...t.math,display:i,blocks:t.blocks,scope:u},g=function(e){let t=e.trim();const n=t.startsWith("_");n&&(t=t.slice(1).trimStart());let r=t.indexOf(":="),i=2;r<0&&n&&(r=t.search(/(?<![<>!≤≥=])=(?!=)/),i=1);const s=n?{error:"a hidden $_…$ saves a variable: $_A := 2+2$"}:null;if(r<=0)return s;const o=t.slice(0,r).trim(),a=t.slice(r+i).trim();let l=null;try{l=/\{\{/.test(o)?null:us(ss(o))}catch{}return null!==l&&a?{hidden:n,lhs:o,name:l,rhs:a,input:gs(a)}:s}(r);if(g&&g.error)throw new Error(g.error);if(g){const{name:t,input:r,hidden:i}=g,l=r?{name:t,text:r.default,input:r,key:`input:${JSON.stringify(r)}`}:{name:t,text:g.rhs,input:null,key:`expr:${g.rhs}`,start:e.start,end:e.end};let u="";if(r){const e=function(e,t){const{input:n,name:r}=e,i=`class="mv-md-input mv-md-${n.kind}" data-mv-var="${Os(r)}" aria-label="${Os(r)}"`;if("dropdown"===n.kind)return`<select ${i}>${n.options.map(e=>`<option value="${Os(e)}"${e===t?" selected":""}>${Os(e)}</option>`).join("")}</select>`;return"slider"===n.kind?`<input type="range" ${i} min="${n.min}" max="${n.max}" step="${n.step}" value="${Os(t)}"><output class="mv-md-output" data-mv-out="${Os(r)}">${Os(t)}</output>`:`<input type="text" ${i} value="${Os(t)}" size="${Math.max(4,t.length+1)}" spellcheck="false" autocomplete="off">`}(l,a(l));u=i?e:`${os(g.lhs,s)}<span class="mv-md-assign" aria-hidden="true">≔</span>${e}`,h.add(n)}else{const e=fs(ss(g.rhs,s),d(s)).tree;if(!i){const t=ts({type:"op",op:"=",args:[cs(ss(g.lhs)),void 0===e.id?e:cs(e)]});p[n]=t,u=function(e){return e.replace('<span class="mv-rel">=</span>','<span class="mv-rel mv-rel-def">≔</span>').replace(/(aria-label="[^"]*?) equals /,"$1 is defined as ").replace("<mo>=</mo>","<mo>≔</mo>")}(os(t,s))}}return o.delete(t),o.set(t,l),c.set(t,l),f(),i&&!r?"":m(u,r?" mv-md-input-def":"")}const{tree:v,changed:b}=fs(ss(r,s),d(s));b&&ts(v),p[n]=v;const y=os(v,s);return!b&&!1!==t.define&&function(e,t,n){const r=Es.exec(e);if(!r||/\{\{/.test(r[2]))return!1;const i=r[1].replace(/[{}]/g,"");if(n.has(i))return!1;try{const e=ui(r[2],t);if("number"==typeof e.value||"bigint"==typeof e.value||Array.isArray(e.value))return t[i]=e.exact?e.text:e.value,!0}catch{}return!1}(r,l,o)&&f(),m(y)}catch(t){return`<span class="mv-md-error" data-mv-md="${n}" title="${Os(t.message)}"><code>${Os(e.raw)}</code></span>`}});return{text:i,math:s,drawn:m,defs:c,inputs:h,trees:p}}const _s=/^(https?:|mailto:|#|\/|\.{0,2}\/|[^:]*$)/i,Ts=e=>_s.test(e.trim())?Os(e.trim()):"#";function js(e,t,n){const r=[],i=e=>(r.push(e),`${r.length-1}`);let s=e;return s=s.replace(/(`+)([\s\S]*?[^`])\1(?!`)/g,(e,t,r)=>i(`<code>${Os(n(r.trim()))}</code>`)),s=s.replace(/\\([\\`*_{}[\]()#+\-.!|~$<>"'])/g,(e,t)=>i(Os(t))),s=s.replace(/<((?:https?:\/\/|mailto:)[^\s>]+)>/g,(e,t)=>i(`<a href="${Ts(t)}">${Os(t)}</a>`)),t.html&&(s=s.replace(/<\/?[A-Za-z][^>]*>/g,e=>i(e))),s=s.replace(/!\[([^\]]*)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,t,n,r)=>i(`<img src="${Ts(n)}" alt="${Os(t)}"${r?` title="${Os(r)}"`:""}>`)),s=s.replace(/\[([^\]]+)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,r,s,o)=>i(`<a href="${Ts(s)}"${o?` title="${Os(o)}"`:""}>${js(r,t,n)}</a>`)),s=Os(s),s=s.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g,"<strong>$2</strong>"),s=s.replace(/(^|[^*\w])\*(?=\S)([\s\S]*?\S)\*(?!\*)/g,"$1<em>$2</em>"),s=s.replace(/(^|[^_\w])_(?=\S)([\s\S]*?\S)_(?![_\w])/g,"$1<em>$2</em>"),s=s.replace(/~~(?=\S)([\s\S]*?\S)~~/g,"<del>$1</del>"),s=s.replace(/( {2,}|\\)\n/g,"<br>\n"),s.replace(/(\d+)/g,(e,t)=>r[Number(t)])}const zs=/^( {0,3})(#{1,6}\s|>|```|~~~|([-*+]|\d{1,9}[.)])\s|(\*[ \t]*){3,}$|(-[ \t]*){3,}$|(_[ \t]*){3,}$)/,Ls=/^( {0,3})([-*+]|\d{1,9}[.)])(\s+|$)/,Cs=/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;function Rs(e,t,n){const r=[];let i=0;const s=e=>js(e,t,n);for(;i<e.length;){const o=e[i];if(!o.trim()){i++;continue}const a=/^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)/.exec(o);if(a){const t=[];for(i++;i<e.length&&!new RegExp(`^ {0,3}${"`"===a[1][0]?"`":"~"}{${a[1].length},}\\s*$`).test(e[i]);)t.push(e[i++]);i++;const s=a[2]?` class="language-${Os(a[2])}"`:"";r.push(`<pre><code${s}>${Os(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}>${s(l[2])}</h${l[1].length}>`),i++;continue}if(/^ {0,3}((\*[ \t]*){3,}|(-[ \t]*){3,}|(_[ \t]*){3,})$/.test(o)){r.push("<hr>"),i++;continue}if(/^ {0,3}>/.test(o)){const s=[];for(;i<e.length&&e[i].trim()&&(/^ {0,3}>/.test(e[i])||s.length);)s.push(e[i].replace(/^ {0,3}> ?/,"")),i++;r.push(`<blockquote>\n${Rs(s,t,n)}\n</blockquote>`);continue}const u=Ls.exec(o);if(u){const s=/\d/.test(u[2]),o=s?parseInt(u[2],10):1,a=[];let l=!1;for(;i<e.length;){const t=Ls.exec(e[i]);if(!t||/\d/.test(t[2])!==s)break;const n=t[0].length,r=[e[i].slice(n)];for(i++;i<e.length;){const t=e[i];if(!t.trim()){const t=e[i+1];if(void 0!==t&&t.startsWith(" ".repeat(Math.min(n,4)))&&t.trim()){r.push(""),l=!0,i++;continue}void 0!==t&&Ls.test(t)&&(l=!0);break}if(t.startsWith(" ".repeat(Math.min(n,4))))r.push(t.slice(Math.min(n,4)));else{if(Ls.test(t)||zs.test(t))break;r.push(t)}i++}for(a.push(r);i<e.length&&!e[i].trim()&&void 0!==e[i+1]&&Ls.test(e[i+1]);)i++}const c=s?"ol":"ul",h=a.map(e=>{let r=Rs(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}${s&&1!==o?` start="${o}"`:""}>\n${h.join("\n")}\n</${c}>`);continue}if(o.includes("|")&&void 0!==e[i+1]&&Cs.test(e[i+1])&&e[i+1].includes("-")){const t=e=>e.trim().replace(/^\|/,"").replace(/\|$/,"").split(/(?<!\\)\|/).map(e=>e.trim()),n=t(e[i+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]}"`:""}>${s(t)}</${e}>`,l=t(o);i+=2;const u=[];for(;i<e.length&&e[i].trim()&&e[i].includes("|");)u.push(t(e[i++]));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(;i<e.length&&(/^( {4}|\t)/.test(e[i])||!e[i].trim());)t.push(e[i++].replace(/^( {4}|\t)/,""));for(;t.length&&!t[t.length-1].trim();)t.pop();r.push(`<pre><code>${Os(n(t.join("\n")))}</code></pre>`);continue}const c=[];for(;i<e.length&&e[i].trim()&&(!c.length||!zs.test(e[i])||/^ {0,3}[-=]+\s*$/.test(e[i]));){if(c.length&&/^ {0,3}(=+|-+)\s*$/.test(e[i])){const t="="===e[i].trim()[0]?1:2;r.push(`<h${t}>${s(c.join("\n"))}</h${t}>`),c.length=0,i++;break}c.push(e[i].replace(/^ {0,3}/,"")),i++}c.length&&r.push(`<p>${s(c.join("\n"))}</p>`)}return r.join("\n")}function Zs(e,t={},n=e=>e){return Rs(String(e).replace(/\r\n?/g,"\n").split("\n"),t,n)}function Fs({text:e,math:t,drawn:n},r){return(r.render?r.render(e):Zs(e,r,e=>e.replace(As,(e,n)=>t[Number(n)].raw))).replace(new RegExp("<p>\\s*(\\d+)\\s*</p>","g"),(e,r)=>t[Number(r)].display&&n[Number(r)]?`<div class="mv-md-block">${n[Number(r)]}</div>`:e).replace(As,(e,t)=>n[Number(t)]).replace(/<p>\s*<\/p>\n?/g,"")}const Ps=new WeakMap,Bs=new Set;function Ds(){for(const e of Bs)e.connected()&&!e.element.isConnected&&e.stop(!0)}function Ws(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,[i,s]=r,a=(e,r)=>c(n,_(e),r)?`(${t(e)})`:t(e),l=()=>r.map(t).join(", "),u=e=>z(n,e)?`(${t(e)})`:t(e);if("*"===n&&I(e))return"-"+t(s);if("+"===n&&I(s))return`${a(i,"left")} ${t(s)}`;if("-"===n&&I(s))return`${a(i,"left")} + ${t(s).slice(1)}`;if("^"===n){const e=a(i,"left");return`${e.startsWith("-")?`(${e})`:e}^${a(s,"right")}`}if(Us[n])return`${a(i,"left")} ${Us[n]} ${a(s,"right")}`;if(Q[n])return`${n}(${X(e).map(e=>`[${e.map(t).join(", ")}]`).join(", ")})`;if(Vs[n])return Vs[n][0]+l()+Vs[n][1];if(o(n))return`${W(n)}(${l()})`;switch(n){case"neg":return"-"+u(i);case"pmod":return`${t(i)} (mod ${t(s)})`;case"pm":return"±"+u(i);case"!":return u(i)+"!";case"\\not":return"¬"+u(i);case"sqrt":return`√(${t(i)})`;case"root":{const e="number"===i.type?{3:"∛",4:"∜"}[i.value]:null;return e?`${e}(${t(s)})`:`root(${t(i)}, ${t(s)})`}case"abs":return`|${t(i)}|`;case"floor":return`⌊${t(i)}⌋`;case"ceil":return`⌈${t(i)}⌉`;case"log":return`log_${"op"===i.type?`(${t(i)})`:t(i)}(${t(s)})`;case"loglog":return`ln(ln(${t(i)}))`;case"logloglog":return`ln(ln(ln(${t(i)})))`;case"perm":return`perm(${t(i)}, ${t(s)})`;case"comb":return`comb(${t(i)}, ${t(s)})`;case"_":return`${t(i)}_${t(s)}`;case"?:":return`${t(i)} ? ${t(s)} : ${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:i,variable:s}=U(e),o=n>1?`^${n}`:"";return s?`d${o}${t(r)}/d${t(i)}${o}`:`d${o}/d${t(i)}${o}(${t(r)})`}case"int":return function(e,t){const[n,r,i,s]=e,o=e.length>=2&&D(r)?t(r):S(n)||"x",a=`${t(n)} d${o}`;switch(e.length){case 1:return`∫ ${a}`;case 2:return D(r)?`∫ ${a}`:`∫[${t(r)}] ${a}`;case 3:return D(r)?`∫[${t(i)}] ${a}`:`∫[${t(r)}, ${t(i)}] ${a}`;default:return`∫[${t(i)}, ${t(s)}] ${a}`}}(r,t);case"lim":return function(e,t){const[n,r,i,s]=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(i)}] ${t(n)}`;default:{const e=E(s).toLowerCase().startsWith("r")?"⁺":"⁻";return`lim[${t(r)}→${t(i)}${e}] ${t(n)}`}}}(r,t);case"\\sumidx":return Hs("∑",r,t);case"\\prodidx":return Hs("∏",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 Us={"+":"+","-":"-","*":"*","/":"/","^":"^",mod:"mod","±":"±","=":"=","===":"===","≠":"≠","≠=":"≠","<":"<",">":">","≤":"≤","≥":"≥","∈":"∈","∉":"∉","→":"→","≈":"≈","∪":"∪","∩":"∩","≡":"≡","&":"∧","|":"∨","\\xor":"⊕","\\nand":"↑","\\nor":"↓"},Vs={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]};function Hs(e,t,n){const[r,i,s]=t,o="∑"===e?"sum":"prod";return 3===t.length&&"op"===i.type&&"="===i.op?`${o}(${n(r)}, ${n(i)}, ${n(s)})`:2===t.length&&"op"===i.type&&"∈"===i.op?`${o}(${n(r)}, ${n(i)})`:1===t.length?`${e} ${n(r)}`:2===t.length?`${e}[${n(i)}] ${n(r)}`:`${e}[${n(i)}, ${n(s)}] ${n(r)}`}for(const e of[Us,Vs])Object.setPrototypeOf(e,null);function Gs(e){return sn(e)?"":Ws(rn(e))}const Qs=new Map,Xs=-1,Js="\\:",Ys=e=>"string"==typeof e&&e.startsWith(Js)&&e.length>2;function Ks(e){if(!e||!e.symbol)throw new Error("operator needs a symbol");if(!Number.isInteger(e.arity)||e.arity<0&&e.arity!==Xs)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 Qs.set(t.symbol,t),t}const eo=Object.freeze({symbol:Js,arity:Xs,commutative:!1,fold:null,label:"function"});function to(e){const t=Qs.get(e);return t||(Ys(e)?{...eo,symbol:e,label:e.slice(2)}:null)}function no(e){return Qs.has(e)||Ys(e)}const ro=e=>Number.isFinite(e)&&Number.isInteger(e)?e:null,io=e=>Number.isFinite(e)?e:null;!function(){Ks({symbol:"+",arity:2,commutative:!0,label:"add",fold:(e,t)=>io(e+t)}),Ks({symbol:"-",arity:2,label:"subtract",fold:(e,t)=>io(e-t)}),Ks({symbol:"*",arity:2,commutative:!0,label:"multiply",fold:(e,t)=>io(e*t)}),Ks({symbol:"/",arity:2,label:"divide",fold:(e,t)=>0===t?null:ro(e/t)}),Ks({symbol:"^",arity:2,label:"power",fold:(e,t)=>Number.isInteger(t)&&Math.abs(t)<=64?io(e**t):null}),Ks({symbol:"neg",arity:1,label:"negate",fold:e=>io(-e)}),Ks({symbol:"pm",arity:1,label:"plus or minus"}),Ks({symbol:"±",arity:2,label:"plus or minus"}),Ks({symbol:"mod",arity:2,label:"modulo",fold:(e,t)=>0===t?null:ro((e%t+t)%t)}),Ks({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}),Ks({symbol:"_",arity:2,label:"subscript"}),Ks({symbol:"der",arity:2,label:"derivative"}),Ks({symbol:"int",arity:Xs,label:"integral"}),Ks({symbol:"lim",arity:Xs,label:"limit"}),Ks({symbol:"\\sumidx",arity:Xs,label:"sum over an index"}),Ks({symbol:"\\prodidx",arity:Xs,label:"product over an index"}),Ks({symbol:"abs",arity:1,label:"absolute value",fold:e=>io(Math.abs(e))}),Ks({symbol:"floor",arity:1,label:"floor",fold:e=>io(Math.floor(e))}),Ks({symbol:"ceil",arity:1,label:"ceiling",fold:e=>io(Math.ceil(e))}),Ks({symbol:"round",arity:2,label:"round",fold:(e,t)=>Number.isInteger(t)?io(Math.round(e*10**t)/10**t):null}),Ks({symbol:"fixed",arity:2,label:"fixed",fold:()=>null}),Ks({symbol:"sqrt",arity:1,label:"square root",fold:e=>ro(Math.sqrt(e))}),Ks({symbol:"root",arity:2,label:"nth root",fold:(e,t)=>ro(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"])Ks({symbol:e,arity:1,label:e});Ks({symbol:"log",arity:2,label:"log to a base"}),Ks({symbol:"atan2",arity:2,label:"atan2"}),Ks({symbol:"perm",arity:2,label:"permutations"}),Ks({symbol:"comb",arity:2,label:"combinations"}),Ks({symbol:"random",arity:0,label:"random"});for(const e of["max","min","gcd","mean","sum","prod"])Ks({symbol:e,arity:Xs,label:e});for(const e of["()","[]","{}","(]","[)"])Ks({symbol:e,arity:Xs,label:"group"});for(const e of["pmatrix","bmatrix","vmatrix"])Ks({symbol:e,arity:Xs,label:"matrix"});Ks({symbol:"det",arity:1,label:"determinant"});for(const e of["=","===","≠","≠=","<",">","≤","≥","∈","∉","∪","∩","≈","≡","→","pmod","&","|","\\xor","\\nand","\\nor"])Ks({symbol:e,arity:2,label:e});Ks({symbol:"\\not",arity:1,label:"not"}),Ks({symbol:"?:",arity:3,label:"if then else"})}();const so="num",oo="sym",ao="op",lo=Object.freeze([]);class uo extends Error{constructor(e){super(e),this.name="ExprError"}}function co(e){if("number"!=typeof e||!Number.isFinite(e))throw new uo(`not a finite number: ${e}`);const t=(n=e,Object.is(n,-0)?"0":String(n));var n;return Object.freeze({type:so,token:t,value:e,args:lo,s:t})}function ho(e){if("string"!=typeof e||""===e)throw new uo("symbol needs a non-empty token");return Object.freeze({type:oo,token:e,value:null,args:lo,s:e})}function po(e){const t=/^(-?)0*(\d+?)(?:\.(\d*?)0*)?$/.exec(String(e));if(!t)throw new uo(`not an exact decimal: ${e}`);const[,n,r,i=""]=t,s=i?`${r}.${i}`:r,o=/^0(\.0*)?$/.test(s)?"0":n+s;return Object.freeze({type:so,token:o,value:Number(o),args:lo,s:o})}const fo=/^-?\d+(\.\d+)?$/;function mo(e){const t=String(e);if(fo.test(t))return po(t);if(""!==t&&!/\s/.test(t)){const e=Number(t);if(Number.isFinite(e))return co(e)}return ho(t)}function go(e,t){const n=to(e);if(!n)throw new uo(`unknown operator "${e}"`);if(n.arity!==Xs&&t.length!==n.arity)throw new uo(`"${e}" takes ${n.arity} operand(s), got ${t.length}`);const r=Object.freeze(t.slice()),i=n.arity===Xs?` ${r.length}`:"",s=`${r.length?r.map(e=>e.s).join(" "):""}${r.length,""}${i} ${e}`.trimStart();return Object.freeze({type:ao,op:e,token:e,value:null,args:r,s:s})}const vo=e=>e.type===so,bo=e=>e.type===ao;function yo(e){return xo(function(e){const t=String(e).trim();return""===t?[]:t.split(/\s+/)}(e))}function xo(e){if(!Array.isArray(e))throw new uo("fromPostfix needs an array of tokens");if(0===e.length)throw new uo("empty expression");const t=[];for(let n=0;n<e.length;n++){const r=String(e[n]);if(no(r)){let e=to(r).arity;if(e===Xs){const i=t.pop();if(e=i&&i.type===so&&Number.isInteger(i.value)&&i.value>=0?i.value:-1,e<0)throw new uo(`"${r}" at position ${n+1} takes any number of operands, so a count must come before it`)}if(t.length<e)throw new uo(`"${r}" at position ${n+1} needs ${e} operand(s), only ${t.length} on the stack`);const i=t.splice(t.length-e,e);t.push(go(r,i))}else t.push(mo(r))}if(1!==t.length){const n=[...new Set(e.filter(e=>!no(e)))];throw new uo(`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 wo(e){if(e.type!==ao)return 0;let t=0;for(const n of e.args)t=Math.max(t,wo(n));return t+1}function $o(e){if(e.type!==ao)return 1;let t=1;for(const n of e.args)t+=$o(n);return t}function ko(e,t=[]){if(e.type!==ao)t.push(e.token);else for(const n of e.args)ko(n,t);return t}function qo(e){return e.type===so||e.type!==oo&&e.args.every(qo)}function Mo(e,t="pre",n=[],r=[]){"pre"===t&&r.push({node:e,path:n});for(let i=0;i<e.args.length;i++)Mo(e.args[i],t,n.concat(i),r);return"post"===t&&r.push({node:e,path:n}),r}function Ao(e,t,n){if(0===t.length)return n;const[r,...i]=t,s=e.args.slice();return s[r]=Ao(s[r],i,n),go(e.op,s)}class No extends Error{constructor(e){super(e),this.name="CasError"}}const So=1e5,Oo=e=>e<0n?-e:e,Eo=e=>0n===e?0:Oo(e).toString(2).length;function Io(e,t){for(e=Oo(e),t=Oo(t);t;)[e,t]=[t,e%t];return e}class _o{constructor(e,t=1n){if(0n===t)throw new No("division by zero");t<0n&&(e=-e,t=-t);const n=Io(e,t)||1n;if(this.n=e/n,this.d=t/n,Eo(this.n)>So||Eo(this.d)>So)throw new No("a number too large to keep exactly")}static of(e){return new _o(BigInt(e))}add(e){return new _o(this.n*e.d+e.n*this.d,this.d*e.d)}sub(e){return new _o(this.n*e.d-e.n*this.d,this.d*e.d)}mul(e){return new _o(this.n*e.n,this.d*e.d)}div(e){if(0n===e.n)throw new No("division by zero");return new _o(this.n*e.d,this.d*e.n)}neg(){return new _o(-this.n,this.d)}abs(){return this.n<0n?this.neg():this}inv(){return _o.ONE.div(this)}pow(e){if((e=BigInt(e))<0n)return this.inv().pow(-e);if((0n===this.n||1n===Oo(this.n))&&1n===this.d)return 0n===e||-1n===this.n&&e%2n==0n?_o.ONE:this;if(BigInt(Math.max(Eo(this.n),Eo(this.d)))*e>BigInt(So))throw new No("a power too large to work out exactly");return new _o(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 _o(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(Eo(this.n),Eo(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 To(e){const t=/^(-?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(String(e));if(!t||""===t[2]&&!t[3])return null;const[,n,r,i="",s="0"]=t;let o=new _o(BigInt((r||"0")+i),10n**BigInt(i.length));const a=Number(s);return a&&(o=o.mul(_o.of(10).pow(a))),n?o.neg():o}function jo(e,t){if(e<2n)return e;if(t>=Eo(e))return 1n;const n=BigInt(t);let r=1n<<BigInt(Math.ceil(Eo(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}_o.ZERO=new _o(0n),_o.ONE=new _o(1n),_o.MINUS_ONE=new _o(-1n),_o.HALF=new _o(1n,2n);const zo=(()=>{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 Lo(e,t){const n=BigInt(t);let r=1n,i=1n,s=e;for(const e of zo){if(e*e>s)break;if(s%e)continue;let t=0n;for(;s%e===0n;)s/=e,t++;r*=e**(t/n),i*=e**(t%n)}if(s>1n){const e=function(e,t){if(e<0n)return null;if(e<2n)return e;const n=jo(e,t);return n**BigInt(t)===e?n:null}(s,t);null!==e?r*=e:i*=s}return{outside:r,inside:i}}const Co=new Set(["pi","e","π"]),Ro={complex:!1};function Zo(e,t){const n=Ro.complex;Ro.complex=Boolean(e);try{return t()}finally{Ro.complex=n}}const Fo=e=>Co.has(e)||Ro.complex&&"i"===e,Po=e=>Ro.complex&&"atom"===e.k&&"sym"===e.node.type&&"i"===e.node.token,Bo=e=>({k:"num",q:e}),Do=Bo(_o.ONE),Wo=Bo(_o.ZERO),Uo=Bo(_o.HALF),Vo=e=>"num"===e.k,Ho=e=>({k:"atom",node:e}),Go=new WeakMap;function Qo(e){let t=Go.get(e);return void 0===t&&Go.set(e,t=Na(e).s),t}function Xo(e){if("num"===e.k)return 0;if("atom"===e.k)return"sym"===e.node.type&&Fo(e.node.token)?0:1;if("add"===e.k)return Math.max(...e.terms.map(e=>Xo(e.x)));let t=0;for(const n of e.fs){const e=Xo(n.b);e&&(t+=e*(Vo(n.e)?n.e.q.toNumber():1))}return t}function Jo(e,t){return"num"===e.k?t&&!Vo(t)?3:0:Po(e)?1.5:"atom"===e.k&&"sym"===e.node.type?Fo(e.node.token)?t&&!Vo(t)?3:1:2:"atom"===e.k?3:4}const Yo=(e,t)=>e<t?-1:e>t?1:0;function Ko(e){const t=new Map,n=(e,n)=>{"atom"!==e.k||"sym"!==e.node.type||Fo(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,Vo(t.e)?t.e.q.toNumber():1);else n(e,1);return t}function ea(e,t){const n=Xo(t.x)-Xo(e.x);if(n)return n;const r=Ko(e.x),i=Ko(t.x);for(const e of[...new Set([...r.keys(),...i.keys()])].sort()){const t=(i.get(e)??0)-(r.get(e)??0);if(t)return t}return Yo(Qo(e.x),Qo(t.x))}function ta(e,t){return e.isOne?t:e.isZero?Wo:sa([Bo(e),t])}function na(e){if("num"===e.k)return{coef:e.q,rest:null};if("mul"!==e.k||e.c.isOne)return{coef:_o.ONE,rest:e};const t=1===e.fs.length&&Vo(e.fs[0].e)&&e.fs[0].e.q.isOne?e.fs[0].b:{k:"mul",c:_o.ONE,fs:e.fs};return{coef:e.c,rest:t}}function ra(e){let t=_o.ZERO;const n=new Map,r=(e,t)=>{const r=Qo(t),i=n.get(r);i?i.coef=i.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}=na(n);r(e,t)}const i=[...n.values()].filter(e=>!e.coef.isZero);return i.length?t.isZero&&1===i.length?ta(i[0].coef,i[0].x):(i.sort(ea),{k:"add",c:t,terms:i}):Bo(t)}function ia(e,t){if(!Vo(t))return e.isOne?{coef:_o.ONE,fs:[]}:{coef:_o.ONE,fs:[{b:Bo(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 No("division by zero");return{coef:_o.ZERO,fs:[]}}if(e.isOne)return{coef:_o.ONE,fs:[]};if(e.sign<0){if(n.d%2n==1n){const{coef:r,fs:i}=ia(e.neg(),t);return{coef:n.n%2n==0n?r:r.neg(),fs:i}}if(Ro.complex&&2n===n.d){const{coef:r,fs:i}=ia(e.neg(),t);return{coef:r,fs:[...i,{b:la,e:Bo(new _o(n.n))}]}}return{coef:_o.ONE,fs:[{b:Bo(e),e:t}]}}if(!e.isInteger){const r=ia(new _o(e.n),t),i=ia(new _o(e.d),Bo(n.neg()));return{coef:r.coef.mul(i.coef),fs:[...r.fs,...i.fs]}}const r=n.floor(),i=n.sub(r);if(BigInt(Eo(e.n))*i.n>BigInt(So)||i.d>1000n)return{coef:_o.ONE,fs:[{b:Bo(e),e:t}]};let s=r.isZero?_o.ONE:e.pow(r.n);const{outside:o,inside:a}=Lo(e.n**i.n,Number(i.d));s=s.mul(new _o(o));return{coef:s,fs:a>1n?[{b:Bo(new _o(a)),e:Bo(new _o(1n,i.d))}]:[]}}function sa(e){let t=_o.ONE;const n=new Map,r=(e,t)=>{const r=Qo(e),i=n.get(r);i?i.e=ra([i.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,Do);if(t.isZero)return Wo;const i=[],s=new Map;for(const e of n.values())if(!Vo(e.e)||!e.e.q.isZero){if("num"===e.b.k){if(Vo(e.e)&&!e.e.q.isInteger&&e.b.q.sign>0&&e.b.q.isInteger){const t=e.e.q.toString(),n=s.get(t);n?n.n*=e.b.q.n:s.set(t,{n:e.b.q.n,e:e.e});continue}const n=ia(e.b.q,e.e);t=t.mul(n.coef),i.push(...n.fs);continue}if("mul"===e.b.k&&Vo(e.e)&&e.e.q.isInteger){const n=oa(e.b,e.e);"mul"===n.k?(t=t.mul(n.c),i.push(...n.fs)):"num"===n.k?t=t.mul(n.q):i.push({b:n,e:Do});continue}i.push(e)}for(const{n:e,e:n}of s.values()){const r=ia(new _o(e),n);t=t.mul(r.coef),i.push(...r.fs)}if(t.isZero)return Wo;const o=new Map;for(const e of i){const t=Qo(e.b),n=o.get(t);n?n.e=ra([n.e,e.e]):o.set(t,{...e})}let a=[...o.values()].filter(e=>!(Vo(e.e)&&e.e.q.isZero));if(Ro.complex){a=a.flatMap(e=>{if(!Po(e.b)||!Vo(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:Do}]:[]});const e=a.filter(e=>"add"===e.b.k&&Vo(e.e)&&e.e.q.isInteger&&ca(e.b)),n=a.some(e=>Po(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)&&!Po(t.b));let i=n?[la]:[Do];for(const t of e){const e=t.e.q.sign<0?fa(t.b):t.b;for(let n=0n;n<(t.e.q.sign<0?-t.e.q.n:t.e.q.n);n++)i=ha(i,Ia(e))}return sa([Bo(t),ra(i),...r.map(e=>aa(e.b,e.e))])}}if(a.some(e=>"num"===e.b.k&&Vo(e.e)&&e.e.q.compare(_o.ONE)>=0))return sa([Bo(t),...a.map(e=>"num"===e.b.k?oa(e.b,e.e):{k:"mul",c:_o.ONE,fs:[e]})]);if(!a.length)return Bo(t);if(1===a.length&&!t.isOne&&"add"===a[0].b.k&&Vo(a[0].e)&&a[0].e.q.isOne){const e=a[0].b;return ra([Bo(t.mul(e.c)),...e.terms.map(e=>ta(t.mul(e.coef),e.x))])}return t.isOne&&1===a.length&&Vo(a[0].e)&&a[0].e.q.isOne?a[0].b:(a=a.sort((e,t)=>Jo(e.b,e.e)-Jo(t.b,t.e)||Yo(Qo(e.b),Qo(t.b))),{k:"mul",c:t,fs:a})}function oa(e,t){if(Ro.complex&&Vo(t)&&t.q.isInteger){if(Po(e))return sa([{k:"mul",c:_o.ONE,fs:[{b:e,e:t}]}]);if("add"===e.k&&ca(e)&&!t.q.isOne)return sa([{k:"mul",c:_o.ONE,fs:[{b:e,e:t}]}])}if(Vo(t)){if(t.q.isZero){if(Vo(e)&&e.q.isZero)throw new No("0^0 is undefined");return Do}if(t.q.isOne)return e}if(Vo(e)){const n=ia(e.q,t);if(!n.fs.length)return Bo(n.coef);if(n.fs.some(e=>Po(e.b)))return sa([Bo(n.coef),...n.fs.map(e=>({k:"mul",c:_o.ONE,fs:[e]}))]);const r={k:"mul",c:n.coef,fs:n.fs};return n.coef.isOne&&1===n.fs.length&&Vo(n.fs[0].e)&&n.fs[0].e.q.isOne?n.fs[0].b:r}if(Ro.complex&&Vo(t)&&2n===t.q.d&&ca(e)){const n=pa(e);if(n&&Vo(n.im)&&!n.im.q.isZero){const e=e=>oa(e,Bo(_o.of(2))),r=oa(ra([e(n.re),e(n.im)]),Uo),i=oa(sa([ra([r,n.re]),Bo(_o.HALF)]),Uo),s=oa(sa([ra([r,ga(n.re)]),Bo(_o.HALF)]),Uo);return oa(ra([i,sa([Bo(_o.of(n.im.q.sign)),s,la])]),Bo(new _o(t.q.n)))}}if("mul"===e.k){if(Vo(t)&&t.q.isInteger)return sa([Bo(e.c.pow(t.q.n)),...e.fs.map(e=>aa(e.b,sa([e.e,t])))]);if(!e.c.isOne&&e.c.sign>0)return sa([oa(Bo(e.c),t),oa({k:"mul",c:_o.ONE,fs:e.fs},t)]);if(e.c.isOne&&1===e.fs.length){const[n]=e.fs;if(Vo(n.e)&&Vo(t)&&1n===n.e.q.n&&n.e.q.d%2n==1n)return aa(n.b,sa([n.e,t]))}}return{k:"mul",c:_o.ONE,fs:[{b:e,e:t}]}}function aa(e,t){return Vo(t)&&t.q.isZero?Do:Vo(e)?oa(e,t):Vo(t)&&t.q.isOne?e:{k:"mul",c:_o.ONE,fs:[{b:e,e:t}]}}const la=Ho(ho("i")),ua=e=>Ro.complex&&Na(e).s.split(" ").includes("i");function ca(e){return Ro.complex&&ua(e)&&0===Ea(Na(e)).size}function ha(e,t){const n=[];for(const r of e)for(const e of t)n.push(sa([r,e]));return Ia(ra(n))}function pa(e){const t=[],n=[];for(const r of Ia(e)){const{coef:e,rest:i}=na(r),s=i?_a(i):[],o=s.filter(e=>Po(e)),a=s.filter(e=>!Po(e));if(a.some(e=>ua(e)))return null;(o.length?n:t).push(sa([Bo(e),...a]))}return{re:ra(t),im:ra(n)}}function fa(e){const t=pa(e);if(!t)return oa(e,Bo(_o.MINUS_ONE));const n=ra([oa(t.re,Bo(_o.of(2))),oa(t.im,Bo(_o.of(2)))]);return sa([ra([t.re,sa([Bo(_o.MINUS_ONE),t.im,la])]),oa(n,Bo(_o.MINUS_ONE))])}const da={re:([e])=>pa(e)?.re??null,im:([e])=>pa(e)?.im??null,conj:([e])=>{const t=pa(e);return t?ra([t.re,sa([Bo(_o.MINUS_ONE),t.im,la])]):null},arg:([e])=>{const t=pa(e);return t?xa("atan2",[t.im,t.re]):null},abs:([e])=>{const t=pa(e);return!t||Vo(t.im)&&t.im.q.isZero?null:oa(ra([oa(t.re,Bo(_o.of(2))),oa(t.im,Bo(_o.of(2)))]),Uo)}},ma={Re:"re",re:"re",Im:"im",im:"im",conj:"conj",overline:"conj",bar:"conj",arg:"arg"},ga=e=>sa([Bo(_o.MINUS_ONE),e]),va=(e,t)=>sa([e,oa(t,Bo(_o.MINUS_ONE))]),ba=3000n,ya={abs:([e])=>Vo(e)?Bo(e.q.abs()):"mul"!==e.k||e.c.isOne?null:sa([Bo(e.c.abs()),xa("abs",[na(e).rest])]),floor:([e])=>Vo(e)?Bo(e.q.floor()):null,ceil:([e])=>Vo(e)?Bo(e.q.ceil()):null,"!":([e])=>{if(!Vo(e)||!e.q.isInteger||e.q.sign<0||e.q.n>ba)return null;let t=1n;for(let n=2n;n<=e.q.n;n++)t*=n;return Bo(new _o(t))},mod:([e,t])=>Vo(e)&&Vo(t)&&!t.q.isZero?Bo(e.q.sub(t.q.mul(e.q.div(t.q).floor()))):null,max:e=>e.every(Vo)&&e.length?e.reduce((e,t)=>t.q.compare(e.q)>0?t:e):null,min:e=>e.every(Vo)&&e.length?e.reduce((e,t)=>t.q.compare(e.q)<0?t:e):null,gcd:e=>e.length&&e.every(e=>Vo(e)&&e.q.isInteger)?Bo(new _o(e.reduce((e,t)=>Io(e,t.q.n),0n))):null,log:([e,t])=>{if(!Vo(e)||!Vo(t)||e.q.sign<=0||t.q.sign<=0||e.q.isOne)return null;if(t.q.isOne)return Wo;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 i=Math.round(n*r);if(!(Math.abs(n*r-i)>1e-9||0===i)&&(Math.abs(i)<=256&&e.q.pow(BigInt(i)).equals(t.q.pow(BigInt(r)))))return Bo(new _o(BigInt(i),BigInt(r)))}return null},comb:([e,t])=>Vo(e)&&Vo(t)&&e.q.isInteger&&t.q.isInteger&&e.q.sign>=0&&t.q.sign>=0&&e.q.n<=ba?Bo(function(e,t){if(t>e)return _o.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 _o(n)}(e.q.n,t.q.n)):null,perm:([e,t])=>{if(!(Vo(e)&&Vo(t)&&e.q.isInteger&&t.q.isInteger&&e.q.sign>=0&&t.q.sign>=0&&e.q.n<=ba))return null;if(t.q.n>e.q.n)return Wo;let n=1n;for(let r=0n;r<t.q.n;r++)n*=e.q.n-r;return Bo(new _o(n))}};function xa(e,t){if(Ro.complex&&da[e]){const n=da[e](t);if(n)return n}const n=ya[e];if(n){const e=n(t);if(e)return e}return Ho(go(e,t.map(Na)))}const wa=new Map;function $a(e){const t=Ro.complex?`ℂ ${e.s}`:e.s,n=wa.get(t);if(n)return n;const r=function(e){if("num"===e.type){const t=To(e.token);if(!t)throw new No(`not an exact number: ${e.token}`);return Bo(t)}if("sym"===e.type)return"π"===e.token?Ho(ho("pi")):Ho(e);const t=e.args.map($a);switch(e.op){case"+":return ra(t);case"-":return((e,t)=>ra([e,ga(t)]))(t[0],t[1]);case"neg":return ga(t[0]);case"*":return sa(t);case"/":return va(t[0],t[1]);case"^":return oa(t[0],t[1]);case"sqrt":return oa(t[0],Uo);case"root":return oa(t[1],oa(t[0],Bo(_o.MINUS_ONE)));default:{const n=e.op.startsWith("\\:")?e.op.slice(2):null;return n&&Ro.complex&&ma[n]&&1===t.length?xa(ma[n],t):n&&no(n)&&to(n).arity===t.length?xa(n,t):xa(e.op,t)}}}(e);return wa.size>2e4&&wa.clear(),wa.set(t,r),r}const ka=e=>Na($a(e)),qa=e=>po(String(e));function Ma(e){return e.isInteger?qa(e.n):go("/",[qa(e.n),qa(e.d)])}const Aa=new WeakMap;function Na(e){let t=Aa.get(e);return t||Aa.set(e,t=function(e){switch(e.k){case"num":return Ma(e.q);case"atom":return e.node;case"mul":return function(e,t){const n=[],r=[];for(const e of t)Vo(e.e)&&e.e.q.sign<0?r.push(Sa(e.b,Bo(e.e.q.neg()))):n.push(Sa(e.b,e.e));let i=1n!==e.n&&-1n!==e.n||!n.length?Oa([qa(e.n),...n]):Oa(n);-1n===e.n&&n.length&&(i=go("neg",[i]));1n!==e.d&&r.unshift(qa(e.d));return r.length?go("/",[i,Oa(r)]):i}(e.c,e.fs);case"add":return function(e){let t=null;const n=e=>Ro.complex&&ua(e.x)&&0===Ea(Na(e.x)).size,r=[...e.terms.filter(e=>!n(e)),...e.terms.filter(n)],i=e.c,s=()=>{i.isZero||(t=t?i.sign<0?go("-",[t,Ma(i.neg())]):go("+",[t,Ma(i)]):Ma(i))};let o=!1;for(const e of r)!o&&n(e)&&(s(),o=!0),t=t?e.coef.sign<0?go("-",[t,Na(ta(e.coef.neg(),e.x))]):go("+",[t,Na(ta(e.coef,e.x))]):Na(ta(e.coef,e.x));o||s();return t}(e);default:throw new Error(`bad form ${e.k}`)}}(e)),t}function Sa(e,t){const n=Na(e);if(Vo(t)){const e=t.q;if(e.isOne)return n;if(1n===e.n&&2n===e.d)return go("sqrt",[n]);if(1n===e.n)return go("root",[qa(e.d),n])}return go("^",[n,Na(t)])}const Oa=e=>e.reduce((e,t)=>e?go("*",[e,t]):t,null);function Ea(e,t=new Set){if("sym"===e.type)Fo(e.token)||t.add(e.token);else if(bo(e))for(const n of e.args)Ea(n,t);return t}function Ia(e){if("add"!==e.k)return[e];const t=e.terms.map(e=>ta(e.coef,e.x));return e.c.isZero||t.push(Bo(e.c)),t}function _a(e){if("num"===e.k)return[e];if("mul"!==e.k)return[e];const t=e.c.isOne?[]:[Bo(e.c)];for(const n of e.fs)t.push(aa(n.b,n.e));return t}const Ta="_",ja=new WeakMap;function za(e,t){return[...t,...to(e.op)?.arity===Xs?[String(e.args.length)]:[],e.op].join(" ")}function La(e,t){let n=ja.get(e);n||ja.set(e,n=new Map);const r=n.get(t);if(r)return r;const i=function(e,t){const n={key:Ta,slots:[e]};if(e.type!==ao||t<=0)return[n];const r=e.args.map(e=>La(e,t-1)),i=[n],s=new Array(r.length).fill(0);for(;;){const t=[],n=[];for(let e=0;e<r.length;e++){const i=r[e][s[e]];t.push(i.key);for(const e of i.slots)n.push(e)}if(i.push({key:za(e,t),slots:n}),i.length>=4096)break;let o=r.length-1;for(;o>=0&&!(++s[o]<r[o].length);o--)s[o]=0;if(o<0)break}return i}(e,t);return n.set(t,i),i}function Ca(e){return e.type!==ao?Ta:za(e,e.args.map(Ca))}function Ra(e,t=[]){if(e.type!==ao)t.push(e);else for(const n of e.args)Ra(n,t);return t}const Za=new Map,Fa=new Map;class Pa extends Error{constructor(e){super(e),this.name="RequirementError"}}function Ba(e,t,n=""){Za.set(e,{name:e,fn:t,doc:n,arity:Math.max(0,t.length-1)})}function Da(e,t,n=""){Fa.set(e,{name:e,fn:t,doc:n})}function Wa(e){return Za.get(e)||null}function Ua(e){return Fa.get(e)||null}const Va=e=>e.type===so;function Ha(e,t){return e.type===ao&&(e.op===t||e.args.some(e=>Ha(e,t)))}Ba("always",()=>!0,"matches anything"),Ba("never",()=>!1,"matches nothing"),Ba("isLeaf",e=>e.type!==ao,"a bare operand, not an operation"),Ba("isCompound",e=>e.type===ao,"an operation, not a bare operand"),Ba("isSymbol",e=>e.type===oo,"a non-numeric operand such as x"),Ba("isOperation",(e,t)=>e.type===ao&&e.op===t,"is this specific operation"),Ba("notOperation",(e,t)=>!(e.type===ao&&e.op===t),"is anything except this operation"),Ba("isNumber",Va,"a numeric literal"),Ba("isInteger",e=>Va(e)&&Number.isInteger(e.value),"a whole number"),Ba("isPositive",e=>Va(e)&&e.value>0,"greater than zero"),Ba("isNegative",e=>Va(e)&&e.value<0,"less than zero"),Ba("isNonNegative",e=>Va(e)&&e.value>=0,"zero or greater"),Ba("isZero",e=>Va(e)&&0===e.value,"exactly 0"),Ba("isOne",e=>Va(e)&&1===e.value,"exactly 1"),Ba("isNonZero",e=>Va(e)&&0!==e.value,"a number that is provably not 0"),Ba("isNotZeroLiteral",e=>!(Va(e)&&0===e.value),"anything except a literal 0"),Ba("isPositiveInteger",e=>Va(e)&&Number.isInteger(e.value)&&e.value>0,"a whole number above 0"),Ba("isNegativeInteger",e=>Va(e)&&Number.isInteger(e.value)&&e.value<0,"a whole number below 0"),Ba("isEven",e=>Va(e)&&Number.isInteger(e.value)&&e.value%2==0,"a whole even number"),Ba("isOdd",e=>Va(e)&&Number.isInteger(e.value)&&1===Math.abs(e.value%2),"a whole odd number"),Ba("greaterThan",(e,t)=>Va(e)&&e.value>Number(t),"above a given value"),Ba("lessThan",(e,t)=>Va(e)&&e.value<Number(t),"below a given value"),Ba("isValue",(e,t)=>Va(e)&&e.value===Number(t),"equals a given number"),Ba("isNumeric",qo,"contains no symbols: a constant (it need not fold to a number: 1 sin)"),Ba("hasSymbol",e=>!qo(e),"mentions a symbol somewhere, so it is not just a number"),Ba("isVar",(e,t)=>e.type===oo&&e.token===String(t),"is exactly this symbol"),Ba("contains",(e,t)=>ko(e).includes(String(t)),"mentions this operand somewhere"),Ba("isFree",(e,t)=>!ko(e).includes(String(t)),"never mentions this operand"),Ba("hasOperation",(e,t)=>Ha(e,String(t)),"uses this operation somewhere inside"),Ba("equals",(e,t)=>e.s===String(t),"is exactly this postfix expression");const Ga=e=>e.type===ao?null:e.token;function Qa(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 Pa(`bad requirement: ${JSON.stringify(e)}`)}Da("freeOf",(e,t)=>{const n=Ga(t);return null!==n&&!ko(e).includes(n)},"the first operand never mentions the second"),Da("dependsOn",(e,t)=>{const n=Ga(t);return null!==n&&ko(e).includes(n)},"the first operand does mention the second"),Da("sameAs",(...e)=>e.every(t=>t.s===e[0].s),"these operands are structurally identical"),Da("differs",(...e)=>new Set(e.map(e=>e.s)).size===e.length,"these operands are all different"),Da("sameValue",(...e)=>e.every(e=>Va(e))&&e.every(t=>t.value===e[0].value),"these operands are the same number");const Xa="simplify";class Ja extends Error{constructor(e,t){super(t?`rule "${t}": ${e}`:e),this.name="RuleError",this.ruleId=t}}const Ya=/^[A-Za-z_][A-Za-z0-9_]*$/;function Ka(e,t){if(vo(e))return{literal:e.value};const n=e.token;if(n.startsWith("=")){const e=n.slice(1);if(""===e)throw new Ja('"=" needs an operand after it',t);return{token:e}}if(!Ya.test(n))throw new Ja(`"${n}" is not a usable slot name; use letters, digits and _`,t);if(no(n))throw new Ja(`slot name "${n}" collides with an operator`,t);return{name:n}}function el(e){if(!bo(e))return[e];const t=e.args.map(el),n=to(e.op),r=[];for(const i 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(go(e.op,i)),n.commutative&&2===i.length&&i[0].s!==i[1].s&&r.push(go(e.op,[i[1],i[0]])),r.length>=64)break;return r}function tl(e,t=[]){return"op"===e.kind?e.args.forEach(e=>tl(e,t)):"const"===e.kind&&e.free&&t.push(e.node.token),t}function nl(e){if(!e||"object"!=typeof e)throw new Ja("rule must be a mapping");const t=e.id||e.name;if(!t)throw new Ja("rule needs an id");if(!e.pattern)throw new Ja("rule needs a pattern",t);if(void 0===e.output||null===e.output)throw new Ja("rule needs an output",t);let n;try{n=yo(String(e.pattern))}catch(e){if(e instanceof uo)throw new Ja(`bad pattern: ${e.message}`,t);throw e}const r=Ra(n).map(e=>Ka(e,t)),i=new Set(r.filter(e=>e.name).map(e=>e.name)),s=function(e,t,n){const r=[],i=e.when||{};if("object"!=typeof i||Array.isArray(i))throw new Ja('"when" must map slot names to lists of requirements',n);for(const[e,s]of Object.entries(i)){if(!t.has(e))throw new Ja(`"when" mentions "${e}", which is not a slot in the pattern`,n);const i=Array.isArray(s)?s:[s];for(const t of i){const{name:i,args:s}=Qa(t),o=Wa(i);if(!o)throw new Ja(`unknown requirement "${i}"`,n);r.push({slot:e,name:i,args:s,fn:o.fn})}}return r}(e,i,t),o=function(e,t,n){const r=[],i=e.require||[];if(!Array.isArray(i))throw new Ja('"require" must be a list of relations',n);for(const e of i){const{name:i,args:s}=Qa(e),o=Ua(i);if(!o)throw new Ja(`unknown relation "${i}"`,n);if(s.length<2)throw new Ja(`relation "${i}" needs at least two operands`,n);for(const e of s)if("string"==typeof e&&!t.has(e)&&Ya.test(e))throw new Ja(`relation "${i}" mentions "${e}", which is not a slot in the pattern`,n);r.push({name:i,args:s,fn:o.fn})}return r}(e,i,t),a=function(e,t,n){let r;try{r=yo(e)}catch(t){throw new Ja(`bad output "${e}": ${t.message}`,n)}const i=e=>bo(e)?{kind:"op",op:e.op,args:e.args.map(i)}:vo(e)?{kind:"const",node:e}:t.has(e.token)?{kind:"slot",name:e.token}:e.token.startsWith("=")?{kind:"const",node:ho(e.token.slice(1))}:{kind:"const",node:e,free:!0};return i(r)}(String(e.output),i,t),l=e.commutative?el(n):[n],u=[],c=new Set;for(const e of l){const n=Ca(e),r=Ra(e).map(e=>Ka(e,t)),i=n+"\0"+r.map(e=>e.name??(void 0!==e.literal?`#${e.literal}`:`=${e.token}`)).join(",");c.has(i)||(c.add(i),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):Xa,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:s,require:o,slots:[...i],depth:wo(n),bindings:u,freeSymbols:tl(a),source:e};for(const e of u)e.rule=h;return h}function rl(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!==Xa&&(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 il extends Error{constructor(e,t){super(null==t?e:`${e} (line ${t+1})`),this.name="YamlError",this.line=t}}class sl{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 ol=e=>"-"===e||e.startsWith("- ");function al(e){let t=null,n=0;for(let r=0;r<e.length;r++){const i=e[r];if(t)i===t?"'"===t&&"'"===e[r+1]?r++:t=null:'"'===t&&"\\"===i&&r++;else if('"'===i||"'"===i)t=i;else if("["===i||"{"===i)n++;else if("]"===i||"}"===i)n--;else if(":"===i&&0===n&&(r+1===e.length||" "===e[r+1])){const t=e.slice(0,r).trim();return""===t?null:{key:ll(t),rest:e.slice(r+1).trim()}}}return null}function ll(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 ul(e){const t=new sl(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=hl(t,n.indent),i=t.peek();if(i&&"..."!==i.text&&"---"!==i.text)throw new il(`unexpected content "${i.text}"`,i.n);return r}const cl=/^[|>][-+]?\d*$/;function hl(e,t){const n=e.peek();return!n||n.indent<t?null:ol(n.text)?pl(e,n.indent):al(n.text)?function(e,t){const n={};for(;;){const r=e.peek();if(!r||r.indent!==t)break;const i=al(r.text);if(!i)break;e.next();const{key:s,rest:o}=i;if(""===o){const r=e.peek();r&&r.indent>t?n[s]=hl(e,r.indent):r&&r.indent===t&&ol(r.text)?n[s]=pl(e,t):n[s]=null}else cl.test(o)?n[s]=fl(e,o,t):n[s]=dl(o,r.n)}return n}(e,n.indent):(e.next(),cl.test(n.text)?fl(e,n.text,n.indent-1):dl(n.text,n.n))}function pl(e,t){const n=[];for(;;){const r=e.peek();if(!r||r.indent!==t||!ol(r.text))break;if(e.next(),"-"===r.text){const r=e.peek();n.push(r&&r.indent>t?hl(e,r.indent):null);continue}if(cl.test(r.text.slice(2).trim())){n.push(fl(e,r.text.slice(2).trim(),t));continue}const i=r.text.slice(2),s=t+2+(i.length-i.trimStart().length);e.push({raw:r.raw,n:r.n,indent:s,text:i.trim(),blank:!1}),n.push(hl(e,s))}return n}function fl(e,t,n){const r=t[0],i=(t.match(/[-+]/)||[""])[0],s=(t.match(/\d+/)||[null])[0];let o=s?n+Number(s):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"-"===i?l:"+"===i?l+"\n":""===l?"":l+"\n"}function dl(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=gl(n);if(ml(n),n.i<n.text.length)throw new il(`unexpected "${n.text.slice(n.i)}" in flow value`,t);return r}(n,t):'"'===n[0]||"'"===n[0]?ll(n):/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(n)?Number(n):n)}const ml=e=>{for(;e.i<e.text.length&&/\s/.test(e.text[e.i]);)e.i++};function gl(e){ml(e);const t=e.text[e.i];return"["===t?function(e){e.i++;const t=[];for(;;){if(ml(e),e.i>=e.text.length)throw new il("unterminated [",e.line);if("]"===e.text[e.i])return e.i++,t;if(t.push(gl(e)),ml(e),","===e.text[e.i])e.i++;else if("]"!==e.text[e.i])throw new il(`expected , or ] near "${e.text.slice(e.i)}"`,e.line)}}(e):"{"===t?function(e){e.i++;const t={};for(;;){if(ml(e),e.i>=e.text.length)throw new il("unterminated {",e.line);if("}"===e.text[e.i])return e.i++,t;const n=String(gl(e));if(ml(e),":"!==e.text[e.i])throw new il(`expected : after "${n}"`,e.line);if(e.i++,t[n]=gl(e),ml(e),","===e.text[e.i])e.i++;else if("}"!==e.text[e.i])throw new il(`expected , or } near "${e.text.slice(e.i)}"`,e.line)}}(e):dl(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 il("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 vl=/^(true|false|null|yes|no|on|off|~)$/i;function bl(e){if(null==e)return"null";if("boolean"==typeof e)return e?"true":"false";if("number"==typeof e){if(!Number.isFinite(e))throw new il(`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)||vl.test(e)||/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(e))}(t)?JSON.stringify(t):t}const yl=e=>null==e||"object"!=typeof e;function xl(e){return Array.isArray(e)?`[${e.map(xl).join(", ")}]`:e&&"object"==typeof e?`{${Object.entries(e).map(([e,t])=>`${bl(e)}: ${xl(t)}`).join(", ")}}`:bl(e)}function wl(e){return Array.isArray(e)?!!e.every(e=>yl(e)||Array.isArray(e)&&e.every(yl))&&xl(e).length<=72:!(!e||"object"!=typeof e)&&(Object.values(e).every(e=>yl(e)||Array.isArray(e)&&e.every(yl))&&xl(e).length<=72)}function $l(e){const t=[];return kl(e,0,t),t.length?t.join("\n")+"\n":""}function kl(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)ql(r,t,n)}else{if(e&&"object"==typeof e){const i=Object.entries(e).filter(([,e])=>void 0!==e);if(0===i.length)return void n.push(r+"{}");for(const[e,r]of i)Ml(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+bl(e))}(e,r,n)}}function ql(e,t,n){const r=" ".repeat(t);if(null!==e&&"object"==typeof e&&!wl(e)){const i=[];if(kl(e,t+2,i),0===i.length)return void n.push(r+"-");n.push(r+"- "+i[0].slice(t+2));for(let e=1;e<i.length;e++)n.push(i[e]);return}if(null===e||"object"!=typeof e)if("string"==typeof e&&e.includes("\n")){n.push(r+"- |-");for(const r of e.replace(/\n+$/,"").split("\n"))n.push(" ".repeat(t+4)+r)}else n.push(r+"- "+bl(e));else n.push(r+"- "+xl(e))}function Ml(e,t,n,r){const i=" ".repeat(n),s=bl(e);if("string"==typeof t&&t.includes("\n")){r.push(`${i}${s}: |-`);for(const e of t.replace(/\n+$/,"").split("\n"))r.push(" ".repeat(n+2)+e)}else{if(null!==t&&"object"==typeof t)return wl(t)?void r.push(`${i}${s}: ${xl(t)}`):(r.push(`${i}${s}:`),void kl(t,Array.isArray(t)?n:n+2,r));r.push(`${i}${s}: ${bl(t)}`)}}class Al{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:nl(e);if(this.rules.some(e=>e.id===t.id))throw new Ja(`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 Al(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===Xa?-1:t===Xa?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=ul(e);return Al.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 Ja('expected a list of rules, or a mapping with a "rules" list');const i=new Al;i.name=r;const s=[];for(let e=0;e<n.length;e++)try{i.add(n[e])}catch(t){s.push(`#${e+1}: ${t.message}`)}if(s.length&&t)throw new Ja(`${s.length} rule(s) failed to compile:\n ${s.join("\n ")}`);return i.errors=s,i}toSpecs(){return this.rules.map(rl)}toYaml(){const e=this.toSpecs();return this.name?$l({name:this.name,rules:e}):$l(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 Nl(e,t){const n=Object.create(null),r=e.slots;for(let e=0;e<r.length;e++){const i=r[e],s=t[e];if(void 0!==i.literal){if(!vo(s)||s.value!==i.literal)return null;continue}if(void 0!==i.token){if(s.s!==i.token)return null;continue}const o=n[i.name];if(void 0!==o){if(o.s!==s.s)return null}else n[i.name]=s}return n}function Sl(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 Ol(e,t){return t.rule.priority-e.rule.priority||t.rule.depth-e.rule.depth}function El(e,t){const n=[];if(0===t.maxDepth)return n;for(const{key:r,slots:i}of function(e,t){const n=La(e,t),r=[];for(const e of n)e.key!==Ta&&r.push(e);return r}(e,t.maxDepth)){const e=t.candidates(r);if(e)for(const t of e){const e=Nl(t,i);e&&(Sl(t.rule,e)&&n.push({rule:t.rule,binding:t,key:r,bound:e}))}}return n.sort(Ol)}function Il(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 go(e.op,e.args.map(e=>Il(e,t)));default:throw new Error(`bad output template: ${JSON.stringify(e)}`)}}const _l=4e5,Tl=()=>new No("a number too large to approximate"),jl=e=>e<0n?-e:e;class zl{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 No("division by zero");return e*this.S/t}sqrt(e){if(e<0n)throw new No("the square root of a negative number is not real");return jo(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 No("a series did not converge");return n}atanhInv(e){const t=BigInt(e),n=t*t;let r=this.S/t,i=0n;for(let e=1n;0n!==r;e+=2n)i+=r/e,r/=n;return i}atanInv(e){const t=BigInt(e),n=t*t;let r=this.S/t,i=0n;for(let e=1n,t=1n;0n!==r;e+=2n,t=-t)i+=t*r/e,r/=n;return i}get pi(){return this.memo("pi",()=>16n*this.atanInv(5)-4n*this.atanInv(239))}get ln2(){return this.memo("ln2",()=>2n*this.atanhInv(3))}get e(){return this.memo("e",()=>this.exp(this.S))}memo(e,t){return this.cache.has(e)||this.cache.set(e,t()),this.cache.get(e)}exp(e){const t=(e+(e>=0n?this.ln2/2n:-this.ln2/2n))/this.ln2;if(t>BigInt(_l))throw Tl();if(t<-BigInt(_l))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 No("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),i=this.mul(r,r);let s=r,o=0n;for(let e=1n;0n!==s;e+=2n)o+=s/e,s=this.mul(s,i);return 2n*o+t*this.ln2}sin(e){const t=2n*this.pi;let n=e%t;n>this.pi&&(n-=t),n<-this.pi&&(n+=t);const 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(jl(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,i=0n;for(let e=1n,t=1n;0n!==r;e+=2n,t=-t)i+=t*r/e,r=this.mul(r,n);return 4n*i}asin(e){if(jl(e)>this.S)throw new No("arcsin of a number beyond ±1 is not real");return jl(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 Ll(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 No("the argument of 0 is undefined");return t>0n?e.pi/2n:-e.pi/2n}const Cl={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 No("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=Cl.abs(e,t);if(0n===n)throw new No("the log of 0 is undefined");return[e.ln(n),Ll(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,i=[e.S,0n],s=t;for(;n>0n;)1n&n&&(i=Cl.mul(e,i,s)),s=Cl.mul(e,s,s),n>>=1n;return r.n<0n?Cl.div(e,[e.S,0n],i):i}return Cl.exp(e,Cl.mul(e,n,Cl.ln(e,t)))},sinh:(e,t)=>(e.exp(t)-e.exp(-t))/2n,cosh:(e,t)=>(e.exp(t)+e.exp(-t))/2n},Rl={sin:(e,[t,n])=>[e.mul(e.sin(t),Cl.cosh(e,n)),e.mul(e.cos(t),Cl.sinh(e,n))],cos:(e,[t,n])=>[e.mul(e.cos(t),Cl.cosh(e,n)),-e.mul(e.sin(t),Cl.sinh(e,n))],tan:(e,t)=>Cl.div(e,Rl.sin(e,t),Rl.cos(e,t)),ln:(e,t)=>Cl.ln(e,t),sqrt:(e,t)=>Cl.exp(e,Cl.mul(e,[e.S/2n,0n],Cl.ln(e,t))),sinh:(e,[t,n])=>[e.mul(Cl.sinh(e,t),e.cos(n)),e.mul(Cl.cosh(e,t),e.sin(n))],cosh:(e,[t,n])=>[e.mul(Cl.cosh(e,t),e.cos(n)),e.mul(Cl.sinh(e,t),e.sin(n))]},Zl=e=>({q:e}),Fl=([e,t])=>0n===t?{f:e}:{z:[e,t]};function Pl(e,t,n){const r=e=>((e,t)=>t.z??[Bl(e,t),0n])(n,t[e]);switch(e.op){case"+":return Fl(Cl.add(r(0),r(1)));case"-":return Fl(Cl.sub(r(0),r(1)));case"neg":return Fl([-r(0)[0],-r(0)[1]]);case"*":return Fl(Cl.mul(n,r(0),r(1)));case"/":return Fl(Cl.div(n,r(0),r(1)));case"^":return Fl(Cl.pow(n,r(0),r(1),t[1].q));case"sqrt":return Fl(Rl.sqrt(n,r(0)));case"root":return Fl(Cl.pow(n,r(1),Cl.div(n,[n.S,0n],r(0)),t[0].q?.inv()));case"abs":return{f:Cl.abs(n,r(0))};case"arg":return{f:Ll(n,r(0)[1],r(0)[0])};case"re":return{f:r(0)[0]};case"im":return{f:r(0)[1]};case"conj":return Fl([r(0)[0],-r(0)[1]]);case"log":return Fl(Cl.div(n,Cl.ln(n,r(1)),Cl.ln(n,r(0))));default:{const i=Rl[e.op];if(!i||1!==t.length)throw new No(`no complex value for ${e.op}`);return Fl(i(n,r(0)))}}}function Bl(e,t){return t.q?e.fromQ(t.q):t.f}const Dl={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 No("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(jl(t)>=e.S)throw new No("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 Wl(e,t,n){if("num"===e.type)return Zl(To(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&&Ro.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?To(String(t)):null;if(!r)throw new No(`the value of ${e.token} is not a number`);return Zl(r)}throw new No(`${e.token} has no value`)}Ro.complex&&e.op.startsWith("\\:")&&ma[e.op.slice(2)]&&(e=go(ma[e.op.slice(2)],e.args));const r=e.args.map(e=>Wl(e,t,n));if(r.some(e=>e.z)||["re","im","conj","arg"].includes(e.op)||function(e,t){if(!Ro.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 Pl(e,r,t);const i=r.every(e=>e.q),s=e=>Bl(t,r[e]);switch(e.op){case"+":return i?Zl(r[0].q.add(r[1].q)):{f:s(0)+s(1)};case"-":return i?Zl(r[0].q.sub(r[1].q)):{f:s(0)-s(1)};case"neg":return r[0].q?Zl(r[0].q.neg()):{f:-r[0].f};case"*":return i?Zl(r[0].q.mul(r[1].q)):{f:t.mul(s(0),s(1))};case"/":return i?Zl(r[0].q.div(r[1].q)):{f:t.div(s(0),s(1))};case"^":return Vl(t,r[0],r[1]);case"sqrt":return Vl(t,r[0],Zl(_o.HALF));case"root":return Vl(t,r[1],r[0].q?Zl(r[0].q.inv()):{f:t.div(t.S,r[0].f)});case"abs":return r[0].q?Zl(r[0].q.abs()):{f:jl(r[0].f)};case"floor":return Zl(r[0].q?r[0].q.floor():new _o(Ul(r[0].f,t.S)));case"ceil":return Zl(r[0].q?r[0].q.ceil():new _o(-Ul(-r[0].f,t.S)));case"log":return{f:t.div(t.ln(s(1)),t.ln(s(0)))};case"atan2":return{f:Ll(t,s(0),s(1))};case"max":case"min":if(!r.length)throw new No(`${e.op} of nothing`);return i?Zl(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)=>s(t)).reduce((t,n)=>"max"===e.op?n>t?n:t:n<t?n:t)};case"sum":return i?Zl(r.reduce((e,t)=>e.add(t.q),_o.ZERO)):{f:r.reduce((e,t,n)=>e+s(n),0n)};case"prod":return i?Zl(r.reduce((e,t)=>e.mul(t.q),_o.ONE)):{f:r.reduce((e,n,r)=>t.mul(e,s(r)),t.S)};case"mean":if(!r.length)throw new No("mean of nothing");return i?Zl(r.reduce((e,t)=>e.add(t.q),_o.ZERO).div(new _o(BigInt(r.length)))):{f:r.reduce((e,t,n)=>e+s(n),0n)/BigInt(r.length)};case"mod":{if(i){if(r[1].q.isZero)throw new No("mod 0 is undefined");return Zl(r[0].q.sub(r[1].q.mul(r[0].q.div(r[1].q).floor())))}const e=s(1);if(0n===e)throw new No("mod 0 is undefined");return{f:s(0)-t.mul(e,Ul(t.div(s(0),e),t.S)*t.S)}}case"round":{if(!r[1].q?.isInteger)throw new No("round needs a whole number of places");const e=10n**jl(r[1].q.n),n=r[0].q??new _o(s(0),t.S),i=r[1].q.sign>=0,o=(i?n.mul(new _o(e)):n.div(new _o(e))).add(_o.HALF).floor();return Zl(i?o.div(new _o(e)):o.mul(new _o(e)))}case"!":{if(!r[0].q?.isInteger||r[0].q.sign<0)throw new No("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)&&Eo(e)>_l)throw Tl();return Zl(new _o(e))}default:{const n=Dl[e.op];if(!n||1!==r.length)throw new No(`no numeric value for ${e.op}`);return{f:n(t,s(0))}}}}const Ul=(e,t)=>{const n=e/t;return e<0n&&n*t!==e?n-1n:n};function Vl(e,t,n){if(n.q&&n.q.isInteger){if(t.q)return Zl(t.q.pow(n.q.n));let r=n.q.n;const i=r<0n;i&&(r=-r);let s=e.S,o=t.f;for(;r>0n;){if(1n&r&&(s=e.mul(s,o)),o=e.mul(o,o),Eo(s)>_l+4*e.P||Eo(o)>8e5){if(i)return{f:0n};throw Tl()}r>>=1n}return{f:i?e.div(e.S,s):s}}const r=Bl(e,t);if(0n===r){if(n.q?n.q.sign>0:n.f>0n)return Zl(_o.ZERO);throw new No("0 to a power that is not positive is undefined")}if(r<0n){if(n.q&&n.q.d%2n==1n){const t=Vl(e,{f:-r},n).f;return{f:n.q.n%2n==0n?t:-t}}throw new No("a negative number to a fractional power is not real")}if(n.q&&1n===jl(n.q.n)&&n.q.d<=64n){const t=jo(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(Bl(e,n),e.ln(r)))}}function Hl(e,t,n){const r=e<0n?"-":"",i=jl(e);if(0n===i)return{sign:"",digits:"0",point:1};const s=i.toString(),o=s.length-t.P;let a=s.slice(0,n);s.length>n&&s[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 Gl({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 Ql(e){let t=0n,n=0n,r=e.d;for(;r%2n==0n;)r/=2n,t++;for(;r%5n==0n;)r/=5n,n++;const i=t>n?t:n;let s=jl(e.n)*10n**i/e.d;if(0n===s)return 1;for(;s%10n==0n;)s/=10n;return s.toString().length}function Xl(e){let t=e.d;for(;t%2n==0n;)t/=2n;for(;t%5n==0n;)t/=5n;return 1n===t}function Jl(e){const t=/^(-?[\d.]+)e(-?\d+)$/.exec(e);return t?go("*",[po(t[1]),go("^",[po("10"),po(t[2])])]):po(e)}function Yl(e,{digits:t=15,scope:n}={}){if(!Number.isInteger(t)||t<1||t>1e5)throw new No("digits must be a whole number from 1 to 100000");let r=t+25,i=null;for(let s=0;s<4;s++){const o=new zl(r),a=Wl(e,o,n);if(a.z){const e=eu(a.z,o,t);if(e.retry&&s<3){r+=e.retry;continue}return void 0===e.real?e:Kl(e.real,o,t,null)}if(a.q&&a.q.isInteger&&jl(a.q.n).toString().length<=t)return{text:a.q.n.toString(),node:po(a.q.n.toString()),number:Number(a.q.n),re:Number(a.q.n),im:0,exact:!0};const l=Bl(o,a);if(0n===l&&(!a.q||!a.q.isZero)&&s<3){i=null,r*=4;continue}const u=Hl(l,o,t);if(i&&u.point<-10&&i.point-u.point>=(r-i.P)/2)return{text:"0",node:po("0"),number:0,re:0,im:0,exact:!1};if(!(u.point<-10&&s<3)||i&&i.point===u.point)return Kl(l,o,t,a.q);i={point:u.point,P:r},r+=10-u.point}throw new No("could not approximate")}function Kl(e,t,n,r){const i=Gl(Hl(e,t,n));return{text:i,node:Jl(i),number:Number(i),re:Number(i),im:0,exact:Boolean(r)&&Xl(r)&&Ql(r)<=n}}function eu([e,t],n,r){const i=10n**BigInt(Math.max(0,n.P-r-12)),s=e=>jl(e)>i;if(!s(t))return{real:e};const o=Hl(t,n,r);if(o.point<-10&&s(t))return{retry:10-o.point};const a=Gl(o),l="1"===a?"i":"-1"===a?"-i":`${a}i`,u="1"===a?ho("i"):go("*",[Jl(a.replace(/^-/,"")),ho("i")]);if(!s(e))return{text:l,node:a.startsWith("-")?go("neg",[u]):u,number:NaN,re:0,im:Number(a),exact:!1};const c=Gl(Hl(e,n,r)),h=a.startsWith("-"),p="1"===a.replace(/^-/,"")?ho("i"):go("*",[Jl(a.replace(/^-/,"")),ho("i")]);return{text:`${c} ${h?"-":"+"} ${l.replace(/^-/,"")}`,node:go(h?"-":"+",[Jl(c),p]),number:NaN,re:Number(c),im:Number(a),exact:!1}}function tu(e,t={}){const n=e=>(e=>0===Ea(e).size)(e)?"num"===e.type&&/^-?\d+$/.test(e.token)?e:Yl(e,t).node:bo(e)?go(e.op,e.args.map(n)):e;return n(e)}const nu={variable:null},ru=(e,t)=>null!==t&&Ea(e).has(t);function iu(e){if("num"===e.type)return To(e.token);if(bo(e)&&"/"===e.op&&e.args.every(e=>"num"===e.type)){const t=To(e.args[0].token),n=To(e.args[1].token);return t&&n&&!n.isZero?t.div(n):null}return null}const su=e=>0===Ea(e).size;function ou(e,t,n){const r=function(e){const t=$a(e);return"num"===t.k?t.q.isZero?t.q:null:"atom"===t.k&&"sym"===t.node.type&&"pi"===t.node.token?To("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[i,s="1"]=String(t).split("/");return n(r.compare(To(i).div(To(s))))}function au(e){if(!su(e))return NaN;try{const{number:t}=Yl(e,{digits:30});return Math.sign(t)}catch{return NaN}}function lu(){Wa("hasVariable")||(Ba("hasVariable",e=>ru(e,nu.variable),"mentions the variable being solved for"),Ba("freeOfVariable",e=>null!==nu.variable&&!ru(e,nu.variable),"does not mention the variable being solved for"),Ba("isRational",e=>null!==iu(e),"an exact number: 3, -2, 1/2"),Ba("isWhole",e=>iu(e)?.isInteger??!1,"a whole number (any size)"),Ba("isEvenWhole",e=>{const t=iu(e);return Boolean(t?.isInteger&&t.n%2n==0n)},"an even whole number"),Ba("isOddWhole",e=>{const t=iu(e);return Boolean(t?.isInteger&&t.n%2n!=0n)},"an odd whole number"),Ba("isPositiveRational",e=>(iu(e)?.sign??0)>0,"an exact number above 0"),Ba("isNegativeRational",e=>(iu(e)?.sign??0)<0,"an exact number below 0"),Ba("isConstant",su,"has no unknowns (numbers, π and e only)"),Ba("notOne",e=>{const t=iu(e);return!t||!t.isOne},"anything except the number 1"),Ba("notMinusOne",e=>{const t=iu(e);return!t||!t.equals(To("-1"))},"anything except the number -1"),Ba("hasMinusSign",e=>function(e){const t=$a(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"),Ba("piMultipleAtLeast",(e,t)=>ou(e,t,e=>e>=0),"a multiple of π, at least k·π"),Ba("piMultipleAbove",(e,t)=>ou(e,t,e=>e>0),"a multiple of π, above k·π"),Ba("piMultipleBelow",(e,t)=>ou(e,t,e=>e<0),"a multiple of π, below k·π"),Ba("piMultipleAtMost",(e,t)=>ou(e,t,e=>e<=0),"a multiple of π, at most k·π"),Ba("isPositiveConstant",e=>au(e)>0,"no unknowns, and above 0 (e, π, √2, 3)"),Ba("isNegativeConstant",e=>au(e)<0,"no unknowns, and below 0"),Ba("hasImaginaryPart",e=>{if(!Ro.complex)return!1;const t=pa($a(e));return Boolean(t)&&!("num"===t.im.k&&t.im.q.isZero)},"complex mode: has a nonzero imaginary part (unknowns count as real)"),Ba("isSymbolNode",e=>"sym"===e.type&&!Co.has(e.token),"a single unknown such as x"))}function uu(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=yo(e),n=e=>"num"===e.type||("sym"===e.type?e.token.startsWith("="):e.args.every(n)),r=e=>"sym"===e.type?ho(e.token.slice(1)):"num"===e.type?e:go(e.op,e.args.map(r)),i=e=>"sym"===e.type?ho(`=${e.token}`):"num"===e.type?e:go(e.op,e.args.map(i)),s=e=>"op"!==e.type?e:n(e)?i(ka(r(e))):go(e.op,e.args.map(s));return s(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 Al.fromSpecs(n,{strict:!0})}function cu(e,t,n,r){return e.explain?e.explain.replace(/\{(\w+)\}/g,(e,i)=>"result"===i?n?r(n):e:t[i]?r(t[i]):e).trim():""}const hu=e=>bo(e)&&("+"===e.op||"-"===e.op),pu=e=>bo(e)&&("*"===e.op||"/"===e.op);function*fu(e,t,{order:n="pre"}={}){for(const r of function(e,t,{order:n="post"}={}){const r=[];for(const{node:i,path:s}of Mo(e,n))for(const e of El(i,t))r.push({...e,node:i,path:s});return r}(e,t,{order:n})){const t=Il(r.rule.outputTemplate,r.bound);yield{rule:r.rule,bound:r.bound,path:r.path,before:r.node,after:t,next:()=>ka(Ao(e,r.path,t))}}for(const{node:r,path:i}of Mo(e,n)){const n=hu(r);if(!n&&!pu(r))continue;const s=n?Ia($a(r)):_a($a(r));if(s.length<3)continue;const o=n?ra:sa;for(let n=0;n<s.length;n++)for(let r=n+1;r<s.length;r++){const a=Na(o([s[n],s[r]]));for(const l of El(a,t)){const t=Il(l.rule.outputTemplate,l.bound),u=s.filter((e,t)=>t!==n&&t!==r);yield{rule:l.rule,bound:l.bound,path:i,before:a,after:t,next:()=>ka(Ao(e,i,Na(o([$a(t),...u]))))}}}}}function du(e,t,{format:n,order:r="pre",maxSteps:i=200,variable:s=null}={}){const o=nu.variable;nu.variable=s;try{let s=ka(e);const o=new Set([s.s]),a=[];for(let e=0;e<i;e++){let e=null;for(const n of fu(s,t,{order:r})){const t=n.next();if(t.s!==s.s&&!o.has(t.s)){e={c:n,next:t};break}}if(!e)break;const{c:i,next:l}=e;a.push({id:i.rule.id,name:i.rule.name,tags:i.rule.tags,from:s.s,to:l.s,path:i.path,before:i.before.s,after:i.after.s,explanation:cu(i.rule,i.bound,ka(i.after),n)}),s=l,o.add(s.s)}return{node:s,steps:a}}finally{nu.variable=o}}const mu={full:[],normal:["hidden"],brief:["hidden","tidy","identity","value","split","base","arithmetic"]},gu=(e,t)=>"all"===t||"*"===t||Array.isArray(t)&&t.some(t=>t===e.id||e.tags?.includes(t));function vu(e){if(!1===e)return null;if(void 0===e||!0===e)return{show:"all",hide:mu.normal,explain:!0};if("string"==typeof e){if(!mu[e])throw new Error(`steps: "${e}" is not one of ${Object.keys(mu).join(", ")}`);return{show:"all",hide:mu[e],explain:!0}}const t=e.detail??"normal";if(!mu[t])throw new Error(`steps.detail: "${t}" is not one of ${Object.keys(mu).join(", ")}`);return{show:e.show??"all",hide:[...mu[t],...e.hide??[]],explain:e.explain??!0}}function bu(e,t){if(!t)return[];const n=[];let r=null;for(const i of e){if(!(gu(i,t.show)&&!gu(i,t.hide))){r=r??{from:i.from,ids:[]},r.ids.push(i.id);continue}const e={...i};r&&(e.from=r.from,e.also=r.ids,e.path=null,r=null);!0===t.explain||!1!==t.explain&&gu(i,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 yu=Bo(_o.ONE),xu=(e,t)=>"atom"===e.k&&"sym"===e.node.type&&e.node.token===t;function wu(e){switch(e.k){case"num":default:return e;case"atom":return"op"===e.node.type?xa(e.node.op,e.node.args.map(e=>wu($a(e)))):e;case"add":return ra(Ia(e).map(wu));case"mul":{let t=[Bo(e.c)];for(const n of e.fs){const e=wu(n.b);if("add"===e.k&&Vo(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=$u(t,Ia(e));else t=$u(t,[aa(e,n.e)])}return ra(t)}}}function $u(e,t){const n=[];for(const r of e)for(const e of t)n.push(sa([r,e]));return Ia(ra(n))}function ku(e,t){const n=new Map;for(const r of Ia(wu(e))){const{coef:e,rest:i}=na(r);let s=0;const o=[Bo(e)];for(const e of i?_a(i):[]){const{b:n,e:r}="mul"===e.k&&1===e.fs.length&&e.c.isOne?e.fs[0]:{b:e,e:yu};if(xu(n,t)){if(!Vo(r)||!r.q.isInteger||r.q.sign<0)return null;s+=Number(r.q.n)}else{if(qu(n,t)||qu(r,t))return null;o.push(e)}}n.set(s,ra([n.get(s)??Bo(_o.ZERO),sa(o)]))}for(const[e,t]of n)Vo(t)&&t.q.isZero&&n.delete(e);return n}const qu=(e,t)=>Ea(Na(e)).has(t);function Mu(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)??Bo(_o.ZERO);if(!Vo(t))return null;n.push(t.q)}return n}function Au(e,t){const n=$a(ho(t));return ra(e.map((e,t)=>sa([Bo(e),oa(n,Bo(_o.of(t)))])))}const Nu=e=>{const t=e.slice();for(;t.length>1&&t[t.length-1].isZero;)t.pop();return t},Su=(e,t)=>e.reduceRight((e,n)=>e.mul(t).add(n),_o.ZERO);function Ou(e,t){const n=e.length-1,r=new Array(n);let i=_o.ZERO;for(let s=n;s>=1;s--)i=e[s].add(i.mul(t)),r[s-1]=i;return r}function Eu(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 i of r)for(let r=0,s=1n;r<=n;r++,s*=e)t.push(i*s);if(r=t,r.length>2e4)return null}return r.sort((e,t)=>e<t?-1:e>t?1:0)}function Iu(e){let t=Nu(e);const n=[];for(;t.length>1&&t[0].isZero;)n.push(_o.ZERO),t=t.slice(1);if(t.length<=1)return{roots:n,rest:t};const r=t.reduce((e,t)=>e*t.d/Io(e,t.d),1n),i=t.map(e=>e.n*r/e.d),s=Eu(i[0]),o=Eu(i[i.length-1]);if(!s||!o)return{roots:n,rest:t};const a=new Map;for(const e of s)for(const t of o)for(const n of[1n,-1n]){const r=new _o(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&&Su(t,e).isZero;)n.push(e),t=Ou(t,e);return{roots:n.sort((e,t)=>e.compare(t)),rest:t}}function _u(e){if("num"===e.k)return{coef:e.q,factors:[],notes:[]};if("atom"===e.k)return{coef:_o.ONE,factors:[{base:e,exp:yu}],notes:[]};if("mul"===e.k){let t=e.c;const n=[],r=[];for(const i of e.fs)if("add"===i.b.k&&Vo(i.e)&&i.e.q.isInteger){const e=_u(i.b);t=t.mul(e.coef.pow(i.e.q.n));for(const t of e.factors)n.push({base:t.base,exp:sa([t.exp,i.e])});r.push(...e.notes)}else n.push({base:i.b,exp:i.e});return Tu(t,n,r)}return function(e){const t=Ia(e),n=[],r=t.map(e=>{const{coef:t,rest:n}=na(e);return{coef:t,fs:n?_a(n).map(zu):[]}}),i=r.reduce((e,t)=>({n:Io(e.n,t.coef.n),d:e.d*t.coef.d/Io(e.d,t.coef.d)}),{n:0n,d:1n});let s=new _o(i.n||1n,i.d);ju(e)<0&&(s=s.neg());const o=[];for(const e of r[0].fs){if(!Vo(e.e)||e.e.q.sign<=0)continue;let t=e.e.q;const n=Qo(e.b);let i=!0;for(const e of r.slice(1)){const r=e.fs.find(e=>Qo(e.b)===n&&Vo(e.e)&&e.e.q.sign>0);if(!r){i=!1;break}r.e.q.compare(t)<0&&(t=r.e.q)}i&&o.push({base:e.b,exp:Bo(t)})}let a=e;if(!s.isOne||o.length){const e=sa([Bo(s),...o.map(e=>aa(e.base,e.exp))]);a=ra(t.map(t=>sa([t,oa(e,Bo(_o.MINUS_ONE))]))),n.push({id:"factor.common",values:{common:e}})}const l="add"===a.k?function(e,t){const n=[...Lu(e)];for(const r of n){const i=Mu(ku(e,r));if(!i||i.length<3)continue;if(1!==n.length)break;const{roots:s,rest:o}=Iu(i);if(!s.length)break;const a=[];let l=o[o.length-1]??_o.ONE;const u=o.map(e=>e.div(l)),c=[...s].sort((e,t)=>e.abs().compare(t.abs())||t.sign-e.sign);for(const e of c){const n=Au([new _o(-e.n),new _o(e.d)],r);a.push({base:n,exp:yu}),l=l.div(new _o(e.d)),t.push({id:"factor.root",values:{root:Bo(e),factor:n}})}if(u.length>1){const e=u.reduce((e,t)=>e*t.d/Io(e,t.d),1n),t=u.map(t=>t.mul(new _o(e))),n=t.reduce((e,t)=>Io(e,t.n),0n)||1n;l=l.mul(new _o(n,e)),a.push({base:Au(t.map(e=>e.div(new _o(n))),r),exp:yu})}return Tu(l,a,[])}const r=Ia(e);if(2===r.length){const[e,n]=r;for(const r of[2,3]){const i=Cu(e,r),s=Cu(ga(n),r),o=3===r?Cu(n,r):null;if(i&&s&&2===r){t.push({id:"factor.squares",values:{a:i,b:s}});const e=_u(ra([i,ga(s)])),n=_u(ra([i,s]));return Tu(e.coef.mul(n.coef),[...e.factors,...n.factors],[...e.notes,...n.notes])}if(3===r&&i&&(s||o)){const e=s??o,n=s?-1:1;t.push({id:n<0?"factor.cubes-difference":"factor.cubes-sum",values:{a:i,b:e}});const r=ra(n<0?[i,ga(e)]:[i,e]),a=ra([oa(i,Bo(_o.of(2))),n<0?sa([i,e]):ga(sa([i,e])),oa(e,Bo(_o.of(2)))]),l=_u(r);return Tu(l.coef,[...l.factors,{base:a,exp:yu}],l.notes)}}}return{coef:_o.ONE,factors:[{base:e,exp:yu}],notes:[]}}(a,n):_u(a);return Tu(s.mul(l.coef),[...o,...l.factors],[...n,...l.notes.filter(e=>!n.includes(e))])}(e)}function Tu(e,t,n){const r=new Map;for(const e of t){const t=Qo(e.base),n=r.get(t);n?n.exp=ra([n.exp,e.exp]):r.set(t,{...e})}return{coef:e,factors:[...r.values()].filter(e=>!(Vo(e.exp)&&e.exp.q.isZero)),notes:n}}const ju=e=>na(Ia(e)[0]).coef.sign;const zu=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length?{b:e.fs[0].b,e:e.fs[0].e}:{b:e,e:yu},Lu=e=>Ea(Na(e));function Cu(e,t){const{coef:n,rest:r}=na(e);if(n.sign<0)return null;const i=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 i=(n+r)/2n;i**BigInt(t)<=e?n=i:r=i}return n**BigInt(t)===e?n:null},r=n(e.n),i=n(e.d);return null!==r&&null!==i?new _o(r,i):null}(n,t);if(!i)return null;const s=[Bo(i)];for(const e of r?_a(r).map(zu):[]){if(!Vo(e.e))return null;const n=e.e.q.div(_o.of(t));if(!n.isInteger)return null;s.push(aa(e.b,Bo(n)))}return sa(s)}function Ru({coef:e,factors:t}){const n=[],r=[];for(const e of t){const t=Vo(e.exp)&&e.exp.q.sign<0,i=t?Bo(e.exp.q.neg()):e.exp,s=Na(aa(e.base,i));(t?r:n).push(s)}const i=e=>e.reduce((e,t)=>e?go("*",[e,t]):t,null),s=e.n<0n?-e.n:e.n;let o=n.length?i(1n===s?n:[Na(Bo(new _o(s))),...n]):Na(Bo(new _o(s)));return e.n<0n&&(o=go("neg",[o])),1n!==e.d&&r.unshift(Na(Bo(new _o(e.d)))),r.length?go("/",[o,i(r)]):o}function Zu(e){if("mul"!==e.k)return{num:e,den:yu};const t=[Bo(new _o(e.c.n))],n=[Bo(new _o(e.c.d))];for(const r of e.fs)Vo(r.e)&&r.e.q.sign<0?n.push(aa(r.b,Bo(r.e.q.neg()))):t.push(aa(r.b,r.e));return{num:sa(t),den:sa(n)}}function Fu(e){if("add"!==e.k)return Zu(e);const t=Ia(e).map(Zu),n=new Map;let r=1n;for(const e of t){const{coef:t,rest:i}=na(e.den);r=r*t.n/Io(r,t.n);for(const e of i?_a(i).map(zu):[]){const t=Qo(e.b),r=n.get(t);(!r||Vo(e.e)&&Vo(r.e)&&e.e.q.compare(r.e.q)>0)&&n.set(t,e)}}const i=sa([Bo(new _o(r)),...[...n.values()].map(e=>aa(e.b,e.e))]);if(Vo(i)&&i.q.isOne)return{num:e,den:yu};const s=wu(ra(t.map(e=>sa([e.num,i,oa(e.den,Bo(_o.MINUS_ONE))]))));return{num:s,den:i}}function Pu(e){const{num:t,den:n}=Fu(e);if(Vo(n)&&n.q.isOne)return null;const r=_u(t),i=_u(n),s=new Set(r.factors.map(e=>Qo(e.base))),o=i.factors.filter(e=>s.has(Qo(e.base))),a=[...r.factors,...i.factors.map(e=>({base:e.base,exp:ga(e.exp)}))];return{...Tu(r.coef.div(i.coef),a,[...r.notes,...i.notes]),cancelled:o.map(e=>e.base)}}const Bu=(e,t)=>go("=",[e,t]),Du=ka(go("+",[ho("x"),go("neg",[ho("x")])])),Wu=e=>bo(e)&&"="===e.op;function Uu(e,t,n,r={}){const i=[],s=(t,n,r,s,o,a={})=>i.push(e.step(t,n,r,s,o,a));s.raw=e=>i.push(e);const o=Wu(t)?t:Bu(t,Du),a=Bu(ka(o.args[0]),ka(o.args[1]));a.s!==o.s&&s("normal","Work out each side",["tidy","arithmetic"],o,a);const l=[],u=[],c=new Set;l.numeric=c,Ju(e,a,n,r,s,l,u,0);const h=[],p=new Set;for(const t of l.map(t=>c.has(t)?t:(t=>du(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:Gu(o,n,t);r?s("solve.reject","Check the answer",["check"],Bu(ho(n),t),Bu(ho(n),t),{value:t,reason:r}):h.push(t)}return h.sort(Vu),{solutions:h,unsolved:u,steps:i,always:u.some(e=>e.always)}}function Vu(e,t){const n=Hu(e),r=Hu(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 Hu(e){if(Ea(e).size)return null;try{const{re:t,im:n}=Yl(e,{digits:20});return{re:t,im:n}}catch{return null}}function Gu(e,t,n){const[r,i]=e.args,s=new Set([...Ea(r),...Ea(i),...Ea(n)]);if(s.delete(t),s.size)return null;const o=e=>Qu(e,t,n);try{const e=Yl(o(r),{digits:40}),t=Yl(o(i),{digits:40}),n=Math.max(1,Math.hypot(e.re,e.im),Math.hypot(t.re,t.im));return Math.hypot(e.re-t.re,e.im-t.im)>1e-12*n?"it does not make the two sides equal":null}catch(e){return`the original equation has no value there (${e.message})`}}function Qu(e,t,n){return"sym"===e.type?e.token===t?n:e:bo(e)?go(e.op,e.args.map(e=>Qu(e,t,n))):e}const Xu=24;function Ju(e,t,n,r,i,s,o,a){if(a>Xu)return ic(e,t,n,r,i,s,o);const l=function(e){const t=[],n=e=>{if(bo(e)&&"|"===e.op)return void e.args.forEach(n);if(!Wu(e))return void t.push(e);const r=e.args[1],i=Mo(r,"pre").find(({node:e})=>bo(e)&&"pm"===e.op);if(!i)return void t.push(e);const s=i.node.args[0],o=ka(Ao(r,i.path,s)),a=ka(Ao(r,i.path,go("neg",[s])));n(Bu(e.args[0],o)),a.s!==o.s&&n(Bu(e.args[0],a))};return n(e),t}(t);if(l.length>1){i("solve.split","Two cases",["split"],t,l.reduce((e,t)=>e?go("|",[e,t]):t,null));for(const t of l)Ju(e,t,n,r,i,s,o,a+1);return}if(1===l.length&&l[0].s!==t.s)return Ju(e,l[0],n,r,i,s,o,a+1);const[u,c]=t.args;if("sym"===u.type&&u.token===n&&!qu($a(c),n))return void s.push(c);const h=ra([$a(u),ga($a(c))]);if(!qu(h,n))return Vo(h)&&h.q.isZero?(i("solve.always","Always true",["check"],t,t,{v:n}),void o.push(Object.assign(Object.create(t),{always:!0}))):void i("solve.never","No solution",["check"],t,t,{v:n});const p=Ia(h).filter(e=>qu(e,n)),f=Ia(h).filter(e=>!qu(e,n)),d=ra(p),m=ga(ra(f));if(Ro.complex){const l=ku(h,n);if(l&&[...l.values()].every(e=>!qu(e,n))&&Math.max(...l.keys())>=2){const u=Bu(Na(h),Du);return u.s!==t.s&&i("solve.one-side","Everything on one side",["move"],t,u,{v:n}),nc(e,h,l,n,r,i,s,o,a,u)}}if(1===p.length)return Yu(e,t,d,m,n,r,i,s,o,a);const g=Bu(Na(h),Du),v=ku(h,n);if(v&&[...v.values()].every(e=>!qu(e,n))&&Math.max(...v.keys())>=2)return g.s!==t.s&&i("solve.one-side","Everything on one side",["move"],t,g,{v:n}),nc(e,h,v,n,r,i,s,o,a,g);const b=_u(h),y=b.factors.filter(e=>qu(e.base,n)&&!(Vo(e.exp)&&e.exp.q.sign<0));if(y.length>=2||1===y.length&&b.factors.length>1){const l=Bu(Ru(b),Du);g.s!==t.s&&i("solve.one-side","Everything on one side",["move"],t,g,{v:n}),l.s!==g.s&&i("solve.factor","Factor",["factor"],g,l,{});const u=y.map(e=>Bu(Na(e.base),Du));u.length>1&&i("solve.zero-product","A product is zero when a factor is",["split"],l,u.reduce((e,t)=>e?go("|",[e,t]):t,null),{});for(const t of u)Ju(e,t,n,r,i,s,o,a+1);return}const x=Fu(h);if(qu(x.den,n)){const l=Bu(Na(x.num),Du);return i("solve.clear-denominator","Clear the denominator",["move"],t,l,{den:Na(x.den)}),Ju(e,l,n,r,i,s,o,a+1)}const w=p.filter(e=>!tc(e,n));if(1===w.length&&/\b(sqrt|root|abs)\b/.test(Na(w[0]).s))return Yu(e,t,w[0],ga(ra(Ia(h).filter(e=>e!==w[0]))),n,r,i,s,o,a);const $=function(e,t){const n=Na(e),r=new Map;for(const{node:e}of Mo(n,"pre"))if(bo(e)&&Ea(e).has(t))if("^"!==e.op||Ea(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=$a(e.args[1]),{coef:i,rest:s}=na(n);if(s&&i.isInteger&&Na(s).s===t){const n=Na(oa($a(e.args[0]),$a(ho(t))));r.set(n.s,n)}}const i="u"===t?"w":"u";for(const e of r.values()){const r=rc(n,e,t,i);if(!r||Ea(r).has(t))continue;const s=$a(r),o=ku(s,i);if(o&&Math.max(...o.keys())>=1)return{kernel:$a(e),poly:s,symbol:i}}return null}(h,n);if($){const t=$.symbol;i("solve.substitute","Substitute",["substitute"],g,Bu(Na($.poly),Du),{u:ho(t),kernel:Na($.kernel)});const l=[];Ju(e,Bu(Na($.poly),Du),t,r,i,l,o,a+1);for(const t of l)Ju(e,Bu(Na($.kernel),t),n,r,i,s,o,a+1);return}return ic(e,g,n,r,i,s,o)}function Yu(e,t,n,r,i,s,o,a,l,u){let c=Bu(Na(n),Na(r));c.s!==t.s&&o("solve.move","Move the terms",["move"],t,c,{v:i});const{coef:h,rest:p}=na(n),f=p?_a(p):[],d=sa([Bo(h),...f.filter(e=>!qu(e,i))]);if(!Vo(d)||!d.q.isOne){const e=sa(f.filter(e=>qu(e,i))),t=Bu(Na(e),Na(va(r,d))),n=Vo(d)&&!d.q.isInteger&&(1n===d.q.n||-1n===d.q.n);o(n?"solve.multiply":"solve.divide",n?"Multiply both sides":"Divide both sides",["move"],c,t,{by:Na(n?Bo(d.q.inv()):d),v:i}),c=t}if("sym"===c.args[0].type&&c.args[0].token===i)return void a.push(c.args[1]);const m=$a(c.args[1]);if(Vo(m)&&m.q.isZero){const t=$a(c.args[0]),n=_a(t).filter(e=>qu(e,i)&&!Ku(e));if(n.length>1||n.length<_a(t).filter(e=>qu(e,i)).length){const t=n.map(e=>Bu(Na(ec(e)),Du));o("solve.zero-product","A product is zero when a factor is",["split"],c,t.reduce((e,t)=>e?go("|",[e,t]):t,null),{});for(const n of t)Ju(e,n,i,s,o,a,l,u+1);return}}const g=du(c,e.set.view("isolate"),{format:e.format,maxSteps:1,variable:i});return g.steps.length?(function(e,t){for(const n of t)e.raw(n)}(o,g.steps),Ju(e,g.node,i,s,o,a,l,u+1)):ic(e,c,i,s,o,a,l)}const Ku=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&Vo(e.fs[0].e)&&e.fs[0].e.q.sign<0,ec=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&Vo(e.fs[0].e)&&e.fs[0].e.q.sign>0?e.fs[0].b:e,tc=(e,t)=>{const n=ku(e,t);return Boolean(n)&&[...n.values()].every(e=>!qu(e,t))};function nc(e,t,n,r,i,s,o,a,l,u){const c=Math.max(...n.keys()),h=Mu(n);if(Ro.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=oa(Bo(t.abs()),Bo(new _o(1n,BigInt(c)))),i=[];for(let r=0;r<c;r++){const s=sa([Bo(new _o(BigInt((t.sign<0?1:0)+2*r),BigInt(c))),$a(ho("pi"))]),o=go("*",[Na(n),go("+",[go("cos",[Na(s)]),go("*",[ho("i"),go("sin",[Na(s)])])])]);i.push(du(o,e.set.view("simplify"),{format:e.format}).node)}return s("solve.roots","All n roots",["complex"],u,i.map(e=>Bu(ho(r),e)).reduce((e,t)=>e?go("|",[e,t]):t),{v:r,n:String(c),last:String(c-1),r:Na(Bo(t))}),void o.push(...i)}if(h){const{roots:n}=Iu(h);if(n.length){const n=_u(t),c=Bu(Ru(n),Du);if(n.factors.length>1||n.factors.some(e=>!(Vo(e.exp)&&e.exp.q.isOne))){s("solve.factor","Factor",["factor"],u,c,{});const t=n.factors.filter(e=>qu(e.base,r)).map(e=>Bu(Na(e.base),Du));t.length>1&&s("solve.zero-product","A product is zero when a factor is",["split"],c,t.reduce((e,t)=>e?go("|",[e,t]):t,null),{});for(const n of t)Ju(e,n,r,i,s,o,a,l+1);return}}}if(2===c){const e=n.get(2),t=n.get(1)??Bo(_o.ZERO),i=n.get(0)??Bo(_o.ZERO),a=ra([oa(t,Bo(_o.of(2))),sa([Bo(_o.of(-4)),e,i])]);if(Vo(a)&&a.q.sign<0&&!Ro.complex)return void s("solve.no-real","No real solutions",["quadratic"],u,u,{D:Na(a)});const l=sa([Bo(_o.of(2)),e]),c=oa(a,Bo(_o.HALF)),h=Na(va(ra([ga(t),c]),l)),p=Na(va(ra([ga(t),ga(c)]),l)),f=h.s===p.s?Bu(ho(r),h):go("|",[Bu(ho(r),h),Bu(ho(r),p)]);return s(Ro.complex&&Vo(a)&&a.q.sign<0?"solve.quadratic-complex":"solve.quadratic","The quadratic formula",["quadratic"],u,f,{a:Na(e),b:Na(t),c:Na(i),D:Na(a),root:Na(c),v:r}),o.push(h),void(p.s!==h.s&&o.push(p))}return ic(e,u,r,i,s,o,a)}function rc(e,t,n,r){if(e.s===t.s)return ho(r);if(!bo(e))return e;if("^"===e.op&&"^"===t.op&&e.args[0].s===t.args[0].s){const t=$a(e.args[1]),{coef:i,rest:s}=na(t);if(s&&Na(s).s===n&&i.isInteger)return go("^",[ho(r),Na(Bo(i))])}return go(e.op,e.args.map(e=>rc(e,t,n,r)))}function ic(e,t,n,r,i,s,o){if(r.approximate){const e="number"==typeof r.approximate?r.approximate:15,o=$a(go("-",[t.args[0],t.args[1]])),a=Ro.complex?Mu(ku(o,n)):null,l=a&&a.length>2?function(e,t){const n=e.length-1,r=e[n],i=e.map(e=>e/r),s=(e,t)=>{let r=1,s=0;for(let o=n-1;o>=0;o--)[r,s]=[r*e-s*t+i[o],r*t+s*e];return[r,s]};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],i)=>{let[a,l]=s(t,r);for(let e=0;e<n;e++){if(e===i)continue;const n=t-o[e][0],s=r-o[e][1],u=n*n+s*s;[a,l]=[(a*n+l*s)/u,(l*n-a*s)/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=sc(e);if(0===t)return n;const r=go("*",[sc(Math.abs(t)),ho("i")]);return 0===e?t<0?go("neg",[r]):r:go(t<0?"-":"+",[n,r])})}(a.map(e=>e.toNumber()),Math.min(e,14)):function(e,t,n){const r=$a(go("-",[e.args[0],e.args[1]])),i=Na(r),s=e=>{try{return Yl(Qu(i,t,oc(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],i=s(t);const l=s(r);if(Number.isNaN(i)||Number.isNaN(l))continue;if(0===i){o.push(oc(t));continue}if(i*l>0)continue;for(let e=0;e<200&&r-t>1e-16*Math.abs(t);e++){const e=(t+r)/2,n=s(e);if(Number.isNaN(n))break;i*n<=0?r=e:(t=e,i=n)}const u=(t+r)/2;Math.abs(s(u))<1e-6&&o.push(oc(Number(u.toPrecision(Math.min(n,15)))))}return o}(t,n,e);for(const e of l)s.numeric?.add(e);return i("solve.numeric","Numeric solutions",["numeric"],t,l.length?l.map(e=>Bu(ho(n),e)).reduce((e,t)=>e?go("|",[e,t]):t):t,{v:n,count:String(l.length)}),void s.push(...l)}i("solve.unsolved","No exact method",["unsolved"],t,t,{v:n}),o.push(t)}const sc=e=>po(String(e).includes("e")?e.toFixed(20):String(e)),oc=e=>po(Number.isInteger(e)?String(e):e.toFixed(17));const ac=(e,t)=>go("int",[e,"string"==typeof t?ho(t):t]);function lc(e,t,n,r=0){if(r>6)throw new No("integration went too deep");const i=[],s=e.set.view("integrate"),o=du(t,e.set.view("simplify"),{format:e.format});i.push(...o.steps);let a=ka(ac(o.node,n));for(let t=0;t<40;t++){const t=du(a,s,{format:e.format});i.push(...t.steps),a=t.node;const n=Mo(a,"pre").find(({node:e})=>{return bo(t=e)&&"int"===t.op&&2===t.args.length;var t});if(!n)return{node:a,steps:i};const o=uc(e,n.node,r);if(!o)throw new No(`no rule for ∫ ${e.format(n.node.args[0])} d${n.node.args[1].token}`);i.push(...o.steps),a=ka(Ao(a,n.path,o.node))}throw new No("integration did not finish")}function uc(e,t,n){const[r,i]=t.args,s=i.token,o=$a(r),a=function(e,t){const{num:n,den:r}=Fu(e),i=_u(n),s=_u(r),o=i.coef.div(s.coef);if(o.isOne||!qu(e,t))return null;const a=sa([...i.factors.map(e=>aa(e.base,e.exp)),...s.factors.map(e=>aa(e.base,ga(e.exp)))]);return{c:o,rest:a}}(o,s);if(a){const n=go("*",[Na(Bo(a.c)),ac(Na(a.rest),i)]);return{node:n,steps:[e.step("integrate.constant","Take the number out",["split"],t,n,{c:Na(Bo(a.c))})]}}const l=wu(o);if(Na(l).s!==r.s&&"add"===l.k){const n=ac(Na(l),i);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 Mo(e,"pre")){if(!bo(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||!Ea(r).has(t))continue;const e=ku($a(r),t);if(!e||1!==Math.max(...e.keys()))continue;const i=e.get(1);qu(i,t)||Vo(i)&&i.q.isZero||n.set(r.s,{node:r,a:i})}}for(const r of n.values()){if(!Ea(cc(e,r.node,ho("§"))).has(t))return r}return null}(r,s);if(u){const i="u"===s?"t":"u",o=cc(r,u.node,ho(i));if(!Ea(o).has(s)){const r=lc(e,ka(o),i,n+1),a=ka(Qu(r.node,i,u.node)),l=Na(va($a(a),u.a));return{node:l,steps:[e.step("integrate.substitute","Substitute",["substitute"],t,ka(ac(o,i)),{u:ho(i),inside:u.node,a:Na(u.a),v:s}),...r.steps,e.step("integrate.back","Substitute back",["substitute"],r.node,l,{u:ho(i),inside:u.node})]}}}const c=function(e,t,n,r){const{num:i,den:s}=Fu(n);if(!qu(s,r))return null;const o=Mu(ku(i,r)),a=Mu(ku(s,r));if(!o||!a||a.length<2)return null;const l=$a(ho(r)),u=e=>Au(e,r);if(o.length>=a.length){const{q:n,r:i}=function(e,t){const n=Nu(t);let r=Nu(e);const i=n[n.length-1];if(i.isZero)throw new No("division by the zero polynomial");const s=new Array(Math.max(1,r.length-n.length+1)).fill(_o.ZERO);for(;r.length>=n.length&&(1!==r.length||!r[0].isZero);){const e=r.length-n.length,t=r[r.length-1].div(i);if(s[e]=t,r=Nu(r.map((r,i)=>i>=e&&i-e<n.length?r.sub(t.mul(n[i-e])):r)),r.length-1<e+n.length-1&&r[r.length-1].isZero)break;if(r.length<n.length)break}return{q:Nu(s),r:r}}(o,a),s=ac(Na(ra([u(n),va(u(i),u(a))])),ho(r));return{node:s,steps:[e.step("integrate.divide","Divide the polynomials",["divide"],t,s,{})]}}const{roots:c,rest:h}=Iu(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?[_o.ZERO]:e.slice(1).map((e,t)=>e.mul(_o.of(t+1))))(a),d=c.map(e=>va(Bo(Su(o,e).div(Su(f,e))),ra([l,Bo(e.neg())]))),m=ac(Na(ra(d)),ho(r));return{node:m,steps:[e.step("integrate.partial-fractions","Partial fractions",["partial-fractions"],t,m,{})]}}(e,t,o,s);return c||function(e,t,n,r,i){if(i>=6)return null;const s=_a(n),o=s.filter(e=>hc(e,r)||!qu(e,r)),a=s.filter(e=>!o.includes(e));if(1!==a.length)return null;const l=sa(o),u=a[0];if(!qu(l,r))return null;const c=Na(u),h=bo(c)?c.op:"";let p,f,d;"ln"===h||"arctan"===h||"arcsin"===h?(p=u,f=l):(p=l,f=u);try{d=lc(e,Na(f),r,i+1)}catch{return null}const m=$a(e.differentiate(Na(p),r)),g=sa([p,$a(d.node)]),v=ac(Na(sa([m,$a(d.node)])),ho(r)),b=ka(go("-",[Na(g),v]));return{node:b,steps:[e.step("integrate.parts","Integration by parts",["parts"],t,b,{u:Na(p),dv:Na(f),V:d.node,du:Na(m),v:r})]}}(e,t,o,s,n)}function cc(e,t,n){return e.s===t.s?n:bo(e)?go(e.op,e.args.map(e=>cc(e,t,n))):e}const hc=(e,t)=>{const n=ku(e,t);return Boolean(n)&&[...n.values()].every(e=>!qu(e,t))&&Math.max(...n.keys())>=1};function pc(e,t,n,r,i,s){for(const e of[r,i])if(Ea(e).has("∞")||/∞|infinity/.test(e.s))throw new No("integrals to infinity need limits, which this CAS does not do yet");if(s&&!Ea(r).size&&!Ea(i).size){const o=Yl(r,{digits:20}).number,a=Yl(i,{digits:20}).number,l=[...Ea(s)].filter(e=>e!==n);if(!l.length){const[r,i]=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 Mo(e,"pre").forEach(({node:e})=>{if(!bo(e))return;let i=null;"/"===e.op?i=e.args[1]:"^"===e.op&&"num"===e.args[1].type&&e.args[1].value<0||"^"===e.op&&bo(e.args[1])&&"neg"===e.args[1].op?i=e.args[0]:r[e.op]&&(i=go(r[e.op],[e.args[0]])),i&&Ea(i).has(t)&&!n.some(e=>e.s===i.s)&&n.push(i)}),n}(s,n)){let s=[];try{s=e.solve(go("=",[o,po("0")]),n,{steps:!1}).solutions}catch{continue}for(const o of s){const s=Yl(o,{digits:20});if(!Number.isFinite(s.number)||s.im||s.number<r||s.number>i)continue;if(s.number>r&&s.number<i)throw new No(`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=Yl(ka(Qu(t,n,o)),{digits:15}).number}catch{}if(!Number.isFinite(a))throw new No(`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=Yl(Qu(s,n,po(t.toFixed(15))),{digits:15}).number;if(!Number.isFinite(e))throw new No("not finite")}catch(e){throw new No(`the integrand has no value at ${n} = ${t.toPrecision(6)}, between the limits, so F(b) - F(a) would be wrong`)}}}const o=e=>ka(Qu(t,n,e)),a=ka(go("-",[o(i),o(r)])),l=go("-",[o(i),o(r)]);return{value:a,step:e.step("integrate.evaluate","Between the limits",["evaluate"],t,l,{a:r,b:i,F:t,v:n})}}const fc={"=":1,"≠":1,"<":1,">":1,"≤":1,"≥":1,"+":2,"-":2,"±":2,"*":3,"/":3,neg:4,pm:4,"^":5},dc={pi:"π","≤":"≤","≥":"≥"};function mc(e){return xc(e).text}function gc(e,t,n=!1){return e.prec<t||n&&e.prec===t?`(${e.text})`:e.text}const vc=e=>"op"===e.type?e.op:null,bc=e=>e.text.startsWith("-"),yc={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]};function xc(e){if("num"===e.type)return{text:e.token,prec:e.token.startsWith("-")?4:9};if("sym"===e.type)return{text:dc[e.token]??e.token,prec:9};const t=e.args.map(xc),n=fc[e.op];switch(e.op){case"+":case"-":case"±":{const r="+"===e.op&&["+","-"].includes(vc(e.args[1])),i=bc(t[1])?`(${t[1].text})`:r?t[1].text:gc(t[1],n,!0);return{text:`${gc(t[0],n)} ${"±"===e.op?"±":e.op} ${i}`,prec:n}}case"*":{const r=gc(t[0],n),i=bc(t[1])?`(${t[1].text})`:"*"===vc(e.args[1])?t[1].text:gc(t[1],n,!0);return{text:"num"===e.args[0].type&&"num"!==e.args[1].type&&!/^[\d(-]/.test(i)||"sym"===e.args[1].type&&"i"===e.args[1].token&&!/[\dA-Za-z]$/.test(r)?`${r}${i}`:`${r}·${i}`,prec:n}}case"/":return{text:`${gc(t[0],n)}/${gc(t[1],n,!0)}`,prec:n};case"^":return{text:`${gc(t[0],n+1)}^${gc(t[1],n)}`,prec:n};case"neg":return{text:`-${gc(t[0],3)}`,prec:4};case"pm":return{text:`±${gc(t[0],4)}`,prec:4};case"!":return{text:`${gc(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:`${gc(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:`${yc[e.op][0]}${t.map(e=>e.text).join(", ")}${yc[e.op][1]}`,prec:9};case"&":return{text:`${t[0].text} and ${t[1].text}`,prec:0};default:return void 0!==n?{text:`${gc(t[0],n)} ${e.op} ${gc(t[1],n,!0)}`,prec:n}:{text:`${e.op.replace(/^\\:?/,"")}(${t.map(e=>e.text).join(", ")})`,prec:9}}}const wc=['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'],$c=['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'],kc={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."},qc=["normal","rewrite","simplify","expand","factor","cancel","diff","differentiate","integrate","solve","solveSystem","substitute","approximate","equivalent"];class Mc{constructor(e,t,n,r,i){this.set=e,this.messages=t,this.format=n,this.read=r,this.complex=i;for(const e of qc){const t=Mc.prototype[e];this[e]=(...e)=>Zo(i,()=>t.apply(this,e))}}node(e){if(e&&"object"==typeof e&&!Array.isArray(e)&&e.type)return e;if(Array.isArray(e))return xo(e);if("string"!=typeof e)throw new No("expected an expression");if(this.read){const t=this.read(e);return Array.isArray(t)?xo(t):"string"==typeof t?yo(t):t}return yo(e)}step(e,t,n,r,i,s={}){return function(e,t,n,r,i,s,o,a,l=[]){const u=(s??"").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:i.s,path:l,before:r.s,after:i.s,explanation:u}}(e,t,n,r,i,this.messages[e]??"",s,this.format)}result(e,t,n,r={}){let i=e;if(n.approximate&&i){i=tu(i,{digits:"number"==typeof n.approximate?n.approximate:15})}return{result:i,text:i?this.format(i):"",steps:bu(t,vu(n.steps)),...r}}variable(e,t){if(t)return t;const n=[...Ea(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 ka(this.node(e))}rewrite(e,t,n={}){const r=this.node(e),i=this.set.view(t);if(!i.size)throw new No(`no rules in mode "${t}" (modes: ${this.set.modes().join(", ")})`);const s=du(r,i,{format:this.format,order:n.order,variable:n.variable});return this.result(s.node,[...this.tidyStep(r,ka(r)),...s.steps],n)}simplify(e,t={}){const n=this.node(e),r=[...this.tidyStep(n,ka(n))],i=du(n,this.set.view("simplify"),{format:this.format});r.push(...i.steps);let s=i.node,o=null;const a=$a(s),l=[],u=0===Ea(s).size,c=u?null:Pu(a);c&&l.push({node:Ru(c),id:"simplify.cancel",name:"Cancel"});const h=du(Na(wu(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:Ru(_u(a)),id:"simplify.factor",name:"Factor"});for(const e of l)$o(e.node)<$o(s)&&(o=this.step(e.id,e.name,["shorter"],s,e.node),s=e.node);return o&&r.push(o),this.result(s,r,t)}expand(e,t={}){const n=this.node(e),r=Na(wu($a(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=_u($a(n)),i=Ru(r),s=[],o=r.notes.find(e=>"factor.common"===e.id);return i.s!==ka(n).s&&s.push(this.step(o?"factor.common":"factor","Factor",["factor"],n,i,o?{common:Na(o.values.common)}:{})),this.result(i,s,t)}cancel(e,t={}){const n=this.node(e),r=$a(n),i=Pu(r);if(!i)return this.result(ka(n),this.tidyStep(n,ka(n)),t);const s=Ru(i),o=Fu(r),a=go("/",[Na(o.num),Na(o.den)]),l=[];return"/"===n.op&&a.s===ka(n).s||l.push(this.step("together","One fraction",["together"],n,a)),s.s!==a.s&&l.push(this.step("cancel","Cancel",["cancel"],a,s,{cancelled:i.cancelled.length?i.cancelled.map(e=>this.format(Na(e))).join(", "):"numbers"})),this.result(s,l,t)}diff(e,t,n={}){const r=this.node(e),i=this.variable(r,t);let s=r;const o=[];for(let e=0;e<(n.order??1);e++){const e=du(go("der",[s,ho(i)]),this.set.view("differentiate"),{format:this.format,order:"pre"}),t=du(e.node,this.set.view("simplify"),{format:this.format});o.push(...e.steps,...t.steps),s=t.node}return this.result(s,o,n,{variable:i})}differentiate(e,t){const n=du(go("der",[e,ho(t)]),this.set.view("differentiate"),{format:this.format,order:"pre"});return du(n.node,this.set.view("simplify"),{format:this.format}).node}integrate(e,t,n={}){let r=this.node(e);const i=e=>void 0===e?null:this.node("number"==typeof e?String(e):e);let s=i(n.from),o=i(n.to);if(bo(r)&&"int"===r.op){const[e,n,i,a]=r.args;t=n.token,i&&a&&(s=i,o=a),r=e}const a=this.variable(r,t),l=lc(this,r,a),u=du(l.node,this.set.view("simplify"),{format:this.format}),c=[...l.steps,...u.steps];if(s&&o){const e=pc(this,u.node,a,s,o,r);c.push(e.step);const t=du(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=go("+",[h,ho(String(n.constant))])),this.result(h,c,n,{variable:a})}solve(e,t,n={}){const r=this.node(e),i=this.variable(r,t),s=Uu(this,r,i,n);let o=s.solutions;if(n.approximate){const e="number"==typeof n.approximate?n.approximate:15;o=o.map(t=>tu(t,{digits:e}))}const a=o.map(e=>go("=",[ho(i),e])),l=a.length?a.reduce((e,t)=>e?go("|",[e,t]):t,null):null;return{solutions:o,result:l,variable:i,text:s.always?`true for every ${i}`:l?this.format(l):s.unsolved.length?`no exact solution found for ${i}`:"no solution",unsolved:s.unsolved.filter(e=>!e.always),always:s.always,steps:bu(s.steps,vu(n.steps))}}solveSystem(e,t,n={}){const r=e.map(e=>this.node(e)),i=t??[...new Set(r.flatMap(e=>[...Ea(e)]))].sort(),s=function(e,t,n){const r=[],i=t.map(t=>{const r=Wu(t)?ra([$a(t.args[0]),ga($a(t.args[1]))]):$a(t),i=n.map(t=>{const n=ku(r,t);if(!n||Math.max(0,...n.keys())>1)throw new No(`not linear in ${t}`);const i=n.get(1)??Bo(_o.ZERO);if(!Vo(i))throw new No(`the coefficient of ${t} must be a number (it is ${e.format(Na(i))})`);return i.q});let s=r;for(let e=0;e<n.length;e++)s=ra([s,sa([Bo(i[e].neg()),$a(ho(n[e]))])]);for(const e of n)if(qu(s,e))throw new No(`not linear in ${e}`);return{coeffs:i,rhs:ga(s)}}),s=()=>i.map(e=>Bu(Na(ra(e.coeffs.map((e,t)=>sa([Bo(e),$a(ho(n[t]))])))),Na(e.rhs))).reduce((e,t)=>e?go("&",[e,t]):t,null);let o=0;const a=[];for(let t=0;t<n.length&&o<i.length;t++){const l=i.findIndex((e,n)=>n>=o&&!e.coeffs[t].isZero);if(l<0)continue;[i[o],i[l]]=[i[l],i[o]];const u=s(),c=i[o],h=c.coeffs[t];c.coeffs=c.coeffs.map(e=>e.div(h)),c.rhs=sa([Bo(h.inv()),c.rhs]);for(let e=0;e<i.length;e++){if(e===o||i[e].coeffs[t].isZero)continue;const n=i[e].coeffs[t];i[e].coeffs=i[e].coeffs.map((e,t)=>e.sub(n.mul(c.coeffs[t]))),i[e].rhs=ra([i[e].rhs,sa([Bo(n.neg()),c.rhs])])}r.push(e.step("system.eliminate","Eliminate",["eliminate"],u,s(),{v:ho(n[t])})),a.push(t),o++}for(const e of i.slice(o))if(!Vo(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],Na(i[t].rhs))),{solution:l,steps:r,status:"one"}}(this,r,i),o=s.solution?Object.fromEntries([...s.solution].map(([e,t])=>[e,t])):null,a="one"===s.status?i.map(e=>`${e} = ${this.format(o[e])}`).join(", "):"none"===s.status?"no solution":"infinitely many solutions";return{solution:o,status:s.status,text:a,steps:bu(s.steps,vu(n.steps))}}substitute(e,t,n={}){const r=this.node(e);let i=r;for(const[e,n]of Object.entries(t))i=Qu(i,e,"number"==typeof n?this.node(String(n)):this.node(n));const s=this.simplify(i,n),o=[this.step("substitute","Substitute",["substitute"],r,i)];return{...s,steps:[...bu(o,vu(n.steps)),...s.steps]}}defined(e){const t=this.set.view("define");return t.size?du(e,t,{format:this.format}).node:e}approximate(e,t={}){const n=this.defined(this.node(e));if(Ea(n).size&&!t.scope){const e=tu(ka(n),t);return{result:e,text:this.format(e),number:null,exact:!1}}const r=Yl(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),i=this.defined(go("-",[n,r])),s=this.simplify(i,{steps:!1}).result;if("num"===s.type&&"0"===s.token)return{equal:!0,how:"exact"};const o=[...Ea(i)];if(!o.length)try{return{equal:Math.abs(Yl(i,{digits:30}).number)<1e-25,how:"numeric"}}catch{return{equal:!1,how:"numeric"}}const a=[.31,1.7,2.9,-.83,.57];let l=0;for(let e=0;e<a.length;e++){const t=Object.fromEntries(o.map((t,n)=>[t,String(a[(e+n)%a.length]+n/7)]));let n;try{n=Yl(i,{digits:30,scope:t}).number}catch{continue}if(l++,Math.abs(n)>1e-20)return{equal:!1,how:"numeric"}}return{equal:l>0,how:"numeric"}}modes(){return this.set.modes()}}function Ac(e={}){const t=!1===e.defaults?[]:[...wc,...e.complex?$c:[]],{specs:n,messages:r}=function(e){lu();const t=[],n={};for(const r of e){const e="string"==typeof r?ul(r):r,i=Array.isArray(e)?e:e?.rules??[];for(const t of(Array.isArray(e)?[]:e?.operators)??[]){if(!t?.symbol)throw new Error("an operator needs a symbol");no(t.symbol)||Ks({symbol:String(t.symbol),arity:"any"===t.arity?Xs:Number(t.arity),label:t.label})}Object.assign(n,(Array.isArray(e)?null:e?.messages)??{});for(const e of i)t.push(e)}return{specs:t,messages:n}}([...t,...e.rules??[]]),i=Zo(e.complex,()=>uu(n));return new Mc(i,{...kc,...r},e.format??mc,e.read??null,Boolean(e.complex))}const Nc=Symbol.for("inlinemath.expressions"),Sc=new Map,Oc={re:"Re",im:"Im",conj:"overline"},Ec=["Re","Im","re","im","conj","arg"];function Ic(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),`\\:${Oc[e.op]??e.op}`)):t.push(e.token)};return n(e),t}function _c(e={}){const t=e.rules||e.names?null:e.complex?"complex":"default";if(t&&Sc.has(t))return Sc.get(t);const n=[...e.names??[],...e.complex?Ec:[]],r=Ac({...e,read:e=>function(e,t={}){const n=en(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 "${tn(e)}": ${n.error}`)}(e,n.length?{names:n}:{}),format:mc});return t&&Sc.set(t,r),r}const Tc=new Set(["simplify","expand","factor","cancel","diff","integrate","solve","approx"]),jc={integral:"integrate",differentiate:"diff",approximate:"approx",simp:"simplify"};const zc=e=>String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");var Lc='/*\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.mv-matrix { display: inline-grid; column-gap: 0.8em; row-gap: 0.3em; align-items: baseline; justify-items: center; margin: 0 0.15em; }\n.mv-matrix-row { display: contents; }\n.mv-matrix-cell { display: block; }\n\n/* ---- decorations: \\boxed \\cancel \\overline \\vec … --------------------------- */\n.mv-boxed { display: inline-block; border: 0.06em solid currentColor; padding: 0.16em 0.2em; }\n.mv-over { display: inline-block; 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; position: relative; }\n.mv-cancel-line { position: absolute; left: 0; top: 0; width: 100%; height: 100%; overflow: visible; pointer-events: none; }\n.mv-accent { display: inline-block; position: relative; padding-top: 0.3em; }\n.mv-accent-mark { position: absolute; top: 0; 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/* Windows high contrast (and other forced colours) drops backgrounds and shadows: outline a highlight instead */\n@media (forced-colors: active) {\n .mv-hl { outline: 0.08em solid Highlight; outline-offset: 0.04em; }\n}\n.mv-clickable .mv-n { cursor: pointer; }\n.mv-editable .mv-n:hover { outline: 1px dashed rgba(0, 0, 0, 0.25); }\n/* the box editing a part in place (view.editable, or a Markdown textbox variable) */\n.mv-edit { transform: translateY(-50%); z-index: 1000; box-sizing: content-box; padding: 0.1em 0.35em; font-family: inherit;\n border: 1px solid #1a5fb4; border-radius: 0.25em; background: #fff; color: #111; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.18); }\n.mv-edit[aria-invalid="true"] { border-color: #c33; outline: 2px solid #c33; }\n/* the live region a view announces steps through ({ announce: true }): read, never seen */\n.mv-sr-only, .mv-sr-math { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }\n.mv-clickable .mv-n:hover { outline: 1px dashed rgba(0, 0, 0, 0.25); }\n/* the keyboard: the expression is one tab stop, and the part the arrow keys are on is ringed */\n.mv[tabindex]:focus-visible { outline: 0.1em solid #1a5fb4; outline-offset: 0.12em; }\n.mv[tabindex]:focus .mv-focus { outline: 0.1em solid #1a5fb4; outline-offset: 0.06em; border-radius: 0.1em; }\n/* while a part is ringed, the whole expression\'s ring steps back so the part is the one that stands out */\n.mv[tabindex]:focus-visible:has(.mv-focus) { outline: 1px dashed #1a5fb4; }\n@media (forced-colors: active) {\n .mv[tabindex]:focus-visible, .mv[tabindex]:focus .mv-focus { outline-color: Highlight; }\n}\n\n/* ---- steps (stepsHTML from \'@mathzetta/inlinemath/cas\') ---------------------------------------- */\n.mv-steps { margin: 0; padding-left: 1.6em; }\n.mv-step { margin: 0.5em 0 0.9em; }\n.mv-step-name { display: block; font-size: 0.85em; font-weight: 600; color: #555; }\n.mv-step-maths { display: flex; flex-wrap: wrap; align-items: center; gap: 0.4em 0.8em; margin: 0.15em 0; }\n.mv-step-arrow { color: #888; }\n.mv-step-why { margin: 0.1em 0 0; font-size: 0.9em; color: #444; }\n\n/* ---- Markdown with 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/* saved variables: $A := 2+2$ draws A ≔ 2 + 2; $A := [[…]]$ an input that sets A */\n.mv-md-input-def { display: inline-flex; align-items: center; gap: 0.3em; }\n.mv-md-assign { margin: 0 0.1em; }\n.mv-md-input { font: inherit; font-size: 0.9em; }\ninput.mv-md-textbox { font-family: inherit; padding: 0.05em 0.3em; field-sizing: content; min-width: 3ch; }\ninput.mv-md-textbox[aria-invalid="true"] { outline: 2px solid #c33; outline-offset: 1px; }\ninput.mv-md-slider { vertical-align: middle; }\n.mv-md-output { font-variant-numeric: tabular-nums; min-width: 2ch; }\n';const Cc=Lc;if("undefined"!=typeof document&&!document.getElementById("inlinemath-css")){const e=document.createElement("style");e.id="inlinemath-css",e.textContent=Lc,document.head.append(e)}return e.CSS=Cc,e.DEFAULTS=Fi,e.PATHS=$i,e.View=ks,e.casBlocks=function(e={}){const t=e.cas??_c(),n=void 0===e.steps?{}:{steps:e.steps},r=(e,i)=>{let s;try{s=t.read(e)}catch{return ci(e,i)}const o=i&&i[Nc];o&&(s=s.flatMap(e=>Object.hasOwn(o,e)?o[e]:[e]));const a=s[s.length-1],l=a?.startsWith("\\:")?jc[a.slice(2)]??a.slice(2):null,u=l&&Tc.has(l);if(!u&&!("der"===a||"int"===a))return ci(e,i);const c=t.node(s),h=u?c.args:[c],p=e=>e?e.s:void 0;let f;try{switch(u?l:"der"===a?"derivative":"antiderivative"){case"simplify":f=t.simplify(h[0],n);break;case"expand":f=t.expand(h[0],n);break;case"factor":f=t.factor(h[0],n);break;case"cancel":f=t.cancel(h[0],n);break;case"diff":f=t.diff(h[0],p(h[1]),{...n,order:h[2]?Number(h[2].s):1});break;case"integrate":f=t.integrate(h[0],p(h[1]),{...n,...h[3]?{from:h[2].s,to:h[3].s}:{}});break;case"solve":f=t.solve(h[0],p(h[1]),n);break;case"approx":f=t.approximate(h[0],{...n,digits:h[1]?Number(h[1].s):15});break;case"derivative":f=t.diff(c.args[0],c.args[1].s,n);break;default:f=t.integrate(c,void 0,n)}}catch(t){return`(${e})`}if(r.last=f,!f.result)return`"${f.text}"`;const d=Gs(Ic(f.result));return/^-?\d+(\.\d+)?$/.test(d)?d:`(${d})`};return r},e.createVariables=ys,e.extractMath=Ns,e.layout=Ui,e.markdownToHTML=function(e,t={}){return Fs(Is(e,t,t.variables||null),t)},e.mathCAS=_c,e.nodeAt=Ki,e.numberTree=ts,e.pathOf=es,e.render=function(e,t,n={}){return new ks(e,t,n)},e.renderMarkdown=Zs,e.renderMarkdownInto=function(e,t,n={}){const r=void 0===n.variables?xs:n.variables||null;Ds();const i=Ps.get(e);i&&i.stop(i.store!==r);let s=Is(t,n,r,e);if(e.innerHTML=Fs(s,n),!r)return Ps.delete(e),e;r.own(e,s.defs);let o=e.isConnected;const a=t=>{const i=t.target,s=i&&i.dataset&&i.dataset.mvVar;if(void 0!==s&&e.contains(i)){if("text"===i.type)try{ss(i.value,{blocks:n.blocks,scope:{}}),i.removeAttribute("aria-invalid")}catch{return void i.setAttribute("aria-invalid","true")}r.set(s,i.value)}},l=i=>{const o=i.target.closest?.("[data-node]"),a=o&&o.closest("[data-mv-md]");if(!a||!e.contains(a))return;const l=Number(a.dataset.mvMd),u=s.trees[l];if(!u)return;const c=Number(o.dataset.node),h=es(u,c)||[];let p=null;for(let e=h.length;e>=0&&!p;e--){const t=Ki(u,h.slice(0,e));t&&void 0!==t.from&&(p={node:t,depth:e})}const f=p&&r.definitions().get(p.node.from);if(f&&f.input&&"textbox"===f.input.kind){i.preventDefault();const t=f.name,s=e.ownerDocument.querySelector(`[data-mv-var="${CSS.escape(t)}"]`),a=n.editable&&n.editable.toText;if(!a)return void(s&&(s.focus(),s.select()));const l=e=>ss(e),c=Ki(u,h);return void $s(o,a(ps(c,l)),{label:`Edit ${t}`,parse:e=>ss(e,{blocks:n.blocks}),commit:e=>{const n=ws(ps(p.node,l),h.slice(p.depth),e);r.set(t,a(n))}})}const d=f&&s.defs.get(f.name),m=d&&d.key===f.key&&void 0!==d.start?{...s.math[l],start:d.start,end:d.end,raw:t.slice(d.start,d.end)}:s.math[l];e.dispatchEvent(new CustomEvent("inlinemath:select",{bubbles:!0,detail:{index:l,start:m.start,end:m.end,raw:m.raw,source:m.source,id:c,path:h}}))};e.addEventListener("input",a),e.addEventListener("change",a),e.addEventListener("dblclick",l);const u=r.subscribe(i=>{i!==e&&(e.isConnected?(o=!0,Ds(),(()=>{const i=Is(t,n,r,e);i.drawn.forEach((t,n)=>{if(t===s.drawn[n]||i.inputs.has(n))return;const r=e.querySelector(`[data-mv-md="${n}"]`);r&&(r.outerHTML=t)});for(const t of e.querySelectorAll("[data-mv-var], [data-mv-out]")){const e=i.defs.get(t.dataset.mvVar??t.dataset.mvOut);if(!e)continue;const n=r.textOf(e);void 0!==t.dataset.mvOut?t.textContent=n:t.value!==n&&t!==t.ownerDocument?.activeElement&&(t.value=n)}s=i})()):o&&c(!0))});function c(t){u(),e.removeEventListener("input",a),e.removeEventListener("change",a),e.removeEventListener("dblclick",l),Bs.delete(h),Ps.delete(e),t&&r.own(e,null)}const h={element:e,store:r,stop:c,connected:()=>o};return Bs.add(h),Ps.set(e,h),e},e.select=Ji,e.shouldAnimate=Ms,e.signature=Xi,e.stepsHTML=function(e,t={}){return`<ol class="mv-steps">${e.map(e=>{const n=os(Ic(yo(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>${os(Ic(yo(e.to)),t)}`,i=e.explanation?`<p class="mv-step-why">${zc(e.explanation)}</p>`:"";return`<li class="mv-step" data-rule="${zc(e.id)}"><span class="mv-step-name">${zc(e.name)}</span><div class="mv-step-maths">${n}${r}</div>${i}</li>`}).join("")}</ol>`},e.toHTML=os,e.toText=Gs,e.tokensOf=Ic,e.treeOf=ss,e.variables=xs,e}({});
1
+ /* Inline Math 0.3.0 — MIT license; 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),det: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),pmatrix:r(t),bmatrix:r(t),vmatrix: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="",f="",d={[p]:"dot",[f]:"cross"},m="",g={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,pmatrix:h,bmatrix:h,vmatrix:h,det: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,[p]:70,[f]: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},v=e=>Object.prototype.hasOwnProperty.call(g,e),b=new Set(["^","?:","?","log"]),y=["(","{","["],w=[")","}","]"];function x(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[g])Object.setPrototypeOf(e,null);const $=e=>({type:"number",value:String(e)}),k=e=>({type:"symbol",value:e}),q=(e,t)=>({type:"op",op:e,args:t}),M=['"',"'","`"];function A(e){return x(e,!0)?$(e):M.includes(e[0])?{type:"string",value:e}:k(e)}const N={"0-":"neg",sqrtpow:"root",pow:"^","==":"=","!==":"≠="};function S(e){if(!Array.isArray(e)||0===e.length)throw new Error("Empty postfix");const n=[],r=[];if(e.forEach((e,s)=>{const i=N[e]??String(e),l=a(i);if(!l)return n.push({...A(i),id:s}),void r.push(1);let u=l.arity;if(u===t){const e=n.pop();if(r.pop(),u=e&&"number"===e.type?Number(e.value):NaN,!Number.isInteger(u)||u<0)throw new Error(`'${i}' takes a variable number of arguments, so it must follow a count`);if(0===u&&!l.group&&!o(i))throw new Error(`'${i}' needs at least one argument`)}if(n.length<u)throw new Error(`'${i}' needs ${u} operand${1===u?"":"s"}`);const c=1+Math.max(0,...r.splice(r.length-u,u));if(c>1e3)throw new Error("Nested too deeply (more than 1000 levels)");r.push(c),n.push({...q(i,n.splice(n.length-u,u)),id:s})}),1!==n.length)throw new Error(`Postfix leaves ${n.length} values instead of 1`);return n[0]}function O(e,n){const r=[];return function e(s){"op"===s.type?(s.args.forEach(e),a(s.op)?.arity===t&&r.push(String(s.args.length)),n&&s.written&&(n[r.length]=s.written),r.push(s.op)):r.push(s.value)}(e),r}function E(e){if(Array.isArray(e))return S(e);if(e&&"object"==typeof e&&e.type)return e;throw new Error("Expected a postfix array or an expression tree")}function I(e,t,n=null){t(e,n),"op"===e.type&&e.args.forEach(n=>I(n,t,e))}function _(e){let t="";return I(e,e=>{!t&&"symbol"===e.type&&1===e.value.length&&/[a-zA-Zʹ-Ͽ]/.test(e.value)&&(t=e.value)}),t}for(const e of[N])Object.setPrototypeOf(e,null);const T={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 j(e){for(;"op"===e.type&&e.args.length;)e=e.args[0];return"op"===e.type?"":e.value}function z(e){const t="string"==typeof e&&/^(-?)(\d*)(?:\.(\d*))?%$/.exec(e);if(!t||!t[2]&&!t[3])return null;const n=(t[2]||"0").padStart(3,"0")+(t[3]??""),r=n.length-(t[3]??"").length-2,s=`${n.slice(0,r).replace(/^0+(?=\d)/,"")}.${n.slice(r)}`.replace(/\.?0+$/,"");return t[1]+(""===s?"0":s)}function L(e){if("*"!==e.op)return!1;const[t,n]=e.args;return"number"===t.type&&"-1"===t.value&&"-1"!==j(n)}function C(e){return"op"!==e.type||a(e.op)?.group?null:"sum"===e.op?"+":"prod"===e.op?"*":L(e)?"neg":e.op}const F=new Set(["=","===","≠","≠=","<",">","≤","≥","≈","≡","→"]),Z=(e,t,n)=>("op"!==t.type||"?:"!==t.op||!F.has(e.op))&&c(e.op,C(t),n);function R(e,t){const n=C(t),r=n&&a(n)?.prec;return r?"!"===e?r<=a("!").prec:"\\not"===e?r<a("\\not").prec:r<70||H(t)||"\\not"===n:"\\not"!==e&&H(t)}function P(e,t,n={}){const r=n.left?"bracket":U(e),s=n.right?"bracket":W(t);return"digit"!==s&&"sign"!==s&&"word"!==r&&"word"!==s&&"other"!==r&&("frac"!==s||"digit"!==r&&"frac"!==r)}function B(e){return 1===e.length||Boolean(T[e])||/^Δ.$/.test(e)||/^.′+$/.test(e)}function D(e){return"op"===e.type&&!a(e.op)?.group&&(a(e.op)?.prec??100)<70&&!["sum","prod"].includes(e.op)}function W(e){if("number"===e.type)return e.value.startsWith("-")?"sign":"digit";if("op"!==e.type)return"symbol"===e.type&&B(e.value)?"name":"word";const t=e.op;return"neg"===t||"pm"===t||L(e)?"sign":"/"===t?"frac":a(t)?.group||D(e)?"bracket":V(e)||["der","int","lim","comb"].includes(t)?"call":["^","!","_"].includes(t)?D(e.args[0])?"bracket":W(e.args[0]):["*","sum","prod","perm"].includes(t)?W(e.args[0]):"other"}function U(e){if("number"===e.type)return"digit";if("op"!==e.type)return"symbol"===e.type&&B(e.value)?"name":"word";const t=e.op;return"/"===t?"frac":"^"===t||"_"===t?"script":a(t)?.group||D(e)||V(e)||["der","int","lim","comb","perm"].includes(t)?"bracket":["*","neg","pm","sum","prod"].includes(t)?U(e.args[e.args.length-1]):"other"}function V(e){if("op"!==e.type)return!1;const t=a(e.op);return"prefix"===t?.fixity&&100===t.prec}function H(e){if("number"===e.type)return e.value.startsWith("-");if("op"!==e.type)return!1;if("neg"===e.op||L(e))return!0;const t=a(e.op);return"infix"===t?.fixity&&!Z(e,e.args[0],"left")&&H(e.args[0])}const G=e=>"symbol"===e.type&&1===e.value.length&&/[a-zA-Zʹ-Ͽ]/.test(e.value),X=e=>e.slice(2);function Q(e){const t="op"===e.args[1].type&&"="===e.args[1].op?e.args[1]:null,n=t?t.args[0]:e.args[1],r=t?t.args[1]:null;let s=1,i=e.args[0];for(;"op"===i.type&&"der"===i.op&&J(i.args[1],n);)s++,i=i.args[0];return{n:s,body:i,by:n,at:r,variable:"symbol"===i.type&&B(i.value)}}const J=(e,t)=>e.type===t.type&&e.value===t.value&&"op"!==e.type,Y=new Set(["<",">","≤","≥","=","===","≠","≠=","&","|","\\not","\\xor","\\nand","\\nor","∈","∉","≈","≡"]);function K(e){return"op"===e.type&&(!!("="===e.op&&(t=e.args[1],"op"===t.type&&Y.has(t.op)||"symbol"===t.type&&("true"===t.value||"false"===t.value)))||e.args.some(K));var t}const ee=new Set(["<",">","≤","≥","=","≠"]);function te(e){if("op"!==e.type||!ee.has(e.op)||2!==e.args.length)return null;const[t,n]=e.args;if("op"!==t.type||!ee.has(t.op)||2!==t.args.length)return null;return{type:"op",op:"&",args:[te(t)??t,{type:"op",op:e.op,args:[t.args[1],n]}]}}for(const e of[T])Object.setPrototypeOf(e,null);const ne={pmatrix:["(",")"],bmatrix:["[","]"],vmatrix:["|","|"]};function re(e){if(!e||"op"!==e.type)return null;if(Object.prototype.hasOwnProperty.call(ne,e.op))return e.args.map(e=>"op"===e.type&&"[]"===e.op?e.args:[e]);if("[]"!==e.op||!e.args.length||!e.args.every(e=>"op"===e.type&&"[]"===e.op))return null;const t=e.args[0].args.length;return!t||!e.args.every(e=>e.args.length===t)||e.args.length<2&&t<2?null:e.args.map(e=>e.args)}function se(e){return Array.isArray(e)&&e.length>0&&e.every(t=>Array.isArray(t)&&t.length>0&&t.length===e[0].length&&!t.some(Array.isArray))}const ie=e=>Array.isArray(e)&&e.length>0&&!e.some(Array.isArray);function oe(e){const t=e,n=t.make??(e=>e),r=t.size??(()=>1),s=t.charge??(()=>{}),i=e=>`${e.length} by ${e[0].length}`,o=(e,r)=>n(Array.from({length:e},(n,r)=>Array.from({length:e},(e,n)=>r===n?t.one():t.zero())),r);function a(e,r){return e[0].length!==r.length&&t.fail(`a ${i(e)} matrix times a ${i(r)} one`),s(e.length*r.length*r[0].length),n(e.map(e=>r[0].map((n,s)=>e.reduce((e,n,i)=>t.add(e,t.mul(n,r[i][s])),t.zero()))),e)}function l(e){const n=e.map(e=>e.slice()),i=n.length,o=n[0].length;s(i*i*o);let a=t.one(),l=0;for(let e=0;e<o&&l<i;e++){let s=-1;for(let o=l;o<i;o++)t.isZero(n[o][e])||(s<0||r(n[o][e])>r(n[s][e]))&&(s=o);if(s<0){a=t.zero();continue}s!==l&&([n[s],n[l]]=[n[l],n[s]],a=t.sub(t.zero(),a));const o=n[l][e];a=t.mul(a,o),n[l]=n[l].map(e=>t.div(e,o));for(let r=0;r<i;r++){if(r===l||t.isZero(n[r][e]))continue;const s=n[r][e];n[r]=n[r].map((e,r)=>t.sub(e,t.mul(s,n[l][r])))}l++}return l<i&&(a=t.zero()),{M:n,det:a,rank:l}}function u(e){const r=e.length;r!==e[0].length&&t.fail(`a ${i(e)} matrix has no inverse`);const s=o(r),{M:a,rank:u}=l(e.map((e,t)=>[...e,...s[t]]));return(u<r||a.some((e,n)=>t.isZero(e[n])))&&t.fail("the matrix has no inverse (its determinant is 0)"),n(a.map(e=>e.slice(r)),e)}return{identity:o,transpose:e=>n(e[0].map((t,n)=>e.map(e=>e[n])),e),times:a,det:function(e){return e.length!==e[0].length&&t.fail(`a ${i(e)} matrix has no determinant`),l(e).det},inverse:u,power:function(e,n){e.length!==e[0].length&&t.fail(`a ${i(e)} matrix has no powers`);let r=n<0n?u(e):e,s=n<0n?-n:n,l=o(e.length,e);for(;s>0n;)1n&s&&(l=a(l,r)),r=a(r,r),s>>=1n;return l},trace:e=>(e.length!==e[0].length&&t.fail(`a ${i(e)} matrix has no trace`),e.reduce((e,n,r)=>t.add(e,n[r]),t.zero())),dot:(e,n)=>(e.length!==n.length&&t.fail("vectors of different lengths"),e.reduce((e,r,s)=>t.add(e,t.mul(r,n[s])),t.zero())),cross:(e,n)=>(3===e.length&&3===n.length||t.fail("the cross product is for vectors of 3 numbers"),[t.sub(t.mul(e[1],n[2]),t.mul(e[2],n[1])),t.sub(t.mul(e[2],n[0]),t.mul(e[0],n[2])),t.sub(t.mul(e[0],n[1]),t.mul(e[1],n[0]))]),solve:function(e,t){return se(t)?a(u(e),t):a(u(e),t.map(e=>[e])).map(e=>e[0])},rank:e=>l(e).rank,rref:e=>n(l(e).M,e),timesVector:(e,t)=>a(e,t.map(e=>[e])).map(e=>e[0]),vectorTimes:(e,t)=>a([e],t)[0]}}function ae(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 ue(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=le(n,e,s);i?(r+=t.get(e.slice(s,s+i)),s+=i):r+=e[s++]}return r}}function le(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 ue(e){const t=new Set([e.toLowerCase(),e.toUpperCase(),ce(e)]);return t.delete(e),t}function ce(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 he=[["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"],["\\cfrac","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"],["∫","\\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",p],["\\times",f],["×",f],["·",p],["÷","/"],["->","→"],["\\to","→"],["\\max","max"],["\\min","min"],["\\det","det"],["^{\\top}","^{T}",!0],["^\\top","^T",!0],["^{\\intercal}","^{T}",!0],["^\\intercal","^T",!0],["^{\\mathsf{T}}","^{T}",!0],["^{\\mathrm{T}}","^{T}",!0],["product(","prod("],["log[","log_["],["\\log[","log_["],["\\log_","log_"],["\\log","log_{e}"],["\\ln","log_{e}"],["log(","log_{e}("],["ln(","log_{e}("],...["","\\"].flatMap(e=>["(","{"].flatMap(t=>[2,3,4,5,6,7,8,9,10].map(n=>[`${e}log${n}${t}`,`log_{${n}}${t}`]))),["\\log_10","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.",m],["\\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)"],["⅕","(1/5)"],["⅖","(2/5)"],["⅗","(3/5)"],["⅘","(4/5)"],["⅙","(1/6)"],["⅚","(5/6)"],["⅐","(1/7)"],["⅑","(1/9)"],["⅒","(1/10)"],["⊕"," \\xor "],["∞","∞"],["⋅",p],["−","-"],["\\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]];const pe=e=>" "===e||"\t"===e||"\n"===e,fe="({[",de=")}]";const me={__proto__:null},ge={__proto__:null};[..."⁰¹²³⁴⁵⁶⁷⁸⁹"].forEach((e,t)=>{me[e]=String(t)}),[..."₀₁₂₃₄₅₆₇₈₉"].forEach((e,t)=>{ge[e]=String(t)}),Object.assign(me,{"⁺":"+","⁻":"-","⁼":"=","⁽":"(","⁾":")","ᵃ":"a","ᵇ":"b","ᶜ":"c","ᵈ":"d","ᵉ":"e","ᶠ":"f","ᵍ":"g","ʰ":"h","ⁱ":"i","ʲ":"j","ᵏ":"k","ˡ":"l","ᵐ":"m","ⁿ":"n","ᵒ":"o","ᵖ":"p","ʳ":"r","ˢ":"s","ᵗ":"t","ᵘ":"u","ᵛ":"v","ʷ":"w","ˣ":"x","ʸ":"y","ᶻ":"z"}),Object.assign(ge,{"₊":"+","₋":"-","₌":"=","₍":"(","₎":")","ₐ":"a","ₑ":"e","ₕ":"h","ᵢ":"i","ⱼ":"j","ₖ":"k","ₗ":"l","ₘ":"m","ₙ":"n","ₒ":"o","ₚ":"p","ᵣ":"r","ₛ":"s","ₜ":"t","ᵤ":"u","ᵥ":"v","ₓ":"x"});const ve=new RegExp(`[${Object.keys(me).join("")}]+|[${Object.keys(ge).join("")}]+`,"g");const be={__proto__:null,"½":"1/2","⅓":"1/3","⅔":"2/3","¼":"1/4","¾":"3/4","⅕":"1/5","⅖":"2/5","⅗":"3/5","⅘":"4/5","⅙":"1/6","⅚":"5/6","⅐":"1/7","⅛":"1/8","⅜":"3/8","⅝":"5/8","⅞":"7/8","⅑":"1/9","⅒":"1/10"},ye=new RegExp(`(?<![\\w.,^_])(\\d+)[ \\t]?([${Object.keys(be).join("")}])`,"g"),we=/(?<![\w.,^_/])(\d+)[ \t]+([1-9]\d*)\/(\d+)(?![\d./^!])/g,xe=/(?<![\w.,^_])(\d+)\s*\\[dtc]?frac\s*(?:\{\s*(\d+)\s*\}\s*\{\s*(\d+)\s*\}|(\d)(\d)(?!\d))/g;function $e(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 ke(e,t){const n=[];let r=0,s=0;for(let i=0;i<e.length;i++)fe.includes(e[i])?r++:de.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 qe(e,t,n){let r=0;const s=new RegExp(`\\b${n}\\b`,"iy");for(let n=t;n<e.length;n++)if(fe.includes(e[n]))r++;else if(de.includes(e[n])){if(--r<0)return-1}else if(0===r&&(s.lastIndex=n,s.test(e)))return n;return-1}function Me(e,t){let n=0;for(let r=t;r<e.length;r++)if(fe.includes(e[r]))n++;else if(de.includes(e[r])&&--n<0)return r;return e.length}function Ae(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 Ne(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(fe.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&&o>0&&(e=e.slice(0,t+1)+"_{"+i+"}("+s+")"+e.slice(o+1))}return e}function Se(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 Oe(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}const Ee=new Set(["pmatrix","bmatrix","vmatrix"]);function Ie(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,", ")+"]"),a=e.slice(s+6+r.length);return Ee.has(r)?r+"("+o.join(", ")+")"+a:"["+o.join(", ")+"]"+a}function _e(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 Te(e){const{lower:t,upper:n,next:r}=function(e){let t="",n="",r=0;return"_"===e[0]&&([t,r]=_e(e,0),"^"===e[r]&&([n,r]=_e(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(fe.includes(e[n]))t++;else if(de.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).trim()?i(o):"1");return a&&(c+=","+a),(t||n)&&(c+=","+t+","+n),c+")"+l}function je(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(de.includes(n[e])?r--:fe.includes(n[e])&&r++,0===r)return"("+n.slice(0,e)+","+t+")"+n.slice(e+1);return!1}function ze(e){return"{"===e[0]||e.length<2?e:"{"+e[0]+"}{"+e[1]+"}"+e.slice(2)}const Le=/[A-Za-z\u0370-\u03FF]/;function Ce(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 Fe(e,t){const n=/^\^(?:\{(\d+)\}|(\d))/.exec(e.slice(t));return n?[Number(n[1]??n[2]),t+n[0].length]:[1,t]}function Ze(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 Re(e,t){if(fe.includes(e[t])){let n=0;for(let r=t;r<e.length;r++)if(fe.includes(e[r]))n++;else if(de.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(fe.includes(e[r]))n++;else{if(de.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 Pe=(e,t,n)=>`der(${e},${t}${n>1?","+n:""})`;const Be="strtktk",De="ABCDEFGHIJ",We=e=>Be+[...String(e)].map(e=>De[e]).join(""),Ue=new RegExp(`^${Be}[${De}]+$`);function Ve(e){let t="";for(let n=0;n<e.length;n++){const r=e[n];if('"'===r||"`"===r){const r=He(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=He(e,n);t+=e.slice(n,r+1),n=r}else t+=r}return t}function He(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}const Ge=new RegExp(`${Be}[${De}]+|§\\d+§`,"g");function Xe(e,t){return t&&0!==t.size?e.map(e=>"string"!=typeof e?e:e.replace(Ge,e=>{const n=t.get(e);if(void 0!==n)return n;for(let n=e.length-1;n>7;n--){const r=t.get(e.slice(0,n));if(void 0!==r)return r+e.slice(n)}return e})):e}const Qe={factorial:"((n) => { if (!Number.isInteger(n) || n < 0) return NaN; if (n > 170) return Infinity; let r = 1; for (let i = 2; i <= n; i++) r *= i; return r; })",perm:"((n, k) => { if (!Number.isInteger(n) || !Number.isInteger(k) || k < 0 || k > n) return NaN; let r = 1; for (let i = n - k + 1; i <= n && r !== Infinity; i++) r *= i; return r; })",comb:"((n, k) => { if (!Number.isInteger(n) || !Number.isInteger(k) || k < 0 || k > n) return NaN; k = Math.min(k, n - k); let r = 1; for (let i = 1; i <= k && r !== Infinity; i++) r = r * (n - k + i) / i; return Math.round(r); })",gcd:"((args)=>{let gcd = function(a,b) { return (!b)?a:gcd(b,a%b); }; return Math.abs(args.reduce(gcd));})",det:"((m) => { const a = m.map((r) => r.slice()); const n = a.length; let d = 1; for (let i = 0; i < n; i++) { let p = i; for (let r = i + 1; r < n; r++) if (Math.abs(a[r][i]) > Math.abs(a[p][i])) p = r; if (a[p][i] === 0) return 0; if (p !== i) { const t = a[p]; a[p] = a[i]; a[i] = t; d = -d; } d *= a[i][i]; for (let r = i + 1; r < n; r++) { const f = a[r][i] / a[i][i]; for (let c = i; c < n; c++) a[r][c] -= f * a[i][c]; } } return d; })",union:"((a, b) => [...new Set([].concat(a, b))])",intersection:"((a, b) => [].concat(a).filter((x) => [].concat(b).includes(x)))",round:"((x, d) => { const p = Math.pow(10, d); return (x < 0 ? -Math.round(-x * p) : Math.round(x * p)) / p; })",mod:"((a, n) => ((a % n) + n) % n)",root:"((n, x) => (x < 0 ? -Math.pow(-x, 1 / n) : Math.pow(x, 1 / n)))"};for(const e of[Qe])Object.setPrototypeOf(e,null);const Je="([{",Ye=")]}";function Ke(e,t){let n=0;for(let r=t;r<e.length;r++)if(Je.includes(e[r]))n++;else if(Ye.includes(e[r])&&0===--n)return r;return-1}function et(e){if(!e.trim())return[];const t=[];let n=0,r=0;for(let s=0;s<e.length;s++)Je.includes(e[s])?n++:Ye.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 tt(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=Ke(e,i);if(o<0)continue;const a=n(et(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 nt=e=>new RegExp(`(?<![\\w.])(${e})\\s*\\(`,"g"),rt=e=>`(${e})`,st=e=>/^\[.*\]$/s.test(e.trim())?`{${e.trim().slice(1,-1)}}`:e;const it={IF:e=>e.length>=2&&`((${e[0]}) ? (${e[1]}) : (${e[2]??"false"}))`,AND:e=>e.length&&`(${e.map(rt).join(" & ")})`,OR:e=>e.length&&`(${e.map(rt).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]})`};function ot(e,t){for(let n=t,r=0;n>=0;n--)if(")"===e[n])r++;else if("("===e[n]&&0===--r)return n;return-1}function at(e){const t="(?:[\\p{L}_][\\p{L}\\p{N}_.]*|\\d+(?:\\.\\d+)?|§\\d+§)";return e=function(e,t){const n=new RegExp(`^(?:${t})`,"u"),r=new RegExp(`(?:${t})$`,"u"),s=/[\p{L}_][\p{L}\p{N}_.]*$/u;for(let t=e.indexOf("^");t>=0;t=e.indexOf("^",t+1)){let i,o=t+1;for(;/\s/.test(e[o]??"");)o++;if("("===e[o])i=Ke(e,o)+1;else{const t=n.exec(e.slice(o));i=t?o+t[0].length:0,t&&"("===e[i]&&(i=Ke(e,i)+1)}if(i<=o||!/^\s*\^/.test(e.slice(i)))continue;let a,l=t;for(;l>0&&/\s/.test(e[l-1]);)l--;if(")"===e[l-1]){a=ot(e,l-1);const t=a>0&&s.exec(e.slice(Math.max(0,a-64),a));t&&(a-=t[0].length)}else{const t=r.exec(e.slice(Math.max(0,l-64),l));a=t?l-t[0].length:-1}a<0||(e=`${e.slice(0,a)}(${e.slice(a,i)})${e.slice(i)}`,t=i+1)}return e}(e=(e=(e=e.replace(/^\s*=/,"").replace(/(?<![\w.])_xlfn\./g,"")).replace(/&/g,"+")).replace(new RegExp(`(^|[(,=<>*/+^-]\\s*)-\\s*(${t})(?=\\s*\\^)`,"gu"),"$1(-$2)"),t),tt(e,/(?<![\w.])([A-Z][A-Z0-9]*(?:\.[A-Z]+)?)\s*\(/g,(e,t)=>it[t[1]]?.(e)||null)}const lt={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"},ut="strtktk[A-J]+";function ct(e){for(let t=!0;t;){const n=e;t=(e=e.replace(new RegExp(`(${ut})\\s*\\|\\|\\s*(${ut})`,"g"),"$1 + $2"))!==n}const t=new RegExp(`^\\(typeof\\(([^()]*)\\)\\s+IN\\s+\\(${ut},\\s*${ut}\\)\\s+AND\\s+(.*)\\)$`,"s");for(let n=e.lastIndexOf("(typeof(");n>=0;n=n>0?e.lastIndexOf("(typeof(",n-1):-1){const r=Ke(e,n),s=r>0&&t.exec(e.slice(n,r+1));if(!s)continue;const[,i,o]=s,a=new Map([[`${i} = TRUNC(${i})`,"ℤ"],[`${i} = TRUNC(${i}) AND ${i} > 0`,"ℕ"],[`ABS(${i}) < ∞`,"ℝ"]]).get(o.trim());a&&(e=`${e.slice(0,n)}((${i}) ∈ ${a})${e.slice(r+1)}`)}e=tt(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=tt(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})`,rt(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=>lt[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=Ke(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 ht={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"},pt={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",union1d:"union",intersect1d:"intersection"};const ft={inf:"∞",nan:"NaN"};function dt(e){return e=(e=(e=(e=e.replace(/(?<![\w.])(?:np|numpy)\.random\.random\(\s*\)|(?<![\w.])random\.random\(\s*\)/g,"Math.random()")).replace(/(?<![\w.])(?:np|numpy)\.linalg\.(det|inv)\b/g,"$1")).replace(/(?<![\w.])(?:np|numpy)\.array\s*\(/g,"(")).replace(/(?<![\w.])(?:np|numpy)\.(\w+)/g,(e,t)=>ht[t]?`Math.${ht[t]}`:pt[t]?pt[t]:ft[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)=>gt[t]??e),e=e.replace(/(?<![\w.])sympy\.(Reals|Integers|Naturals0?|Rationals|Complexes)\b/g,(e,t)=>gt[t]),e.replace(/(?<![\w.])sympy\.(\w+)/g,(e,t)=>vt[t]??mt[t]??e)}(e=(e=(e=e.replace(/(?<![\w.])(?:math|Math)\.(factorial|isfinite|isclose|prod|inf|nan|abs|trunc)\b/g,(e,t)=>ft[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 mt={pi:"π",E:"e",oo:"∞",true:"true",false:"false",nan:"NaN",I:"i"},gt={Reals:"ℝ",Integers:"ℤ",Naturals:"ℕ",Naturals0:"ℕ",Rationals:"ℚ",Complexes:"ℂ"},vt={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",real_root:"sympy_root",det:"det",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",Matrix:""},bt={open:"()",Lopen:"(]",Ropen:"[)"};const yt=e=>{const t=/^\((.*)\)$/s.exec(e.trim());return t?et(t[1]):null},wt=e=>t=>2===t.length&&`${e[0]}${t[0]}, ${t[1]}${e[1]}`,xt=e=>yt(e)??[e],$t={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]}) ∈ ${st(e[1])})`,contains:e=>2===e.length&&`((${e[1]}) ∈ ${st(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]}) < 0 ? (ceil(${e[0]})) : floor(${e[0]}))`,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(rt).join(" & ")})`,sympy_or:e=>e.length&&`(${e.map(rt).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(yt);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:wt("[]"),sympy_interval_open:wt("()"),sympy_interval_Lopen:wt("(]"),sympy_interval_Ropen:wt("[)"),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=xt(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&&xt(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&&xt(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:kt("sum"),prod:kt("prod")};function kt(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=et(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]}))`}}function qt(e){e=function(e){for(let t=e.lastIndexOf("(lambda");t>=0;t=t>0?e.lastIndexOf("(lambda",t-1):-1){const n=Ke(e,t);if(n<0||"("!==e[n+1])continue;const r=Ke(e,n+1),s=/^\(lambda\s+([\w\s,]+?)\s*:\s*([\s\S]*)\)$/.exec(e.slice(t,n+1));if(r<0||!s)continue;const i=s[1].split(",").map(e=>e.trim()),o=et(e.slice(n+2,r));if(o.length!==i.length||!i.every(e=>/^[A-Za-z_]\w*$/.test(e)))continue;const a=new Map(i.map((e,t)=>[e,o[t]])),l=s[2].replace(new RegExp(`(?<![\\w.])(${i.join("|")})(?!\\w)`,"g"),e=>`(${a.get(e)})`);if((e=e.slice(0,t)+`(${l})`+e.slice(r+1)).length>1e5)throw new Error("The expression expands too much when read")}return e}(e),e=tt(e,nt("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=tt(e,nt(Object.keys($t).join("|")),(e,t)=>$t[t[1]](e)||null);for(let t=(e=tt(e,nt("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=Ke(e,n);let s=t;if(Ye.includes(e[t-1])){let n=0;for(s=t-1;s>=0;s--)if(Ye.includes(e[s]))n++;else if(Je.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)}) ∈ ${st(e.slice(s,t))})${e.slice(r+1)}`)}return e}for(const e of[it,lt,ht,pt,mt,gt,vt,bt,$t,ft])Object.setPrototypeOf(e,null);const Mt=String.raw`(?:\([^()]*\)|\[[^\[\]]*\]|\{[^{}]*\}|(?<![\w.′^])[\w.′^]+)`,At=e=>e.trim().split(/\s+/).join(String.raw`\s+`),Nt=e=>new RegExp(String.raw`(?<![\w.])${At(e)}(?![\w.])`,"gi"),St=[["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","="]],Ot="[<>≤≥=≠≈]",Et={second:2,third:3,fourth:4,fifth:5,sixth:6,seventh:7,eighth:8,ninth:9,tenth:10};Object.setPrototypeOf(Et,null);const It=Object.entries({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"}).sort((e,t)=>t[0].length-e[0].length),_t=[["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","∈ ℚ"]],Tt=/(?<![A-Za-z])(?:is|between|exceeds|equals?|does|doesn't|least|most|than|divides|and|or|of|to|squared|cubed|twice|percent|by|over|times|plus|minus|modulo)(?![A-Za-z])/i;St.map(([e])=>e),_t.map(([e])=>e),It.map(([e])=>`${e} of`);const jt=ae([[" 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 ","→"],["===","=...="]]),zt=ae([...he,...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}()]),Lt=[["code",function(e){return/^\s*=|[(.%^<_eE]|\|\||\bif\b|\b(?:True|False|None|TRUE|FALSE|NULL)\b/.test(e)?(/^\s*=(?!=)/.test(e)&&(e=at(e)),e=function(e){return e.includes("sorted")?tt(e,/(?<![\w.])sorted\s*\(/g,e=>{if(1!==e.length)return null;const t=e[0];for(let e=0,n=0;e<t.length;e++)if("([{".includes(t[e]))n++;else if(")]}".includes(t[e]))n--;else if(0===n&&("|"===t[e]||"&"===t[e])){const n=e=>{const t=e.trim(),n=/^set\s*\(/.exec(t);return n&&Ke(t,n[0].length-1)===t.length-1?t.slice(n[0].length,-1):null},[r,s]=[n(t.slice(0,e)),n(t.slice(e+1))];return null!==r&&null!==s?`((${r}) ${"|"===t[e]?"∪":"∩"} (${s}))`:null}return null}):e}(e=dt(e=ct(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]?Ke(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=Ke(e,n),s=e.lastIndexOf("Number(",t);r<0||s<0||Ke(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(Je.includes(e[t]))s++;else{if(Ye.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(Ye.includes(e[t]))s++;else{if(Je.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=qt(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(!Tt.test(e))return e;let t=e;const n=(e,n,r,s="∈")=>{t=t.replace(new RegExp(String.raw`(?<![\w.])${At(e)}\s+(${Mt})\s+(?:and|to)\s+(${Mt})(?:\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+(${Mt})\s+to\s+(${Mt})`,"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`(${Mt})\s+`;t=t.replace(new RegExp(r+String.raw`is\s+(not\s+)?within\s+(${Mt})\s*(%|\s+percent)?\s+of\s+(${Mt})`,"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+(${Mt})`,"gi"),"(($1) mod ($2) = 0)"),t=t.replace(new RegExp(r+String.raw`is\s+(not\s+)?divisible\s+by\s+(${Mt})`,"gi"),(e,t,n,r)=>`((${t}) mod (${r}) ${n?"≠":"="} 0)`),t=t.replace(new RegExp(String.raw`(${Mt})\s+divides\s+(${Mt})`,"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 _t)t=t.replace(Nt(e),` ${n} `);t=t.replace(Nt("is not in")," ∉ ").replace(Nt("is in")," ∈ ").replace(Nt("is an element of")," ∈ ");for(const[e,n]of St)t=t.replace(Nt(e),` ${n} `);t=t.replace(Nt("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`(${Mt})\s*(${Ot})\s*(${Mt})\s+(and|or)\s+(${Ot})`,"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+(${Mt})`,"gi"),"abs($1)"),t=t.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?square\s+root\s+of\s+(${Mt})`,"gi"),"sqrt($1)"),t=t.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?cube\s+root\s+of\s+(${Mt})`,"gi"),"root(3, $1)"),t=t.replace(new RegExp(String.raw`(${Mt})\s+to\s+the\s+power\s+of\s+(${Mt})`,"gi"),"($1)^($2)"),t=t.replace(new RegExp(String.raw`(${Mt})\s+to\s+the\s+(${Object.keys(Et).join("|")}|(\d+|n)(?:st|nd|rd|th))(?:\s+power)?(?![\w.])`,"gi"),(e,t,n,r)=>`(${t})^(${Et[n.toLowerCase()]??r})`),t=t.replace(new RegExp(String.raw`(${Mt})\s+to\s+the\s+(${Mt})(?![\w.])`,"gi"),"($1)^($2)");for(const[e,n]of It)t=t.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?${At(e)}\s+of\s+(${Mt})`,"gi"),`${n}($1)`);t=t.replace(new RegExp(String.raw`(${Mt})\s+squared(?![\w.])`,"gi"),"($1)^2"),t=t.replace(new RegExp(String.raw`(${Mt})\s+cubed(?![\w.])`,"gi"),"($1)^3"),t=t.replace(new RegExp(String.raw`(?<![\w.])half\s+of\s+(${Mt})`,"gi"),"($1)/2"),t=t.replace(new RegExp(String.raw`(?<![\w.])twice\s+(${Mt})`,"gi"),"2*($1)"),t=t.replace(new RegExp(String.raw`(\d+(?:\.\d+)?)\s+percent(?![\w.])`,"gi"),"$1%");const s=e=>new RegExp(String.raw`(?<=[\w.′)\]}]\s+)${At(e)}(?=\s+[\w.(\[{-])`,"gi");for(const[e,n]of[["divided by","/"],["over","/"],["multiplied by","*"],["times","*"],["plus","+"],["minus","-"],["modulo","mod"]])t=t.replace(s(e),` ${n} `);return t}],["words",jt],["spaced",function(e){e=function(e){for(let t=e.lastIndexOf("\\sqrt");t>=0;t=t>0?e.lastIndexOf("\\sqrt",t-1):-1){let n=t+5;if(/[A-Za-z]/.test(e[n]??""))continue;for(;pe(e[n]);)n++;const r=e.slice(n);let s=/^(?:§\d+§|-?(?:\d+(?:\.\d+)?|\.\d+)|-?[A-Za-zͰ-Ͽ])/.exec(r)?.[0];if(!s&&/^\\[A-Za-z]/.test(r)&&!r.startsWith("\\left")){let e=/^\\[A-Za-z]+/.exec(r)[0].length;if(/^\d\d/.exec(r.slice(e))&&/frac$/.test(r.slice(0,e)))e+=2;else{const t=/^\s*\[[^\[\]{}]*\]/.exec(r.slice(e));for(t&&(e+=t[0].length);;){let t=e;for(;pe(r[t]);)t++;if("{"!==r[t])break;let n=0,s=-1;for(let e=t;e<r.length;e++)if("{"===r[e])n++;else if("}"===r[e]&&0===--n){s=e;break}if(s<0)break;e=s+1}}s=r.slice(0,e)}s&&(e=`${e.slice(0,t)}\\sqrt{${s}}${e.slice(n+s.length)}`)}return e}(function(e){return e=e.replace(ye,(e,t,n)=>`(${t}+${be[n]})`),e=e.replace(we,(e,t,n,r)=>Number(n)<Number(r)&&3!==n.length?`(${t}+${n}/${r})`:e),e.replace(xe,(e,t,n,r,s,i)=>{const[o,a]=[n??s,r??i];return Number(o)<Number(a)?`(${t}+\\frac{${o}}{${a}})`:e})}(function(e){return e.replace(ve,e=>{const t=e[0]in me;return`${t?"^":"_"}{${[...e].map(e=>(t?me:ge)[e]).join("")}}`})}(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=qe(e,n+2,"then");if(r<0)return e;const s=e.slice(n+2,r),i=qe(e,r+4,"else"),o=Me(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](?:[^()]*[^()\s])?)\s*\)/g," \\pmod{$1}")).replace(/(^|[^A-Za-z\\])lim\s+([^\s_{}]+?)\s*(->|→|\\to)\s*([^\s]+)\s+/g,"$1lim_{$2→$4} ")),e=Ne(e);for(let t=0;t<e.length-1;t++)if("?"===e[t]&&":"!==e[t+1])e=Ae(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}const r=("^"===e[t]||/[A-Za-z}]/.test(e[t-1]??""))&&/^\\[A-Za-z]+(?![A-Za-z{\d])/.exec(e.slice(t+1));if(r){e=`${e.slice(0,t+1)}{${r[0]}}${e.slice(t+1+r[0].length)}`;continue}let s=t+1;for("-"===e[s]&&s++;s<e.length&&".0123456789".includes(e[s]);)s++;if(s===t+2&&"-"===e[t+1]&&(s=t+1),"-"===e[t+1]&&/^\s*[\^!]/.test(e.slice(s,s+8)))continue;s>t+1&&(e=e.slice(0,t+1)+"{"+e.slice(t+1,s)+"}"+e.slice(s))}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",zt],["bar",function(e){let t=0;for(let n=e.indexOf(m,t);n>=0;n=e.indexOf(m,t)){let r=0,s=-1;for(let t=n+1;t<e.length;t++)if("([{".includes(e[t]))r++;else if(")]}".includes(e[t]))r--;else if(0===r&&e.startsWith("|_",t)){s=t;break}s<0&&Ct(),e=`${e.slice(0,n+1)}(${e.slice(n+1,s)})${e.slice(s)}`,t=n+1}return e}],["compact",function(e){if(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)+Pe(e.slice(r,t+1),"x",s)+e.slice(t+1+s),t=r}return e}(e=(e=Ne(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&&Le.test(e[t-1]);let r,s=null,i=t;if(e.startsWith("frac{",t)){const n=Ce(e,t+4),r=n&&Ce(e,n[1]);s=r&&Ze(n[0],r[0]),s&&(i=r[1])}else if("d"===e[t]&&!n){let[n,r]=Fe(e,t+1),o="";if(Le.test(e[r]??"")&&"/"===e[r+1]&&(o=e[r++]),"/"===e[r]&&"d"===e[r+1]&&Le.test(e[r+2]??"")){const t=e[r+2],[,a]=Fe(e,r+3);s={n:n,of:o,by:t},i=a}}if(s){if(s.of)r=Pe(s.of,s.by,s.n);else{const[t,n]=Re(e,i);if(!t)continue;r=Pe(t,s.by,s.n),i=n}e=e.slice(0,t)+r+e.slice(i),t+=3}}return e}(e),e.split("\\int").length>101)throw new Error("More than 100 integrals");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=Ie(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"+Oe(e.slice(t+1)):"sqrt"===r(4)&&(e=e.slice(0,t-4)+"sqrt"+Oe(e.slice(t+1)));else if("⌊"===n||"⌈"===n)e=e.slice(0,t)+Se(e.slice(t));else if("t"===n)"\\int"===s(3)&&(e=e.slice(0,t-3)+Te(e.slice(t+1)));else if("m"===n)"\\binom"===s(5)&&(e=e.slice(0,t-5)+"\\binom"+ze(e.slice(t+1)));else if("d"===n&&"dd"===s(1)&&"("===e[t+2]){const n=je(e.slice(t+1));n&&(e=e.slice(0,t-1)+"der"+n)}}return(e=e.replace(/\\(?:text|textrm|textit|mathrm|mathit|mathbf|mathsf|operatorname)\{([A-Za-z])\}/g,"$1")).replace(/\\log/g,"log")}],["bars",function(e){for(let t=e.indexOf(m);t>=0;t=e.indexOf(m)){const n=Ct;e.startsWith("(der(",t+1)||n();const r=Ft(e,t+1,"(",")"),s=Ft(e,t+5,"(",")");(s<0||r!==s+1)&&n();const i=Zt(e.slice(t+6,s));(i.length<2||i.length>3||!e.startsWith("|_",r+1))&&n();const o=r;let a,l;"{"===e[o+3]?(l=Ft(e,o+3,"{","}"),l<0&&n(),a=e.slice(o+4,l)):(l=o+3,a=e[l]??"");const[u,c,h]=i;a.trim()||n();const p=a.includes("=")?a:`${c}=${a}`;e=`${e.slice(0,t)}der(${u},${p}${h?`,${h}`:""})${e.slice(l+1)}`}return e}],["tidy",e=>e.replace(/ {2,}/g," ").trim()]],Ct=()=>{throw new Error("An evaluation bar (\\left. … \\right|_{x = a}) is read only after a derivative: \\left.\\frac{d}{dx} f\\right|_{x=a}")};function Ft(e,t,n,r){let s=0;for(let i=t;i<e.length;i++)if(e[i]===n)s++;else if(e[i]===r&&0===--s)return i;return-1}function Zt(e){const t=[];let n=0,r=0;for(let s=0;s<e.length;s++)"([{".includes(e[s])?n++:")]}".includes(e[s])?n--:","===e[s]&&0===n&&(t.push(e.slice(r,s)),r=s+1);return t.push(e.slice(r)),t}function Rt(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=We(t.size);t.set(l,s+o+s),n+=l,r=i+1}return{text:n,strings:t}}(Ve(e));let s=n.replace(/\t/g," ");t.evaluate&&(s=function(e,t,n){const r=/\\[A-Za-z]/.test(e);let s=0;for(;;){let i=e.indexOf("{{",s);if(i<0)return e;let o=!1;const a=r&&Pt.test(e.slice(0,i));if(Bt(e,i)||a&&"{"===e[i+2]?i+=1:o=a,!e.startsWith("{{",i)){s=i;continue}const l=Dt(e,i);if(l<0)return e;let u=e.slice(i+2,l).trim();for(const[e,n]of t)u=u.split(e).join(n);try{let r=n(u);if(/^["'`]/.test(r)){const e=We(t.size);t.set(e,r),r=e}const a=e.slice(0,i).trimEnd(),c=e.slice(l+2).trimStart();/^[\d.]/.test(r)&&(/[\d.]$/.test(a)||/^[\d.]/.test(c))&&(r=`(${r})`),o&&(r=`{${r}}`),e=e.slice(0,i)+" "+r+" "+e.slice(l+2),s=i+1+r.length}catch{s=l+2}}}(s,r,t.evaluate));const i=[["strings",s]];for(const[e,t]of Lt){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}}const Pt=/(?:\\[A-Za-z]+\*?|[\^_}\]])$/;function Bt(e,t){let n=0;for(;"\\"===e[t-1-n];)n++;return n%2==1}function Dt(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 Wt=Object.keys(g).filter(e=>100===g[e]&&/^[a-z]{2,}$/.test(e)),Ut=["frac"],Vt=[...Object.keys(T),"pi","tau","inf","infinity","exp"],Ht="\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+/),Gt=new Set([...Vt,...Ht,"true","false","null","undefined","unchanged","deg","mod","pmod","NaN","Infinity"]),Xt=/^[a-zA-ZͰ-Ͽ]$/,Qt=new Set(["f","g","h","u","v","F","G","H"]),Jt=e=>Wt.includes(e)||Ut.includes(e),Yt=[...Wt,...Ut,...Vt].sort((e,t)=>t.length-e.length),Kt=[...Wt,...Ut,"pi"].sort((e,t)=>t.length-e.length);function en(e,t=Yt){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 tn(e){if(Jt(e))return!0;const t=en(e,Kt);return t.length>1&&Jt(t[t.length-1])&&!Gt.has(e)}function nn(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=>Xt.test(e)))||1===e.length||Gt.has(e)||Jt(e))return[e];var r;if("Δ"===e[0]&&2===e.length)return[e];if("latex"===t)return rn(en(e),n);if(e.length<=2)return[...e];const s=rn(en(e,Kt),n),i=s.findIndex(e=>e.length>1);if(i<0)return[e];if("pi"===s[i]&&!s.some(e=>Wt.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 rn(e,t){const n=e[e.length-1];return t||!Wt.includes(n)?e:[...e.slice(0,-1),...n]}const sn="§",on=/[A-Za-zͰ-Ͽ′]/,an=e=>/^[A-Za-zͰ-Ͽ][A-Za-zͰ-Ͽ′]*$/.test(e);function ln(e,t="plain"){if("string"!=typeof e)throw new Error("Tokenizer input must be a string");const n=[];let r="";const s=e=>{r&&(an(r)?n.push(...function(e,t,n){if((e=>Ue.test(e))(e))return[e];if(y.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 Qt.has(e)?[i+e]:[e];if(v(e))return[e];const n=nn(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 nn(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===sn){s(o);const r=e.indexOf(sn,t+1);if(r<0)throw new Error(`An unmatched ${sn}`);const a=e.slice(t,r+1);n.push(y.includes(e[r+1])?i+a:a),t=r;continue}if(an(r)&&/[0-9]/.test(o)&&v(r+o)){const{op:s,end:i}=un(e,t,r+o);n.push(s),r="",t=i;continue}if(on.test(o)&&"′"!==o&&x(r)&&(n.push(r),r=""),on.test(o)&&(""===r?"′"!==o:an(r)))r+=o;else if(/[0-9]/.test(o)&&an(r)&&!tn(r))r+=o;else if(an(r)&&s(" "===o?e[t+1]:o),"(){}[]".includes(o))r&&n.push(...cn(r,o)),r="",n.push(o);else if("_"!==o&&" "!==o){if(v(r+o)){const{op:s,end:i}=un(e,t,r+o);n.push(s),r="",t=i;continue}if(v(o)){s(o);const{op:r,end:i}=un(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 un(e,t,n){let r=t;for(;r+1<e.length&&v(n+e[r+1]);)n+=e[r+1],r++;return"!"===n&&"_"===e[r+1]&&r++,{op:n,end:r}}function cn(e,t){if(!y.includes(t))return[e];if("\\"===e[0]){const t=e.slice(1);return[v(t)?t:i+t]}return x(e)?[e,"*"]:v(e)||Jt(e)||x(e[0])?[e]:[i+e]}const hn=70,pn=100,fn="%mod",dn=e=>y.includes(e),mn=e=>w.includes(e),gn=e=>o(e)||g[e]===pn&&"_"!==e,vn=new Set(["\\comb","\\perm","comb","perm"]),bn={frac:"/","\\binom":"\\binom"},yn=new Set(["<",">","≤","≥","=","==","===","≠","≠=","!=","!==","&","|","\\not","\\xor","∈","∉","true","false"]),wn={"\\comb":"comb","\\perm":"perm",deg:"°","π":"pi","∨":"|"};class xn{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(mn(e)?`Unmatched '${e}'`:`Unexpected '${e}'`);return this.out}parseExpression(e,t=!1){this.parseOperand(),this.absorb(e,t)}absorb(e,t=!1){for(;;){const n=this.peek();if(void 0===n||mn(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:g.mod,run:()=>this.modulo()};if(e===fn)return{lbp:hn,run:()=>{this.next(),this.parseExpression(hn),this.emit("mod")}};if("pmod"===e)return{lbp:g.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:pn,run:()=>{this.next(),this.parseScript(),this.emit("_")}};if(vn.has(e))return{lbp:pn,run:()=>{this.next(),this.parseExpression(pn),this.emit(e)}};const n=g[e];if("="===e&&void 0!==n)return{lbp:n,run:()=>this.equals(n)};if(void 0!==n&&!gn(e)&&"\\not"!==e&&!(e in bn)){const t=b.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&&!gn(e)?71:hn,run:()=>{this.parseExpression(hn),this.emit("*")}}}startsOperand(e){return void 0===e||mn(e)||"|"===e?"|"===e:e!==fn&&(!!(dn(e)||gn(e)||e in bn)||!v(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:g["|"],run:()=>{this.next(),t&&e%2==0&&this.next(),this.parseExpression(g["|"]),this.emit("|")}}}modulo(){this.next(),this.parseExpression(hn,!0),this.emit("mod")}equals(e){this.next(),this.parseExpression(e),yn.has(this.out[this.out.length-1])&&this.questionAhead()&&this.absorb(8),this.emit("=")}questionAhead(){let e=0;for(let t=this.pos;t<this.tokens.length;t++){const n=this.tokens[t];if(dn(n))e++;else if(mn(n)){if(0===e--)return!1}else{if(0===e&&","===n)return!1;if(0===e&&"?"===n)return!0}}return!1}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(dn(e))return this.bracket(e,"{"===e&&("∈"===t||"∉"===t));if("|"===e)return this.absolute();if("-"===e||"+"===e){return"^"===t&&(void 0===n||mn(n))||dn(t)&&mn(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 bn)return this.parseScript(),this.parseScript(),this.emit(bn[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(gn(e))return this.functionCall(e);if(e===fn)throw new Error("'%' is missing an operand");if(mn(e)||v(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||!x(t[0])&&"∞"!==t[0]?this.emit("neg"):this.out[e]="-"+t[0]}bracket(e,t=!1){if(mn(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();mn(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(dn(e))return this.parseOperand();if("-"===e||"+"===e)return this.parseOperand();if(gn(e))return this.parseOperand();if(this.next(),void 0===e||mn(e)||v(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(g["+"],!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(g["+"],!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&&!dn(this.peek()))return this.emit(e);this.argument(),this.emit(e),t&&this.emit(...t,"^")}argument(){const e=this.peek();if(dn(e))return this.next(),this.bracket(e);this.parseExpression(hn,!0)}}function $n(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(Qt.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:x(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)v(r)||dn(r)||mn(r)||"_"===r||o(r)||x(r)?n.push(r):n.push(...kn(r,t));return n}function kn(e,t){if("%"===e)return[fn];if(!e.includes("%"))return qn(e,t);const n=e.split("%");n.length>1&&""===n[n.length-1]&&(n.pop(),n[n.length-1]+="%");const r=[];return n.forEach((e,n)=>{n>0&&r.push(fn),""!==e&&r.push(...qn(e,t))}),r}function qn(e,t){let n=0;for(;n<e.length&&x(e.slice(0,n+1));)n++;if(0===n||n===e.length)return[e];const r=e.slice(n);return"%"===r?[e]:[e.slice(0,n),...(s=r,$n(ln(s,t),t))];var s}for(const e of[bn,wn])Object.setPrototypeOf(e,null);const Mn=new Set(["()","[]","{}","(]","[)"]),An={pow:"^",sqrtpow:"root","\\binom":"comb","\\comb":"comb","\\perm":"perm",frac:"/","==":"=","!==":"≠=",...Object.fromEntries(Object.keys(d).map(e=>[e,"*"]))},Nn=new Set(["round","fixed","der"]),Sn=e=>o(e)||100===g[e];function On(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((o,l)=>{if("∅"===o)return void n.push({list:[]});if(","===o){const e=r(o),t=r(o);return void n.push({list:[...s(t),...s(e)]})}if(Mn.has(o)){const t=s(r(o));if(!t.length&&!Sn(e[l+1]))throw new Error("Empty brackets");return void n.push(q(o,t))}const u=An[o]??o,c=a(u);if(!c){if("?"===o||"abs("===o)throw new Error(`Unmatched '${o[0]}'`);return void n.push(A(o))}let h;if(Sn(o)&&Mn.has(e[l-1])&&n[n.length-1]?.op===e[l-1])h=n.pop().args;else{let e=c.arity===t||Nn.has(u)?1:c.arity;if(n.length<e)throw new Error(`'${o}' needs ${e} operand${1===e?"":"s"}`);h=n.splice(n.length-e,e).map(e=>i(e,o))}const p=function(e,t){switch(e){case"sqrt":if(2===t.length)return q("root",t);break;case"round":if(1===t.length)return q("round",[t[0],$(0)]);break;case"sum":case"prod":{const n=t[1];if("op"===n?.type&&"symbol"===n.args[0]?.type&&(3===t.length&&"="===n.op||2===t.length&&"∈"===n.op))return q("sum"===e?"\\sumidx":"\\prodidx",t);break}case"det":if(t.length>1&&t.every(e=>"op"===e.type&&"[]"===e.op))return q("det",[q("[]",t)]);break;case"fixed":if(1===t.length)return q("fixed",[t[0],$(2)]);break;case"der":if(1===t.length)return q("der",[t[0],k("x")]);if(3===t.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");const s="op"===t.type&&"="===t.op?t:null,i=s?s.args[0]:t;let o=e;for(let e=0;e<r;e++)o=q("der",[o,s&&e===r-1?s:i]);return o}(t);break;case"log":if(2===t.length&&"symbol"===t[0].type&&"e"===t[0].value)return q("ln",[t[1]]);break;case"lim":return In(e,t),q("lim",function(e){const t=e=>"op"===e.type&&"^"===e.op&&"symbol"===e.args[1].type?En[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],k(t(s))]}return 3===e.length&&t(s)?[n,r,s.args[0],k(t(s))]:e}(t));case"\\:if":if(2===t.length||3===t.length)return q("?:",[t[0],t[1],t[2]??k("unchanged")]);throw new Error("if() takes a condition, a value, and optionally an alternative")}return In(e,t),q(e,t)}(u,h);d[o]&&"*"===p.op&&(p.written=d[o]),n.push(p)}),1!==n.length)throw new Error(n.length?"Some values are not connected by an operator":"Empty expression");return i(n[0],"end")}const En={"\\+":"r","\\-":"l"};function In(e,n){const{arity:r}=a(e);if(r!==t){if(n.length!==r){throw new Error(`'${e}' takes ${r} argument${1===r?"":"s"}, not ${n.length}`)}}else if(0===n.length&&!o(e))throw new Error(`'${e}' needs at least one argument`)}for(const e of[An,En])Object.setPrototypeOf(e,null);const _n=new RegExp(`[${Object.keys(d).join("")}]`,"g"),Tn=e=>e.replace(_n,"*"),jn=/\\(?:text|textrm|textit|mathrm|mathit|operatorname)\{\s*([A-Za-z][A-Za-z0-9 ]*[A-Za-z0-9])\s*\}/g;const zn=e=>/^[a-z][a-z0-9]*$/.test(e)&&v(e);function Ln(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=ke(e.slice(t+13,n),"\\\\").map(e=>ke(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=$e(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 Cn=null;function Fn(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)`);if(e.includes(""))throw new Error("The character U+E000 can't be read: MathZetta uses it to hold § in strings");if((e=function(e,t,n){if(!e.includes(t))return e;const r=Ve(e);let s="";for(let i=0;i<r.length;i++){const o=r[i];if('"'===o||"`"===o||"'"===o){const o=He(r,i);s+=e.slice(i,o+1).replaceAll(t,n),i=o}else s+=e[i]}return s}(e,sn,"")).includes(sn))throw new Error(`The character ${sn} can't be read: MathZetta uses it to mark names`);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=new Map,i=e=>{let t=s.get(e);return void 0===t&&(t=`${sn}${r.size}${sn}`,r.set(t,e),s.set(e,t)),t};e=e.replace(jn,(e,t)=>zn(t.trim())?` ${t.trim()}`:i(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"),()=>i(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)=>i(t)+(r?" * (":n))}return{text:e,protectedNames:r}}(Ln(e),t.names,[...t.values??[],...i]),l=(e=>/\\[A-Za-z]/.test(e)?"latex":"plain")(o),{cleaned:u,stringMap:c,steps:h}=function(e,t={}){const n=void 0===t.blocks?Cn:t.blocks;return Rt(e,{evaluate:n?e=>n(e,t.scope):void 0})}(o,{blocks:t.blocks,scope:t.scope}),p=e=>Xe(Xe(e,c),a).map(e=>"string"==typeof e?e.replaceAll("",sn):e);n.mode=l,n.cleaned=Tn(p([u])[0]),n.cleanSteps=h.map(([e,t])=>[e,Tn(t)]);const f=ln(u,l);n.tokens=f.map(Tn);const d=p(function(e,t="plain"){return new xn($n(e,t)).parseAll().map(e=>wn[e]??e)}(f,l));n.rawPostfix=d.map(Tn);const m={},g=O(On(d),m);n.postfix=g,n.written=m,n.tree=S(g),Object.keys(m).length&&I(n.tree,e=>{m[e.id]&&(e.written=m[e.id])})}catch(e){n.error=e instanceof RangeError?"Nested too deeply":e.message}return n}const Zn=e=>"string"==typeof e&&e.length>80?`${e.slice(0,77)}…`:e;function Rn(e,t={}){const n=Fn(e,t);if(n.error)throw new Error(`Failed to parse expression "${Zn(e)}": ${n.error}`);return n.tree}const Pn=(e,t)=>"string"==typeof e?Rn(e,t):E(e),Bn=e=>Array.isArray(e)&&0===e.length,Dn=oe({add:(e,t)=>e+t,sub:(e,t)=>e-t,mul:(e,t)=>e*t,div:(e,t)=>e/t,isZero:e=>Math.abs(e)<1e-12,zero:()=>0,one:()=>1,size:Math.abs,charge:e=>{if(or+=e/16,or>ir)throw new Error("Too much to work out")},fail:e=>{throw new Error(e)}}),Wn=e=>se(e)&&(e.length>1||e[0].length>1),Un=e=>ie(e)&&!Wn(e),Vn=e=>{const t=(n,r)=>{if(Array.isArray(n)&&Array.isArray(r)){if(n.length!==r.length)throw new Error("Lists of different lengths");return n.map((e,n)=>t(e,r[n]))}return Array.isArray(n)?n.map(e=>t(e,r)):Array.isArray(r)?r.map(e=>t(n,e)):e(n,r)};return t},Hn=(e,t)=>Wn(e)&&Wn(t)?Dn.times(e,t):Wn(e)&&Un(t)?Dn.timesVector(e,t):Un(e)&&Wn(t)?Dn.vectorTimes(e,t):Vn((e,t)=>e*t)(e,t),Gn=(e,t)=>n=>{const r=n.length>1&&n.every(Un)?n:n[0];if(!se(r))throw new Error(`${t}() needs a matrix`);return e(r)},Xn=(e,t)=>([n,r])=>{if(!ie(n)||!ie(r))throw new Error(`${t}() needs two lists`);return e(n,r)},Qn={det:Gn(Dn.det,"det"),inv:Gn(Dn.inverse,"inv"),inverse:Gn(Dn.inverse,"inverse"),transpose:Gn(Dn.transpose,"transpose"),trace:Gn(Dn.trace,"trace"),tr:Gn(Dn.trace,"tr"),rank:Gn(Dn.rank,"rank"),rref:Gn(Dn.rref,"rref"),identity:([e])=>{if(!Number.isInteger(e)||e<1||e>100)throw new Error("identity(n) takes a whole number from 1 to 100");return Dn.identity(e)},dot:Xn(Dn.dot,"dot"),cross:Xn(Dn.cross,"cross"),linsolve:([e,t])=>{if(!se(e)||!Array.isArray(t))throw new Error("linsolve() needs a matrix and a list");return Dn.solve(e,t)}},Jn=(e,t)=>e.args.map(e=>"op"===e.type&&"[]"===e.op?e.args.map(e=>lr(e,t)):[lr(e,t)]),Yn={pi:Math.PI,"π":Math.PI,e:Math.E,tau:2*Math.PI,"τ":2*Math.PI,"∞":1/0,"-∞":-1/0,true:!0,false:!1},Kn=(e,t)=>t?Kn(t,e%t):Math.abs(e),er=(e,t)=>(e%t+t)%t,tr=(e,t)=>Array.isArray(e)&&Array.isArray(t)?e.length===t.length&&e.every((e,n)=>tr(e,t[n])):e==t,nr={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,det:e=>Qn.det([e]),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},rr={"+":(e,t)=>Array.isArray(e)||Array.isArray(t)?Vn((e,t)=>e+t)(e,t):e+t,"-":(e,t)=>Array.isArray(e)||Array.isArray(t)?Vn((e,t)=>e-t)(e,t):e-t,"*":Hn,"/":(e,t)=>Wn(t)?Hn(e,Dn.inverse(t)):Array.isArray(e)||Array.isArray(t)?Vn((e,t)=>e/t)(e,t):e/t,"^":(e,t)=>{if(!Wn(e))return Array.isArray(e)?Vn((e,t)=>e**t)(e,t):e**t;if(!Number.isInteger(t))throw new Error("A matrix to a power that is not a whole number");return Dn.power(e,BigInt(t))},mod:er,log:(e,t)=>Math.log(t)/Math.log(e),root:(e,t)=>t<0&&Number.isInteger(e)&&e%2!=0?-((-t)**(1/e)):t**(1/e),atan2:Math.atan2,round:(e,t)=>(e=>Math.sign(e)*Math.round(Math.abs(e)))(e*10**t)/10**t,"±":(e,t)=>[e+t,e-t],fixed:(e,t)=>{const n=Math.trunc(t);if(!(n>=0&&n<=100))throw new Error("fixed() takes 0 to 100 decimals");return Number(e).toFixed(n)},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)},"=":tr,"===":(e,t)=>e===t,"≠":(e,t)=>!tr(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)},sr={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(Kn,0),"()":e=>e,"[]":e=>e,"{}":e=>e};const ir=5e6;let or=0,ar=0;function lr(e,t){if(++or>ir)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(Yn,e.value))return Yn[e.value];if(z(e.value))return Number(z(e.value));throw new Error(`No value for '${e.value}'`)}const n=te(e);if(n)return lr(n,t);const{op:r,args:s}=e;if("?:"===r)return lr(s[0],t)?lr(s[1],t):lr(s[2],t);if("∈"===r||"∉"===r)return function(e,t){const[n,r]=e.args,s=lr(n,t);let i;if("symbol"===r.type&&ur[r.value])return i=ur[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=>lr(e,t)),o="["===r.op[0]?s>=e:s>e,a="]"===r.op[1]?s<=n:s<n;i=o&&a}else{const e=lr(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){const e="op"===s[1].type&&"="===s[1].op&&"symbol"===s[1].args[0].type,[n,i,o]=[s[0],e?s[1].args[1]:s[1],s[2]],a=e?s[1].args[0].value:_(n);if(!a)throw new Error(`Can't evaluate '${r}' without an index`);const l=lr(i,t),u=lr(o,t);if(!Number.isFinite(l)||!Number.isFinite(u)||u-l>1e6||Math.abs(l)>Number.MAX_SAFE_INTEGER||Math.abs(u)>Number.MAX_SAFE_INTEGER)throw new Error(`Can't evaluate '${r}' over that range`);let c="\\sumidx"===r?0:1;for(let e=l;e<=u;e++){const s=lr(n,{...t,[a]:e});c="\\sumidx"===r?c+s:c*s}return c}if("pmod"===r){const[e,n]=s,r=lr(n,t);if("op"===e.type&&["≡","="].includes(e.op)){const[n,s]=e.args.map(e=>lr(e,t));return(n-s)%r===0}return er(lr(e,t),r)}if("pmatrix"===r||"bmatrix"===r)return Jn(e,t);if("vmatrix"===r)return Dn.det(Jn(e,t));if("^"===r&&"symbol"===s[1].type&&"T"===s[1].value&&!Object.prototype.hasOwnProperty.call(t,"T")){const e=lr(s[0],t);if(Wn(e))return Dn.transpose(e)}const i=s.map(e=>lr(e,t));if(r.startsWith("\\:")&&Object.prototype.hasOwnProperty.call(Qn,r.slice(2)))return Qn[r.slice(2)](i);if(nr[r]&&1===i.length)return nr[r](i[0]);if(rr[r]&&2===i.length)return rr[r](i[0],i[1]);if(sr[r])return sr[r](i);throw new Error(`Can't evaluate '${r}'`)}const ur={"ℝ":Number.isFinite,"ℤ":Number.isInteger,"ℕ":e=>Number.isInteger(e)&&e>0,"ℚ":Number.isFinite,"ℂ":e=>"number"==typeof e&&!Number.isNaN(e)};for(const e of[Yn,nr,rr,sr,ur,Qn])Object.setPrototypeOf(e,null);class cr extends Error{}class hr extends Error{}const pr={bits:2e5,factorial:2e4,terms:1e5,rootIndex:12,steps:5e6,places:1e4};let fr=0;function dr(e){if(fr+=e,fr>pr.steps)throw new hr("too much to work out")}const mr=(e,t)=>dr(Number(e)*(t/64)/128);let gr=0;const vr=e=>e<0n?-e:e,br=0xFFFFFFFFFFFFn,yr=e=>0n===e?0:vr(e).toString(2).length;function wr(e,t){for(e=vr(e),t=vr(t);t;)[e,t]=[t,e%t];return e}function xr(e,t=1n){if(0n===t)throw new cr("division by zero");if(t<0n&&(e=-e,t=-t),t>br&&(e>br||-e>br)){const n=Math.min(e.toString(16).length-(e<0n?1:0),t.toString(16).length)/16;if(fr+=1+n*n/2,fr>pr.steps)throw new hr("too much to work out")}const n=wr(e,t)||1n;return{n:e/n,d:t/n}}const $r=xr(0n),kr=xr(1n),qr=(e,t)=>xr(e.n*t.d+t.n*e.d,e.d*t.d),Mr=(e,t)=>xr(e.n*t.n,e.d*t.d),Ar=(e,t)=>xr(e.n*t.d,e.d*t.n),Nr=e=>({n:-e.n,d:e.d}),Sr=(e,t)=>{const n=e.n*t.d-t.n*e.d;return n<0n?-1:n>0n?1:0},Or=e=>{const t=e.n/e.d;return e.n<0n&&t*e.d!==e.n?t-1n:t};function Er(e){if(e.n<0n)return-Er(Nr(e));const t=yr(e.n),n=yr(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 Ir(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 hr(`'${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=qr(xr(BigInt(o||"0")),xr(s-r,(10n**BigInt(e)-1n)*10n**BigInt(n.length)))}else l=xr(BigInt(o+a||"0"),10n**BigInt(a.length));if(Math.abs(s)>pr.bits/3)throw new hr("too large to calculate");return s&&(l=s>0?Mr(l,xr(10n**BigInt(s))):Ar(l,xr(10n**BigInt(-s)))),n<0n?Nr(l):l}function _r(e,t=0,n=0,r=null){return 0n===e.n?{kind:"x",c:$r,pi:0,e:0,root:null}:{kind:"x",c:e,pi:t,e:n,root:r}}const Tr=(e,t=1n)=>_r(xr(BigInt(e),BigInt(t))),jr=_r(kr,1),zr=_r(kr,0,1),Lr=e=>null!==e&&"object"==typeof e&&"x"===e.kind,Cr=e=>Lr(e)&&!e.pi&&!e.e&&!e.root,Fr=e=>Lr(e)?0n===e.c.n:0===e,Zr=e=>Cr(e)&&1n===e.c.d?e.c.n:null,Rr=(e,t)=>Object.assign(e,{group:t}),Pr=e=>({kind:"s",text:e});function Br(e,t){return e&&t?e.n===t.n&&e.r===t.r:e===t}const Dr=(e,t)=>0===Sr(e.c,t.c)&&e.pi===t.pi&&e.e===t.e&&Br(e.root,t.root);function Wr(e){const t=Math.max(0,yr(e)-60);return t+Math.log2(Number(e>>BigInt(t)))}function Ur(e){if("number"==typeof e)return e;if(Lr(e)){let t=Er(e.c);if(e.pi&&(t*=Math.PI**e.pi),e.e&&(t*=Math.E**e.e),e.root){const n=function(e,t){const n=Number(e);return Number.isFinite(n)?n**(1/t):2**(Wr(e)/t)}(e.root.r,e.root.n);if(!(0n===e.c.n||0!==t&&Number.isFinite(t)&&Number.isFinite(n))){const t=Wr(e.c.n<0n?-e.c.n:e.c.n)-Wr(e.c.d)+Wr(e.root.r)/e.root.n+e.pi*Math.log2(Math.PI)+e.e*Math.LOG2E;return(e.c.n<0n?-1:1)*2**t}t*=n}return t}if("boolean"==typeof e)return e?1:0;throw new hr("not a number")}function Vr(e,...t){if(Number.isNaN(e))throw new cr("undefined");if(!Number.isFinite(e)&&t.every(Number.isFinite))throw new hr("too large to calculate");return e}const Hr=e=>"boolean"==typeof e?e:Lr(e)?0n!==e.c.n:"number"==typeof e?0!==e:Boolean(e);function Gr(e){if("bigint"==typeof e)return _r(xr(e));if("number"==typeof e)return Number.isFinite(e)?_r(Number.isInteger(e)&&Math.abs(e)<=Number.MAX_SAFE_INTEGER?xr(BigInt(e)):Ir(String(e))):e;if("boolean"==typeof e)return e;if("string"==typeof e)return/^-?(\d+\.?\d*|\.\d+)(\.\.)?$/.test(e.trim())?_r(Ir(e)):Ds(Rn(e),{});if(Array.isArray(e))return!e.group&&se(e)?Rr(e.map(e=>Rr(e.map(Gr),"[]")),"[]"):Rr(e.map(Gr),e.group||"()");if(Lr(e)||"function"==typeof e)return e;throw new hr(`can't use ${typeof e} as a value`)}function Xr(e){return Array.isArray(e)?e.map(Xr):e&&"s"===e.kind?e.text:"boolean"==typeof e?e:Ur(e)}function Qr(e,t){if(e<2n)return e;const n=BigInt(t);let r=1n<<BigInt(Math.ceil(yr(e)/t));for(;;){const t=((n-1n)*r+e/r**(n-1n))/n;if(t>=r)return r;r=t}}function Jr(e,t,n,r=0,s=0){if(0n===n)return _r($r);const{coef:i,root:o}=function(e,t){let n=1n,r=t;const s=BigInt(e),i=r<10n**24n?1000000n:10000n;let o=0;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;o++}fr+=o/4;const a=Qr(r,e);if(a**s===r&&(n*=a,r=1n),1n===r)return{coef:n,root:null};for(let t=e;t>=2;t--){if(e%t!==0)continue;const s=Qr(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?_r(Mr(e,xr(i*o.r)),r,s):_r(Mr(e,xr(i)),r,s,o)}function Yr(e,t){const n=Mr(e.c,t.c);if(yr(n.n)+yr(n.d)>pr.bits)return null;const r=e.pi+t.pi,s=e.e+t.e;if(!e.root||!t.root)return _r(n,r,s,e.root||t.root);const i=Ns(e.root.n,t.root.n);if(i>pr.rootIndex)return null;const o=e.root.r**BigInt(i/e.root.n)*t.root.r**BigInt(i/t.root.n);return yr(o)>4e3?null:Jr(n,i,o,r,s)}function Kr(e){if(0n===e.c.n)throw new cr("division by zero");const t=_r(Ar(kr,e.c),-e.pi,-e.e);if(!e.root)return t;const{n:n,r:r}=e.root;return yr(r)*(n-1)>4e3?null:Yr(t,Jr(xr(1n,r),n,r**BigInt(n-1)))}function es(e,t){if(0n===t){if(0n===e.c.n)throw new cr("0^0 is undefined");return _r(kr)}if(t<0n){const n=Kr(e);return n&&es(n,-t)}if((yr(e.c.n)+yr(e.c.d)+(e.root?yr(e.root.r):0))*Number(t)>pr.bits||t>100000n)return null;const n=xr(e.c.n**t,e.c.d**t),r=Number(t);if(!e.root)return _r(n,e.pi*r,e.e*r);const{n:s,r:i}=e.root,o=i**(t/BigInt(s));return Jr(Mr(n,xr(o)),s,i**(t%BigInt(s))||1n,e.pi*r,e.e*r)}function ts(e,t,n){if(!Cr(e)||n>1000n)return null;const r=es(e,t);if(!r)return null;let{n:s,d:i}=r.c,o=!1;if(s<0n){if(n%2n==0n)throw new cr("not a real number");o=!0,s=-s}const a=function(e,t){const n=e.n*e.d**BigInt(t-1);return yr(n)>4e3?null:Jr(xr(1n,e.d),t,n)}({n:s,d:i},Number(n));return a?o?_r(Nr(a.c),a.pi,a.e,a.root):a:null}function ns(e){return t=>Array.isArray(t)?Rr(t.map(t=>ns(e)(t)),t.group):e(t)}function rs(e){const t=(n,r)=>{const s=Array.isArray(n),i=Array.isArray(r);if(s&&i){if(n.length!==r.length)throw new cr("lists of different lengths");return Rr(n.map((e,n)=>t(e,r[n])),n.group)}return s?Rr(n.map(e=>t(e,r)),n.group):i?Rr(r.map(e=>t(n,e)),r.group):e(n,r)};return t}const ss=rs((e,t)=>Lr(e)&&Lr(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||!Br(e.root,t.root))return null;const n=qr(e.c,t.c);return yr(n.n)+yr(n.d)>pr.bits?null:_r(n,e.pi,e.e,e.root)}(e,t)||Vr(Ur(e)+Ur(t),Ur(e),Ur(t))),is=ns(e=>Lr(e)?_r(Nr(e.c),e.pi,e.e,e.root):-Ur(e)),os=(e,t)=>ss(e,is(t)),as=rs((e,t)=>Lr(e)&&Lr(t)&&Yr(e,t)||Vr(Ur(e)*Ur(t),Ur(e),Ur(t))),ls=rs((e,t)=>{if(Fr(t))throw new cr("division by zero");if(Lr(e)&&Lr(t)){const n=Kr(t),r=n&&Yr(e,n);if(r)return r}return Vr(Ur(e)/Ur(t),Ur(e),Ur(t))}),us=rs((e,t)=>{if(Lr(e)&&Cr(t)){const{n:n,d:r}=t.c,s=1n===r?es(e,n):ts(e,n,r);if(s)return s}const n=Ur(e),r=Ur(t);if(0===n&&0===r)throw new cr("0^0 is undefined");if(0===n&&r<0)throw new cr("division by zero");if(n<0&&!Number.isInteger(r))throw new cr("not a real number");const s=n**r;if(0===s&&0!==n)throw new hr("too small to calculate");return Vr(s,n,r)});function cs(e,t){if(Cr(e)&&Cr(t))return Sr(e.c,t.c);if(Lr(e)&&Lr(t)&&Dr(e,t))return 0;const n=Ur(e),r=Ur(t);if(n===r)return 0;const s=Lr(e)&&Lr(t)?Math.max(Math.abs(n),Math.abs(r)):Math.max(1,Math.abs(n),Math.abs(r));return Number.isFinite(n)&&Number.isFinite(r)&&Math.abs(n-r)<=1e-12*s?0:n<r?-1:1}function hs(e,t){return Array.isArray(e)||Array.isArray(t)?Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>hs(e,t[n])):e&&"s"===e.kind||t&&"s"===t.kind?Boolean(e&&"s"===e.kind&&t&&"s"===t.kind&&e.text===t.text):"boolean"==typeof e||"boolean"==typeof t?e===t:0===cs(e,t)}const ps={0:()=>Tr(0),2:()=>Tr(1,2),3:()=>Jr(xr(1n,2n),2,2n),4:()=>Jr(xr(1n,2n),2,3n),6:()=>Tr(1)};function fs(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=ps[t];return r?n<0?is(r()):r():null}const ds=e=>fs(e+6),ms=(e,t)=>Math.abs(e)<1e-15&&Math.abs(t)>1e-6?0:e;function gs(e,t){const n=function(e){if(Fr(e))return 0;if(!Lr(e)||1!==e.pi||e.e||e.root)return null;const t=Mr(e.c,xr(12n));return 1n!==t.d?null:Number((t.n%24n+24n)%24n)}(t);if(null!==n){const t=fs(n),r=ds(n);if(t&&r)switch(e){case"sin":return t;case"cos":return r;case"tan":return ls(t,r);case"cot":return ls(r,t);case"sec":return ls(Tr(1),r);case"csc":return ls(Tr(1),t)}}const r=Ur(t),s=ms(Math.sin(r),r),i=ms(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 cr("undefined");return Vr(o)}function vs(e,t){const n={arcsin:[-6,6],arccos:[0,12],arctan:[-5,5]}[e],r=t=>"arcsin"===e?fs(t):"arccos"===e?ds(t):ds(t)&&!Fr(ds(t))?ls(fs(t),ds(t)):null;if(Lr(t))for(let e=n[0];e<=n[1];e++){const n=r(e);if(n&&Lr(n)&&Dr(n,t))return _r(xr(BigInt(e),12n),1)}const s=Ur(t);if("arctan"!==e&&Math.abs(s)>1)throw new cr("not a real number");return{arcsin:Math.asin,arccos:Math.acos,arctan:Math.atan}[e](s)}function bs(e){if(Lr(e)){if(0n===e.c.n)throw new cr("ln 0 is undefined");if(e.c.n<0n)throw new cr("not a real number");if(1n===e.c.n&&1n===e.c.d&&!e.pi&&!e.root)return Tr(e.e)}const t=Ur(e);if(t<=0)throw new cr(0===t?"ln 0 is undefined":"not a real number");return Math.log(t)}function ys(e){if(e<.5)return Math.PI/(Math.sin(Math.PI*e)*ys(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 ws(e,t){const n=Zr(e)??("number"==typeof e&&Number.isInteger(e)?BigInt(e):null);if(null===n)throw new cr(`${t} needs whole numbers`);return n}const xs=(e,t)=>Number(t)*yr(e)>pr.bits;const $s=ns(e=>Cr(e)?_r(xr(Or(e.c))):Gr(Math.floor(Ur(e)))),ks=ns(e=>Cr(e)?_r(xr(-Or(Nr(e.c)))):Gr(Math.ceil(Ur(e))));function qs(e,t){const n=Number(ws(t,"round"));if(Math.abs(n)>pr.places)throw new hr("too many decimal places");if(Cr(e)){const t=xr(10n**BigInt(Math.abs(n))),r=n>=0?Mr(e.c,t):Ar(e.c,t),s=Or(qr(Mr(xr(2n),xr(vr(r.n),r.d)),kr))/2n,i=xr(r.n<0n?-s:s);return _r(n>=0?Ar(i,t):Mr(i,t))}if(n>15)return Ur(e);const r=10**n;return 0===r?0:Math.sign(Ur(e))*Math.round(Math.abs(Ur(e))*r)/r}const Ms=(e,t)=>e.toFixed(Math.min(t,100))+(t>100?"0".repeat(t-100):"");function As(e,t){if(Fr(t))throw new cr("division by zero");if(Cr(e)&&Cr(t))return _r(qr(e.c,Nr(Mr(t.c,xr(Or(Ar(e.c,t.c)))))));const n=Ur(e),r=Ur(t);return Vr((n%r+r)%r)}const Ns=(e,t)=>e/Ss(e,t)*t,Ss=(e,t)=>t?Ss(t,e%t):e,Os={pi:()=>jr,"π":()=>jr,tau:()=>_r(xr(2n),1),"τ":()=>_r(xr(2n),1),e:()=>zr,"∞":()=>1/0,"-∞":()=>-1/0,true:()=>!0,false:()=>!1},Es={abs:e=>Lr(e)?_r(xr(vr(e.c.n),e.c.d),e.pi,e.e,e.root):Math.abs(Ur(e)),floor:$s,ceil:ks,sqrt:e=>us(e,Tr(1,2)),ln:ns(bs),loglog:ns(e=>bs(bs(e))),logloglog:ns(e=>bs(bs(bs(e)))),expm1:ns(e=>Fr(e)?Tr(0):Math.expm1(Ur(e))),sinh:ns(e=>Fr(e)?Tr(0):Math.sinh(Ur(e))),cosh:ns(e=>Fr(e)?Tr(1):Math.cosh(Ur(e))),tanh:ns(e=>Fr(e)?Tr(0):Math.tanh(Ur(e))),arcsinh:ns(e=>Fr(e)?Tr(0):Math.asinh(Ur(e))),arccosh:ns(e=>{const t=Ur(e);if(t<1)throw new cr("not a real number");return 1===t?Tr(0):Math.acosh(t)}),arctanh:ns(e=>{const t=Ur(e);if(Math.abs(t)>=1)throw new cr("undefined");return Fr(e)?Tr(0):Math.atanh(t)}),"!":ns(function(e){const t=Zr(e)??("number"==typeof e&&Number.isInteger(e)?BigInt(e):null);if(null!==t){if(t<0n)throw new cr("factorial of a negative number");if(t>BigInt(pr.factorial))throw new hr("too large to calculate");mr(t,Number(t)*Math.log2(Number(t)+1));let e=1n;for(let n=2n;n<=t;n++)e*=n;return _r(xr(e))}const n=Ur(e);if(n<0&&Number.isInteger(n))throw new cr("factorial of a negative number");return Vr(ys(n+1),n)}),neg:is,pm:e=>Rr([e,is(e)],"pm"),"\\not":e=>!Hr(e),det:e=>Fs.det(e)};for(const e of["sin","cos","tan","csc","sec","cot"])Es[e]=ns(t=>gs(e,t));for(const e of["arcsin","arccos","arctan"])Es[e]=ns(t=>vs(e,t));const Is=new Set(["pmatrix","bmatrix"]),_s=e=>se(e)&&(Is.has(e.group)||"[]"===e.group&&e.every(e=>"[]"===e.group)&&(e.length>1||e[0].length>1)),Ts=e=>ie(e)&&!_s(e)&&"pm"!==e.group,js=oe({add:ss,sub:os,mul:as,div:ls,charge:dr,isZero:e=>Lr(e)?0n===e.c.n:Math.abs(Ur(e))<1e-12,zero:()=>Tr(0),one:()=>Tr(1),size:e=>Math.abs(Ur(e)),fail:e=>{throw new cr(e)},make:(e,t)=>Rr(e.map(e=>Rr(e,"[]")),t&&t.group?t.group:"bmatrix")}),zs=(e,t)=>Rr(e,t&&t.group?t.group:"[]"),Ls=(e,t)=>(...n)=>{const r=n.length>1&&n.every(Ts)?Rr(n.map(e=>Rr(e,"[]")),"[]"):n[0];if(n.length>1&&r===n[0])throw new hr(`${e} of more than one thing`);if(!_s(r))throw new hr(`${e} of something that isn't a matrix`);return t(r)};function Cs(e,t){return _s(e)&&_s(t)?js.times(e,t):_s(e)&&Ts(t)?zs(js.timesVector(e,t),t):Ts(e)&&_s(t)?zs(js.vectorTimes(e,t),e):as(e,t)}const Fs={det:Ls("det",js.det),inv:Ls("inv",js.inverse),inverse:Ls("inverse",js.inverse),transpose:Ls("transpose",js.transpose),trace:Ls("trace",js.trace),tr:Ls("tr",js.trace),rank:Ls("rank",e=>Tr(js.rank(e))),rref:Ls("rref",js.rref),identity:e=>{const t=Zr(e);if(null===t||t<1n||t>100n)throw new hr("identity(n) needs a whole number n");return js.identity(Number(t))},dot:(e,t)=>{if(!Ts(e)||!Ts(t))throw new hr("dot of something that isn't a vector");return js.dot(e,t)},cross:(e,t)=>{if(!Ts(e)||!Ts(t))throw new hr("cross of something that isn't a vector");return zs(js.cross(e,t),e)},linsolve:(e,t)=>{if(!_s(e)||!_s(t)&&!Ts(t))throw new hr("linsolve(A, b) needs a matrix and a vector");return _s(t)?js.solve(e,t):zs(js.solve(e,t),t)}};function Zs(e,t){const n=e.args.map(e=>Rr("op"===e.type&&"[]"===e.op?e.args.map(t):[t(e)],"[]"));if(n.some(e=>e.length!==n[0].length))throw new cr("rows of different lengths");return Rr(n,"vmatrix"===e.op?"bmatrix":e.op)}const Rs={"+":ss,"-":os,"*":Cs,"/":(e,t)=>_s(t)?Cs(e,js.inverse(t)):ls(e,t),"^":function(e,t){if(!_s(e))return us(e,t);const n=Zr(t);if(null===n)throw new hr("a matrix to a power that is not a whole number");return js.power(e,n)},"±":(e,t)=>Rr([ss(e,t),os(e,t)],"pm"),mod:rs(As),log:rs(function(e,t){if(Lr(e)&&Dr(e,zr))return bs(t);const n=Ur(e),r=Ur(t);if(n<=0||1===n)throw new cr("not a valid base");if(r<=0)throw new cr(0===r?"log 0 is undefined":"not a real number");const s=Math.log(r)/Math.log(n);if(Cr(e)&&Cr(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=es(e,BigInt(r)),o=es(t,n);if(i&&o&&Dr(i,o))return _r(xr(BigInt(r),n))}return s}),root:rs((e,t)=>us(t,ls(Tr(1),e))),atan2:(e,t)=>Math.atan2(Ur(e),Ur(t)),round:qs,fixed:function(e,t){const n=Number(ws(t,"fixed"));if(n<0)throw new cr("fixed needs 0 or more decimal places");const r=qs(e,t);if(Cr(r)){const e=r.c.n*10n**BigInt(n)/r.c.d,t=(e<0n?-e:e).toString().padStart(n+1,"0");return Pr(`${e<0n?"-":""}${t.slice(0,t.length-n)}${n?"."+t.slice(-n):""}`)}return Pr(Ms(Ur(r),n))},perm:function(e,t){const n=ws(e,"permutations"),r=ws(t,"permutations");if(r<0n||r>n)throw new cr("undefined");if(r>BigInt(pr.terms)||xs(n,r))throw new hr("too large to calculate");mr(r,Number(r)*yr(n));let s=1n;for(let e=n-r+1n;e<=n;e++)s*=e;return _r(xr(s))},comb:function(e,t){const n=ws(e,"combinations");let r=ws(t,"combinations");if(r<0n||r>n)throw new cr("undefined");if(n-r<r&&(r=n-r),r>BigInt(pr.terms)||xs(n,r))throw new hr("too large to calculate");mr(2n*r,Number(r)*yr(n));let s=1n;for(let e=1n;e<=r;e++)s=s*(n-r+e)/e;return _r(xr(s))},"=":(e,t)=>hs(e,t),"===":(e,t)=>hs(e,t),"≠":(e,t)=>!hs(e,t),"≠=":(e,t)=>!hs(e,t),"≈":(e,t)=>Math.abs(Ur(e)-Ur(t))<=1e-9*Math.max(1,Math.abs(Ur(e)),Math.abs(Ur(t))),"<":(e,t)=>cs(e,t)<0,">":(e,t)=>cs(e,t)>0,"≤":(e,t)=>cs(e,t)<=0,"≥":(e,t)=>cs(e,t)>=0,"&":(e,t)=>Hr(e)&&Hr(t),"|":(e,t)=>Hr(e)||Hr(t),"\\xor":(e,t)=>Hr(e)!==Hr(t),"\\nor":(e,t)=>!(Hr(e)||Hr(t)),"\\nand":(e,t)=>!(Hr(e)&&Hr(t))},Ps={sum:e=>e.reduce((e,t)=>ss(e,t),Tr(0)),prod:e=>e.reduce((e,t)=>as(e,t),Tr(1)),max:e=>e.reduce((e,t)=>cs(t,e)>0?t:e),min:e=>e.reduce((e,t)=>cs(t,e)<0?t:e),mean:e=>ls(Ps.sum(e),Tr(e.length)),gcd:e=>_r(xr(e.map(e=>ws(e,"gcd")).reduce(wr)))},Bs=["∈","∉","∪","∩","pmod","random","(]","[)"];function Ds(e,t){if(++fr>pr.steps)throw new hr("too much to work out");switch(e.type){case"number":return _r(Ir(e.value));case"string":return Pr(e.value.slice(1,-1));case"symbol":return Ws(e.value,t)}const n=te(e);if(n)return Ds(n,t);const{op:r,args:s}=e,i=e=>Ds(e,t);if("?:"===r)return Hr(i(s[0]))?i(s[1]):i(s[2]);if("_"===r){if(s.every(e=>"op"!==e.type))return Ws(`${s[0].value}_${s[1].value}`,t);throw new hr("subscript")}if("der"===r)return function(e,t){const[n,r]=e.args;if("op"===r.type&&"="===r.op){const e=Gs(r.args[0]);if(!e)throw new hr("a derivative at a point names its variable: der(f, x = a)");return Xs(n,e,Ur(Ds(r.args[1],t)),t)}const s=Gs(r);if(!s||!t[Us]?.has(s))throw new hr(`a derivative needs a point: der(f, ${s||"x"} = a)`);return Xs(n,s,Ur(t[s]),t)}(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]=[Gs(r),s,i];else{if(3!==e.length||o(r))throw new hr("an integral needs limits to be calculated");[a,l,u]=[_(n)||"x",r,s]}let c=Ur(Ds(l,t)),h=Ur(Ds(u,t));if(c===h)return Tr(0);let p=1;c>h&&([c,h]=[h,c],p=-1);const f=Hs(n,a,t),{value:d,error:m}=Qs(f,c,h);return ti(p*d,m)}(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]=[Gs(r.args[0]),r.args[1]];else if(2===e.length)[o,a]=[_(n),r];else{if(!(e.length>=3))throw new hr("a limit needs a point");[o,a]=[Gs(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 hr("a limit needs a variable");const u=Ds(a,t),c=Ur(u),h=Hs(n,o,t);let p,f;if(Number.isFinite(c))if(l){({value:p,error:f}=Ys(e=>h(c+l*e*Math.max(1,Math.abs(c)))));try{const e=Ds(n,Vs(t,o,u));if(Math.abs(Ur(e)-p)<=Math.max(f,1e-6*Math.max(1,Math.abs(p))))return e}catch(e){if(!(e instanceof cr))throw e}}else{const e=Ys(e=>h(c+e*Math.max(1,Math.abs(c)))),r=Ys(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 cr("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=Ds(n,Vs(t,o,u));if(Math.abs(Ur(e)-p)<=1e-6*Math.max(1,Math.abs(p)))return e}catch(e){if(!(e instanceof cr))throw e}}else({value:p,error:f}=Ys(e=>h(Math.sign(c)/e)));return Number.isFinite(p)?ti(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 hr("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=_(r)||"n";const l=ws(Ds(a,n),"a sum"),u=Ds(i,n),c=e?ss:as;if(u===1/0){if(!e)throw new hr("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 cr("undefined");s+=t}if(n.push(a),r.push(s),o>=6&&r[r.length-1]===r[r.length-2]&&!ei(e,t,i))return ti(s,0)}if(ei(e,t,i))throw new cr("the series diverges");const o=r[r.length-1]-r[r.length-2],a=r[r.length-2]-r[r.length-3],l=r[r.length-3]-r[r.length-4],u=o/a;if(Math.abs(o)>1e-12&&u>=.999&&a/l>=.999)throw new cr("the series diverges");if(Math.abs(o)>1e-6*Math.max(1,Math.abs(s))&&u>=.9)throw new hr("the series grows too slowly to tell whether it has a sum");const c=n.slice(-7).map(e=>1/e),h=r.slice(-7),p=r.slice(-8,-1),f=(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]},d=f(c,h),m=f(n.slice(-8,-1).map(e=>1/e),p);return ti(d,Math.abs(d-m))}(Hs(r,o,n),Number(l))}const h=ws(u,"a sum");if(h-l+1n>BigInt(pr.terms))throw new hr("too many terms to add one by one");let p=Tr(e?0:1);for(let e=l;e<=h;e++)p=c(p,Ds(r,Vs(n,o,_r(xr(e)))));return p}("\\sumidx"===r,s,t);if(["()","[]","{}"].includes(r))return Rr(s.map(i),r);if("pmatrix"===r||"bmatrix"===r)return Zs(e,i);if("vmatrix"===r)return js.det(Zs(e,i));if("^"===r&&"symbol"===s[1].type&&"T"===s[1].value&&!Object.prototype.hasOwnProperty.call(t,"T")){const e=i(s[0]);if(_s(e))return js.transpose(e)}if("pmod"===r)return function([e,t],n){const r=n(t);return"op"===e.type&&["≡","="].includes(e.op)&&2===e.args.length?Fr(As(os(n(e.args[0]),n(e.args[1])),r)):As(n(e),r)}(s,i);if("∈"===r||"∉"===r){const t=function(e,t){const[n,r]=e.args,s=t(n);let i;if("symbol"===r.type&&["ℤ","ℕ","ℚ","ℝ"].includes(r.value)&&Lr(s))i="ℝ"===r.value||("ℚ"===r.value?Cr(s):Cr(s)&&1n===s.c.d&&("ℤ"===r.value||s.c.n>0n));else if("op"===r.type&&["()","[]","(]","[)"].includes(r.op)&&2===r.args.length){const[e,n]=r.args.map(t),o=cs(s,e),a=cs(s,n);i=("["===r.op[0]?o>=0:o>0)&&("]"===r.op[1]?a<=0:a<0)}else{if("op"!==r.type||"{}"!==r.op)return;i=r.args.some(e=>hs(s,t(e)))}return"∈"===e.op?i:!i}(e,i);if(void 0!==t)return t}if(Bs.includes(r))return function(e,t){const n={};for(const[e,r]of Object.entries(t))"function"!=typeof r&&(n[e]=Xr(r));try{return Gr(function(e,t={}){0===ar&&(or=0),ar++;try{return lr(Pn(e),t)}finally{ar--}}(e,n))}catch(e){throw new hr(e.message)}}(e,t);if(r.startsWith("\\:")){const e=r.slice(2),n=Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;if("function"!=typeof n&&Object.prototype.hasOwnProperty.call(Fs,e))return Fs[e](...s.map(i));if("function"!=typeof n)throw new hr(`no function ${r.slice(2)}`);return Gr(n(...s.map(e=>Xr(i(e)))))}if(Es[r]&&1===s.length)return Es[r](i(s[0]));if(Rs[r]&&2===s.length)return Rs[r](i(s[0]),i(s[1]));if(Ps[r])return Ps[r](s.map(i));throw new hr(`can't calculate '${r}'`)}function Ws(e,t){if(Object.prototype.hasOwnProperty.call(t,e))return t[e];if(Object.prototype.hasOwnProperty.call(Os,e))return Os[e]();if(z(e))return _r(Ir(z(e)));throw new hr(`no value for '${e}'`)}const Us=Symbol("bound"),Vs=(e,t,n)=>({...e,[t]:n,[Us]:new Set([...e[Us]??[],t])});function Hs(e,t,n){return r=>{try{return Ur(Ds(e,Vs(n,t,r)))}catch(e){if(e instanceof cr)return NaN;throw e}}}const Gs=e=>"symbol"===e.type?e.value:null;function Xs(e,t,n,r){const s=Hs(e,t,r);if(!Number.isFinite(s(n)))throw new cr("undefined");const i=1e-6*Math.max(1,Math.abs(n)),o=(s(n+i)-s(n))/i,a=(s(n)-s(n-i))/i;if(!Number.isFinite(o)||!Number.isFinite(a)||Math.abs(o-a)>.001*Math.max(1,Math.abs(o)))throw new cr("not differentiable here");let l=.1*Math.max(1,Math.abs(n));const u=1.4,c=[[(s(n+l)-s(n-l))/(2*l)]];let h=c[0][0],p=1/0;for(let e=1;e<12;e++){l/=u,c[e]=[(s(n+l)-s(n-l))/(2*l)];let t=u*u;for(let n=1;n<=e;n++){c[e][n]=(c[e][n-1]*t-c[e-1][n-1])/(t-1),t*=u*u;const r=Math.max(Math.abs(c[e][n]-c[e][n-1]),Math.abs(c[e][n]-c[e-1][n-1]));r<=p&&(p=r,h=c[e][n])}if(Math.abs(c[e][e]-c[e-1][e-1])>=2*p)break}if(!Number.isFinite(h))throw new cr("not differentiable here");return ti(h,p)}function Qs(e,t,n){if(t===-1/0&&n===1/0){const t=Qs(e,-1/0,0),n=Qs(e,0,1/0);return{value:t.value+n.value,error:t.error+n.error}}return n===1/0?Js(n=>e(t+n/(1-n))/((1-n)*(1-n)),0,1):t===-1/0?Js(t=>e(n-t/(1-t))/((1-t)*(1-t)),0,1):Js(e,t,n)}function Js(e,t,n,r=0){try{return function(e,t,n){const r=(n-t)/2,s=4;let i=1,o=0,a=NaN,l=NaN,u=0;const c=i=>{const o=Math.PI/2*Math.sinh(Math.abs(i)),a=Math.exp(-2*o),l=2*r*a/(1+a),c=r*(Math.PI/2)*Math.cosh(i)*(4*a)/((1+a)*(1+a));if(0===l||0===c)return 0;const h=i>0?n-l:t+l;if(0!==i&&(h<=t||h>=n))return 0;const p=e(0===i?(t+n)/2:h);if(!Number.isFinite(p)){if(l<1e-6*r)return 0;throw new cr("the integral diverges")}return Math.abs(i)>s-.5&&(u=Math.max(u,Math.abs(c*p))),c*p};o=c(0);for(let e=i;e<=s;e+=i)o+=c(e)+c(-e);a=i*o;for(let e=1;e<=8;e++){i/=2;for(let e=i;e<=s;e+=2*i)o+=c(e)+c(-e);l=a,a=i*o;const t=Math.max(1,Math.abs(a));if(u>1e-8*t)throw new cr("the integral diverges");if(e>=3&&Math.abs(a-l)<=1e-13*t)break}const h=Math.abs(a-l);if(!Number.isFinite(a)||h>1e-6*Math.max(1,Math.abs(a)))throw new cr("the integral does not converge");return{value:a,error:h}}(e,t,n)}catch(e){if(!(e instanceof cr)||"the integral does not converge"!==e.message||r>=10)throw e}const s=(t+n)/2,i=Js(e,t,s,r+1),o=Js(e,s,n,r+1);return{value:i.value+o.value,error:i.error+o.error}}function Ys(e){const t=Ks(e),n=Ks(t=>e(.7548776662466927*t));if(t.value===n.value)return t;if(!Number.isFinite(t.value)||!Number.isFinite(n.value))throw new cr("the limit does not exist");const r=Math.max(1,Math.abs(t.value)),s=Math.max(t.error,n.error,1e-6*r);if(s>.001*r)throw new cr("the limit could not be found");if(Math.abs(t.value-n.value)<=s)return t;throw new cr("the limit does not exist")}function Ks(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 cr("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=e=>{const t=n[e+1]-n[e],r=n[e+2]-n[e+1];return r===t?n[e+2]:n[e+2]-r*r/(r-t)},a=e=>(n[e+2]-n[e+1])/(n[e+1]-n[e]),l=e=>[e,e+1].every(e=>a(e)>0&&a(e)<.95)&&Math.abs(a(e)-a(e+1))<.05;for(let e=0;e+3<n.length;e++){if(!l(e))continue;const t=o(e),n=Math.abs(t-o(e+1));Number.isFinite(t)&&(!i||n<i.error)&&(i={value:t,error:n})}const u=n[n.length-1],c=Math.abs(u-n[n.length-2]);if(!i||i.error>Math.max(c,1e-6*Math.max(1,Math.abs(u)))){if(c<=1e-6*Math.max(1,Math.abs(u)))return{value:u,error:10*c};throw new cr("the limit could not be found")}return i}function ei(e,t,n){const r=t=>Math.max(...Array.from({length:8},(n,r)=>Math.abs(e(t+r)))),s=r(n);return s>1e-12&&s>=.5*r(t+Math.floor((n-t)/16))}function ti(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 function(e,t){if(!(t>0)||0===e)return e;const n=Math.floor(-Math.log10(t/Math.abs(e)));return n>=15?e:Number(e.toPrecision(Math.max(1,n)))}(e,t);if(Math.abs(e)<=Math.max(4*t,1e-15))return Tr(0);if(Math.abs(e)<1e-10)return e;const r=[[Tr(1),1e3],[jr,100],[_r(kr,2),100],[zr,100],...[2n,3n,5n,6n,7n].map(e=>[_r(kr,0,0,{n:2,r:e}),100])];for(const[t,s]of r){const r=e/Ur(t),i=ni(r,s);if(i&&Math.abs(Number(i.n)/Number(i.d)-r)*Ur(t)<=n)return Yr(_r(i),t)}return e}function ni(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?xr(BigInt(r),BigInt(i)):null}function ri(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&&hs(e[1],is(e[0])))return`±${si(e[0],t)}`;if(Is.has(e.group)&&se(e))return`${e.group}(${e.map(e=>`[${e.map(e=>ri(e,t)).join(", ")}]`).join(", ")})`;const[n,r]={"()":"()","[]":"[]","{}":"{}"}[e.group]||"{}";return n+e.map(e=>ri(e,t)).join(", ")+r}return"number"==typeof e?ii(e,t):t.decimal||null!==t.places?function(e,t){if(Cr(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=vr(n).toString().padStart(i+1,"0"),o=i?`${s.slice(0,-i)}.${s.slice(-i)}`:s;if(s.length<=t.maxDigits)return(r?"-":"")+oi(o)}}return Cr(e)&&null!==t.places?ri(qs(e,Tr(t.places)),{...t,places:null,decimal:!0}):ii(Ur(e),t)}(e,t):function(e,t){const{c:n}=e,r=vr(n.n);if(r.toString().length>t.maxDigits||n.d.toString().length>t.maxDigits)return function(e,t){if(!Cr(e))return ii(Ur(e),t);if(1n!==e.c.d){const n=Ur(e);if(0!==n&&Number.isFinite(n))return ii(n,t);const r=vr(e.c.n),s=e.c.d,i=t.digits+1-(r.toString().length-s.toString().length),o=(i>=0?r*10n**BigInt(i)/s:r/(s*10n**BigInt(-i))).toString(),a=((BigInt(o.slice(0,t.digits+1))+5n)/10n).toString(),l=o.length-1-i+(a.length>t.digits?1:0),u=oi(`${a[0]}.${a.slice(1,t.digits)}`);return`${e.c.n<0n?"-":""}${u}*10^(${l})`}const n=vr(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=oi(`${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 si=(e,t)=>{const n=ri(e,t);return/^[\d.]+$|^[a-zπ]+$/i.test(n)?n:`(${n})`};function ii(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 Ms(e,t.places);const n=Math.abs(e);if(n>=1e15||n<1e-6){const[n,r]=e.toExponential(t.digits-1).split("e");return`${oi(n)}*10^(${Number(r)})`}return String(Number(e.toPrecision(t.digits)))}const oi=e=>e.includes(".")?e.replace(/\.?0+$/,""):e;function ai(e,t={},n={}){0===gr&&(fr=0);const r="string"==typeof e?Rn(e):E(e),s={};for(const[e,n]of Object.entries(t))s[e]=Gr(n);let i;gr++;try{i=Ds(r,s)}finally{gr--}const o={decimal:!1,places:null,digits:12,maxDigits:50,...n};if(void 0===o.places&&(o.places=null),null!==o.places&&!(Number.isInteger(o.places)&&o.places>=0&&o.places<=pr.places))throw new hr(`places is a whole number from 0 to ${pr.places}`);const a=e=>Array.isArray(e)?e.every(a):"number"!=typeof e;return{value:Xr(i),text:ri(i,o),exact:a(i)}}function li(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}=ai(n,t,r);return e.startsWith('"')||/^\d+(\.\d+)?$/.test(e)?e:`(${e})`}catch(e){if(e instanceof cr)return'"undefined"';if(e instanceof hr)return`(${n})`;throw e}}Cn=li;for(const e of[pr,ps,Os,Es,Rs,Ps])Object.setPrototypeOf(e,null);Object.setPrototypeOf(Fs,null);const ui=e=>"op"===e.type&&o(e.op)&&["vec","hat"].includes(X(e.op)),ci={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",dot:"dot",cross:"cross",vector:"vector",hat:"hat",at:"at",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",matrix:(e,t)=>`the ${e} by ${t} matrix`,row:e=>`row ${e}`,determinantOf:"the determinant 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",endQuantity:"end quantity",endFraction:"end fraction",endRoot:"end root",endExponent:"end exponent",endSub:"end sub",endAbsoluteValue:"end absolute value",endFloor:"end floor",endCeiling:"end ceiling",endLimit:"end limit",endSum:"end sum",endMatrix:"end matrix",endProduct:"end product",endDerivative:"end derivative",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"]},hi={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",det:"the determinant",atan2:"the arctangent",round:"round",fixed:"fixed",random:"random"},pi=Object.fromEntries(Object.entries(T).map(([e,t])=>[t,e]));function fi(e,t={}){return mi(function(e,t={}){return di(e,t,!0)}(e,t))}function di(e,t,n){return function(e){let t=e.length;for(;t>0&&(e[t-1].close||!e[t-1].text.replace(/,/g,"").trim());)t--;const n=[];for(const{text:r,id:s}of e.slice(0,t)){const e=r.trim();if(!e)continue;const t=e.startsWith(","),i=t?e.slice(1).trim():e;t&&n.length&&!n[n.length-1].text.endsWith(",")&&(n[n.length-1].text+=","),i&&n.push({text:i,id:s})}n.length&&(n[n.length-1].text=n[n.length-1].text.replace(/,$/,""));return n}(new bi({...ci,...t.words},{...hi,...t.names},t.say||{},n).speak(e))}function mi(e){return e.map(e=>e.text).join(" ").replace(/\s+/g," ").replace(/ ,/g,",").replace(/,(\s*,)+/g,",").replace(/^,\s*/,"").replace(/,\s*$/,"").trim()}const gi={"=":"equals","===":"equals","≠":"notEqual","≠=":"notEqual","<":"lessThan",">":"greaterThan","≤":"lessOrEqual","≥":"greaterOrEqual","≈":"approx","≡":"congruent","→":"tendsTo","∈":"isIn","∉":"isNotIn","∪":"union","∩":"intersect","±":"plusOrMinus","&":"and","|":"or","\\xor":"xor","\\nand":"nand","\\nor":"nor"},vi={"ℝ":"reals","ℤ":"integers","ℕ":"naturals","ℚ":"rationals","ℂ":"complexes"};class bi{constructor(e,t,n,r=!1){this.w=e,this.names=t,this.say=n,this.audio=r}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=>mi(this.speak(e))):[e.value],e,e=>mi(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(vi[e])return t[vi[e]];if(pi[e])return pi[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,t="endQuantity"){return this.isCompound(e)?[this.seg(e,this.w.quantity),...this.speak(e),...this.closer(e,t)]:this.speak(e)}grouped(e,t,n){return this.isCompound(e)||this.audio&&n?[this.seg(e,this.w.quantity),...this.speak(e),...this.closer(e,t)]:this.speak(e)}closer(e,t){const n=this.seg(e,this.w.comma);return this.audio&&t?[n,{text:this.w[t],id:e.id,close:!0},n]:[n]}contents(e,t){return this.audio&&this.isCompound(e)?this.quantity(e,t):[...this.speak(e),...this.pauseAfter(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.listed(e)]:this.listed(e));if(gi[t])return[...this.speak(r),a(i[gi[t]]),...this.speak(s)];if(o(t)){if(1===n.length&&"symbol"===r.type&&"vec"===X(t))return[a(i.vector),...this.speak(r)];if(1===n.length&&"symbol"===r.type&&"hat"===X(t))return[...this.speak(r),a(i.hat)];const e=this.symbol(X(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 L(s)?[...this.leftSide(r),a(i.minus),...this.quantityIfSum(s.args[1])]:[...this.leftSide(r),a(i.plus),...this.speak(s)];case"-":return L(s)?[...this.leftSide(r),a(i.plus),...this.speak(s.args[1])]:[...this.leftSide(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.audio?this.grouped(s,"endSub","op"===s.type):this.speak(s)];case"neg":return this.isCompound(r)||"op"===r.type&&"neg"===r.op?[a(`${i.negative} ${i.quantity}`),...this.speak(r),...this.closer(r,"endQuantity")]:[a(i.negative),...this.speak(r)];case"pm":return[a(i.plusOrMinus),...this.speak(r)];case"!":return[...this.grouped(r,"endQuantity","op"===r.type||"number"===r.type&&r.value.startsWith("-")),a(i.factorial)];case"\\not":return[a(i.not),...this.quantity(r)];case"sqrt":return[a(i.squareRoot),...this.contents(r,"endRoot")];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):mi(this.speak(r))+"th");return[a(t),...this.contents(s,"endRoot")]}case"abs":return[a(i.absoluteValue),...this.contents(r,"endAbsoluteValue")];case"floor":return[a(i.floor),...this.contents(r,"endFloor")];case"ceil":return[a(i.ceiling),...this.contents(r,"endCeiling")];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:`${mi(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"?:":{const e=[a(i.if),...this.speak(r),a(`${i.comma} ${i.then}`),...this.speak(s)];return(e=>"symbol"===e.type&&"unchanged"===e.value)(n[2])?e:[...e,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"pmatrix":case"bmatrix":return this.matrix(e);case"vmatrix":return[a(i.determinantOf),...this.matrix(e)];case"[]":return re(e)?this.matrix(e):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,"endSum");case"\\prodidx":return this.bigOperator(e,i.productFrom,i.productOver,i.productOf,"endProduct")}throw new Error(`No speech for '${t}'`)}matrix(e){const t=this.w,n=re(e),r=[this.seg(e,t.matrix(n.length,n[0].length))];return n.forEach((n,s)=>{const i=e.args[s];r.push(this.seg(e,t.comma),this.seg("op"===i.type&&"[]"===i.op?i:e,`${t.row(s+1)}:`)),n.forEach((n,s)=>r.push(...s?[this.seg(e,t.comma)]:[],...this.speak(n)))}),[...r,...this.closer(e,"endMatrix")]}arguments(e){return 1===e.length?this.argument(e[0]):e.flatMap((e,t)=>t?[{text:this.w.comma,id:e.id},...this.listed(e)]:this.listed(e))}listed(e){return this.audio?this.quantity(e):this.speak(e)}pauseAfter(e){return this.isCompound(e)?[this.seg(e,this.w.comma)]:[]}leftSide(e){return this.audio&&"op"===e.type&&"?:"===e.op?[this.seg(e,this.w.quantity),...this.speak(e),...this.closer(e,"endQuantity")]:this.speak(e)}quantityIfSum(e){return this.quantity(e)}product(e){const[t,n]=e.args,r=this.w;if(L(e))return this.speak({...e,op:"neg",args:[n]});if("symbol"===n.type&&"°"===n.value)return[...this.speak(t),this.seg(e,r.degrees)];const s=this.audio&&"op"===t.type&&"/"===t.op&&!t.args.every(e=>"number"===e.type&&/^\d$|^10$/.test(e.value))?[this.seg(t,r.quantity),...this.speak(t),...this.closer(t,"endFraction")]:this.quantity(t);this.audio&&"op"===t.type&&"^"===t.op&&"number"!==t.args[1].type&&s.push(...this.closer(t.args[1],"endExponent"));const i=this.quantity(n);if(e.written&&[t,n].some(ui))return[...s,this.seg(e,r[e.written]),...i];return Boolean(e.written)||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)&&!T[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}`)]}const i=(e,...t)=>"op"===e.type&&t.includes(e.op)&&!L(e);return[...this.grouped(t,null,i(t,"/")),...this.isCall(t)?[s(r.comma)]:[],s(r.over),...this.grouped(n,"endFraction",i(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||this.audio&&"op"===t.type&&("^"===t.op||"neg"===t.op||L(t))?[s(r.quantity),...this.speak(t),...this.closer(t,"endQuantity")]: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))}`)];if(!(this.isCompound(n)||"op"===n.type&&"/"===n.op&&this.isCompound(n.args[0]))){const e=this.speak(n),t=e[0]&&e[0].text.startsWith(r.quantity);return[...i,s(t?r.toThePowerOf:r.toThe),...e]}return this.audio?[...i,s(r.toThePowerOf),s(r.quantity),...this.speak(n),...this.closer(n,"endExponent")]:[...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,at:s,variable:i}=Q(e),o=this.w,a=t=>this.seg(e,t),l=s?[a(`${o.comma} ${o.at}`),...this.speak(r),a(o.equals),...this.speak(s)]:[];if(i){return[...[a(1===t?o.d:`${o.d} ${2===t?o.squared:3===t?o.cubed:`${o.toThe} ${this.ordinal(t)}`}`),...this.speak(n),a(o.d),...this.speak(r),a(1===t?"":2===t?o.squared:3===t?o.cubed:`${o.toThe} ${this.ordinal(t)}`)],...l]}return[a(`${1===t?o.derivative:2===t?o.secondDerivative:o.nthDerivative(this.ordinal(t))} ${o.withRespectTo}`),...this.speak(r),a(o.of),...this.contents(n,"endDerivative"),...l]}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(_(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=_(n);l=e?[a(e),a(o.approaches),...this.speak(r)]:this.speak(r)}}return this.audio&&"op"===n.type&&"/"===n.op?[a(o.limitAs),...l,a(o.of),...this.grouped(n,"endLimit",!0)]:[a(o.limitAs),...l,a(o.of),...this.contents(n,"endLimit")]}bigOperator(e,t,n,r,s){const{args:i}=e,[o,a,l]=i,u=this.w,c=t=>this.seg(e,t);let h;return h=3===i.length?[c(t),...this.speak(a),c(u.to),...this.speak(l),c(u.of)]:2===i.length?[c(n),...this.speak(a),c(u.of)]:[c(r)],[...h,...this.contents(o,s)]}}for(const e of[ci,hi,gi,vi,pi])Object.setPrototypeOf(e,null);function yi(e,t={}){return Bn(e)?[]:function(e,t={}){return di(e,t,!1)}(Pn(e),t)}function wi(e,t={}){return Bn(e)?"":fi(Pn(e),t)}const xi={"(":{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"},cancel:{stroke:"M0,1 L1,0"},int:{stroke:"M0.95,0.09 C0.9,0.01 0.72,0 0.66,0.12 C0.6,0.25 0.42,0.75 0.34,0.88 C0.28,0.99 0.1,0.99 0.05,0.91"},sum:{fill:"M0.04,0 L0.94,0 L0.98,0.24 L0.94,0.24 C0.9,0.1 0.8,0.07 0.62,0.07 L0.24,0.07 L0.58,0.5 L0.2,0.93 L0.64,0.93 C0.82,0.93 0.92,0.9 0.95,0.76 L0.99,0.76 L0.94,1 L0.02,1 L0.47,0.47 Z"},prod:{fill:"M0,0 L1,0 L1,0.04 L0.88,0.05 L0.88,0.95 L1,0.96 L1,1 L0.62,1 L0.62,0.96 L0.74,0.95 L0.74,0.06 L0.26,0.06 L0.26,0.95 L0.38,0.96 L0.38,1 L0,1 L0,0.96 L0.12,0.95 L0.12,0.05 L0,0.04 Z"}};function $i(e,t,n=""){const r=xi[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 ki=.8,qi=.2,Mi=.25,Ai=.7,Ni="−",Si={"+":"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",pmatrix:"matrix",bmatrix:"matrix",vmatrix:"matrix"},Oi={"=":"=","===":"=","≠":"≠","≠=":"≠","<":"<",">":">","≤":"≤","≥":"≥","∈":"∈","∉":"∉","→":"→","≈":"≈","≡":"≡","&":"∧","|":"∨","\\xor":"⊕","\\nand":"↑","\\nor":"↓"},Ei={"±":"±","∪":"∪","∩":"∩",mod:"mod"},Ii=["sin","cos","tan","csc","sec","cot","sinh","cosh","tanh"],_i={arcsin:"sin",arccos:"cos",arctan:"tan",arcsinh:"sinh",arccosh:"cosh",arctanh:"tanh"},Ti=[...Ii,...Object.keys(_i),"ln","det"],ji={atan2:"atan2",max:"max",min:"min",gcd:"gcd",mean:"mean",round:"round",fixed:"fixed",expm1:"expm1",random:"random"},zi={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]},Li=["int","lim","\\sumidx","\\prodidx"],Ci={"\\partial":"∂","\\nabla":"∇","\\ell":"ℓ","\\infty":"∞","\\emptyset":"∅"},Fi={vec:"→",hat:"ˆ",widehat:"ˆ",tilde:"˜",dot:"˙",ddot:"¨"},Zi=/^[acegmnopqrsuvwxyzαγεημνοπρστυχω]$/,Ri=e=>"symbol"===e?.type&&Zi.test(T[e.value]??e.value),Pi=["boxed","overline","bar","underline","cancel",...Object.keys(Fi)],Bi={prefix:"mv",display:!0,fnParens:"auto",trigPowers:!0,inverseTrig:"arc",derivativeBrackets:"[",scriptFractions:"slash",cases:!0,label:!0,mathml:null,attributes:null,style:null},Di=e=>String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),Wi=e=>+e.toFixed(3)+"em",Ui=(e,t=ki,n=qi)=>({html:e,h:t,d:n});function Vi(...e){const t=e.flat().filter(Boolean);return{html:t.map(e=>e.html).join(""),h:Math.max(ki,...t.map(e=>e.h)),d:Math.max(qi,...t.map(e=>e.d))}}function Hi(e,t={}){const n=new Gi({...Bi,...t}),r=n.render(e,{level:0}),s=`${n.p}${n.o.display?` ${n.p}-display`:""}`,i="function"==typeof n.o.mathml?function(e,t,n,r){try{return String(e(t)).replace(/ id="mz-\d+"/g,"").replace(/^<math>/,`<math class="${n}-sr-math"${r?' display="block"':""}>`)}catch{return""}}(n.o.mathml,e,n.p,n.o.display):"",o=i?null:function(e,t){if(!1===t||null===t)return null;if("string"==typeof t)return t;try{return"function"==typeof t?t(e):wi(e)}catch{return null}}(e,n.o.label),a=null!==o||i?r.html.replace(/^<span /,'<span aria-hidden="true" '):r.html;return{html:`<span class="${s}"${null===o?"":` role="math" aria-label="${Di(o)}"`}>${a}${i}</span>`,h:r.h,d:r.d}}class Gi{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=Ui(this.el(e,Di(t)));return n.leaf={kind:e,content:Di(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="${Di(e.op)}"`);const s=this.o.attributes&&this.o.attributes(e)||{};for(const[e,t]of Object.entries(s))"class"!==e&&"style"!==e&&/^[A-Za-z_:][\w:.-]*$/.test(e)&&(r+=` ${e}="${Di(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?[Di(s.class)]:[]).join(" "),a=n.leaf?n.leaf.content:n.html;return{html:`<span class="${o}"${i?` style="${Di(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(/^-/,Ni)))}symbol(e){return T[e]&&(e=T[e]),Ci[e]?this.text("ord",Ci[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)?Ui(this.el("var",Di(e[0]))+this.el("prime",Di(e.slice(1)))):/^Δ[A-Za-z]$/.test(e)?Ui(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,leftFactor:!1}),l=Si[n]??(/^[a-z0-9]+$/i.test(n)?n:"other"),c=t=>this.wrap(e,["op",`op-${l}`],t),h=(t,n)=>Z(e,t,n)&&"/"!==t.op?this.fence(a(t)):a(t);if(Ti.includes(n)||"log"===n)return c(this.named(e,t));if(ji[n])return c(Vi(this.word(ji[n]),this.fence(this.list(r,t))));if(o(n))return c(this.custom(e,t));const p=re(e);if(p)return c(this.matrix(e,p,t));if(zi[n])return c(this.fence(this.list(r,t),...zi[n]));if(("|"===n||"&"===n)&&r.length>=2&&r.every(Ji)){const e=e=>"|"!==e.op&&"&"!==e.op||e.op===n?a(e):this.fence(a(e));return c(Vi(r.map((t,r)=>r?[this.text("conj","|"===n?"or":"and"),e(t)]:[e(t)]).flat()))}if(Oi[n]&&2===r.length)return c(Vi(h(s,"left"),this.rel(Oi[n]),h(i,"right")));if(Ei[n]&&2===r.length)return c(Vi(h(s,"left"),this.bin(Ei[n]),h(i,"right")));switch(n){case"+":if(L(i)){const e=i.args[1],t=Z({op:"-"},e,"right")?this.fence(a(e)):a(e);return c(Vi(h(s,"left"),this.bin(Ni),this.wrap(i,["op","op-mul"],t)))}return"number"===i.type&&i.value.startsWith("-")?c(Vi(h(s,"left"),this.bin(Ni),this.wrap(i,["number"],this.text("num",i.value.slice(1))))):c(Vi(h(s,"left"),this.bin("+"),this.signed(i,h(i,"right"))));case"-":return c(Vi(h(s,"left"),this.bin(Ni),this.signed(i,h(i,"right"))));case"*":return c(this.product(e,t));case"/":return c(this.fraction(e,t));case"^":return c(this.power(e,t));case"_":{const e=C(s)&&u(C(s))<100;return c(this.script(e?this.fence(a(s)):a(s,{forceParens:!0}),null,t,a(i,{level:t.level+1})))}case"neg":return c(Vi(this.text("sign",Ni),R(n,s)?this.fence(a(s)):a(s,{before:t.before})));case"pm":return c(Vi(this.text("sign","±"),R(n,s)?this.fence(a(s)):a(s)));case"!":return c(Vi(R(n,s)?this.fence(a(s)):a(s,{forceParens:!0}),this.text("ord","!")));case"\\not":return c(Vi(this.text("sign","¬"),R(n,s)?this.fence(a(s)):a(s)));case"pmod":return c(Vi(a(s),this.fence(Vi(this.word("mod"),this.text("space",""),a(i)))));case"sqrt":return c(this.radical(a(s)));case"root":return c(this.radical(a(i),this.render(s,{level:t.level+2})));case"abs":return c(this.fence(a(s),"|","|"));case"floor":return c(this.fence(a(s),"⌊","⌋"));case"ceil":return c(this.fence(a(s),"⌈","⌉"));case"loglog":return c(Vi(this.word("ln"),this.fence(Vi(this.word("ln"),this.fence(a(s))))));case"logloglog":return c(Vi(this.word("ln"),this.fence(Vi(this.word("ln"),this.fence(Vi(this.word("ln"),this.fence(a(s))))))));case"perm":return c(this.script(this.script(Ui(""),this.render(s,{level:t.level+1}),t),null,t,this.render(i,{level:t.level+1}),this.word("P")));case"comb":return c(this.fence(this.stack(a(s),a(i),!1)));case"?:":return c(this.o.cases?this.cases(e,t):Vi(a(s),this.bin("?"),a(i),this.bin(":"),a(r[2])));case"sum":case"prod":{const e={op:"sum"===n?"+":"*"},t=(t,n)=>Z(e,t,n?"right":"left")?this.fence(a(t)):a(t);return c(Vi(r.map((e,r)=>r?[this.bin("sum"===n?"+":"·"),t(e,r)]:[t(e,r)]).flat()))}case"der":return c(this.derivative(e,t));case"int":return c(this.integral(r,t));case"lim":return c(this.limit(r,t));case"\\sumidx":return c(this.bigOperator("sum",r,t));case"\\prodidx":return c(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 Vi(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(L(e))return Vi(this.text("sign",Ni),R("neg",r)?this.fence(this.render(r,t)):this.render(r,t));const s=function(e){const[t,n]=e.args;return{left:Z(e,t,"left")&&"/"!==t.op,right:Z(e,n,"right")&&"/"!==n.op}}(e);Li.includes(n.op)&&(s.left=!0);const i=!e.written&&P(n,r,s),a=function(e){for(;"op"===e.type;){if(Ti.includes(e.op)||"log"===e.op||ji[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,leftFactor:!0}),u=s.right?this.fence(this.render(r,t)):this.render(r,{...t,before:t.before});return Vi(l,i?Ui(this.el(a?"fnspace":"times","")):this.bin("cross"===e.written?"×":"·"),u)}named(e,t,n=null){const{op:r,args:s}=e,i="log"===r?s[1]:s[0];let o;o=_i[r]&&"power"===this.o.inverseTrig?this.script(this.word(_i[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&&Xi(i),l=this.render(i,{...t,forceParens:!1,before:!1});return Vi(o,a?Vi(Ui(this.el("fnspace","")),l):this.fence(l))}custom(e,t){const n=X(e.op),r=e.args;if(Pi.includes(n)&&1===r.length)return this.decorate(n,this.render(r[0],t),r[0]);return Vi(/^[A-Za-z]′*(⁻¹)?$/.test(n)?this.symbol(n):this.word(n),Ui(this.el("callgap","")),this.fence(this.list(r,t)))}decorate(e,t,n){switch(e){case"boxed":return Ui(this.el("boxed",t.html),t.h+.22,t.d+.22);case"cancel":return Ui(this.el("cancel",t.html+$i("cancel",`${this.p}-cancel-line`)),t.h,t.d);case"underline":return Ui(this.el("underline",t.html),t.h,t.d+.12);case"overline":case"bar":return Ui(this.el("over"+(Ri(n)?" over-low":""),t.html),t.h+.14,t.d);default:{const r=Ri(n);return Ui(this.el("accent"+(r?" accent-low":""),this.el(`accent-mark accent-${e}`,Fi[e])+t.html),t.h+.3,t.d)}}}fraction(e,t){const[n,r]=e.args;if(t.level>0&&"slash"===this.o.scriptFractions&&Xi(n,!0)&&Xi(r,!0)){const e={...t,leftFactor:!1},s=(t,n)=>"op"!==t.type||Xi(t)&&(!n||"*"!==t.op||L(t))?this.render(t,e):this.fence(this.render(t,e)),i=Vi("op"===n.type&&"neg"===n.op?this.render(n,e):s(n,!1),this.text("ord","/"),s(r,!0));return t.leftFactor?this.fence(i):i}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:${Wi(r)}`),i=n?.06:0,o=Mi+i/2+.1+Math.max(qi,r*e.d),a=this.el("frac"+(n?"":" frac-nobar"),this.el("numer",s(e))+this.el("denom",s(t)),`vertical-align:${Wi(o)}`);return Ui(a,o+Math.max(ki,r*e.h),Math.max(ki,r*t.h)+Math.max(qi,r*t.d)+.1+i/2-Mi)}power(e,t){const[n,r]=e.args,s={...t,level:t.level+1,forceParens:!1,before:!1,inFraction:!1,leftFactor:!1},i=()=>this.render(r,s);if(this.o.trigPowers&&Ii.includes(n.op)&&Ki(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=Z(e,n,"left")||"number"===n.type&&n.value.startsWith("-")||"/"===n.op||Ti.includes(n.op)||Li.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:Ai,o=s?Vi(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:${Wi(i)}`);if(t&&!r)return Ui(e.html+this.el("sup",t.html,`font-size:${Wi(i)};vertical-align:${Wi(a/i)}`),Math.max(o.h,a+i*t.h),Math.max(o.d,i*t.d-a));if(r&&!t)return Ui(o.html+this.el("sub",r.html,`font-size:${Wi(i)};vertical-align:${Wi(-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:${Wi(a)};height:${Wi(c+h)}`);return Ui(o.html+p,Math.max(o.h,c),Math.max(o.d,h))}radical(e,t=null){const n=Math.max(e.h,ki)+.1+.06,r=Math.max(e.d,qi),s=n+r,i=$i("sqrt",`${this.p}-hook`,`height:${Wi(s)};width:${Wi(.5+.06*(s-1))};vertical-align:${Wi(-r)}`);let o="";if(t){const e=.8*Ai;o=this.el("rootindex",t.html,`font-size:${Wi(e)};vertical-align:${Wi((.55*s-r)/e)}`)}return Ui(this.el("sqrt",o+i+this.el("radicand",e.html)),n,r)}fence(e,t="(",n=")"){const r=Math.max(e.h,ki)+Math.max(e.d,qi),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:$i(e,`${this.p}-delim ${this.p}-delim-${t}`,`width:${Wi(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:${Wi(i)} ${Wi(l.w)} ${Wi(i)} ${Wi(a.w)}`,c=Ui(this.el("fence",a.html+e.html+l.html,u),Math.max(e.h,ki)+i,Math.max(e.d,qi)+i);return c.fenced=!0,c}derivative(e,t){const n=this.leibniz(e,t),{by:r,at:s}=Q(e);if(!s)return n;const i=e.args[1],o=this.render({...i,args:[{...r,id:void 0},s]},{...t,level:t.level+1});return this.script(this.fence(n,"","|"),null,t,o)}leibniz(e,t){const{n:n,body:r,by:s,variable:i}=Q(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=Vi(a(),l()?this.script(this.render(s,c),l(),c):this.render(s,c)),p=e=>Vi(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 d=C(r)&&u(C(r))<100,[m,g]="("===this.o.derivativeBrackets?["(",")"]:["[","]"],v=d?this.fence(this.render(r,t),m,g):this.render(r,t);return Vi(this.stack(p(),h,!0,f),v)}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",_(n)||"x");let u,c=null,h=null;switch(e.length){case 1:u=l();break;case 2:G(r)?u=o(r):(u=l(),c=a(r));break;case 3:G(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=Ui(this.el("dx",this.el("d","d")+u.html),u.h,u.d);return Vi(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-Mi,t.d+Mi)+.12),a=$i(e,`${this.p}-bigsign ${this.p}-${e}sign`,`height:${Wi(2*o)};width:${Wi(i?.38:.5)};vertical-align:${Wi(Mi-o)}`);if(!n&&!r)return Ui(a,Mi+o,o-Mi);const l=Ai,u=r||Ui(""),c=n||Ui(""),h=Mi+o-l*u.h;c.d;const p=this.el("limits",this.el("script",u.html,`font-size:${Wi(l)}`)+this.el("script lower",c.html,`font-size:${Wi(l)}`),`vertical-align:${Wi(h)};height:${Wi(2*o)}`);return Ui(a+p,Mi+o,o-Mi)}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 Vi(this.word("lim"),Ui(this.el("fnspace","")),this.body(n,t));case 2:{const e=_(n),t="number"===r.type||"symbol"===r.type&&r.value.includes("∞");u=e&&t?Vi(this.text("var",e),l(),a(r)):a(r);break}case 3:u=Vi(a(r),l(),a(s));break;default:{const e=j(i).toLowerCase().startsWith("r")?"+":Ni;u=Vi(a(r),l(),this.script(a(s),this.wrap(i,["symbol"],this.text("ord",e)),o))}}return Vi(this.under(this.word("lim"),u,t),this.body(n,t))}under(e,t,n){return!this.o.display||n.level>0?this.script(e,null,n,t):Ui(this.el("under",e.html+this.el("script",t.html,`font-size:${Wi(.7)}`)),e.h,Math.max(e.d,qi)+.05+.7*(t.h+t.d))}body(e,t){const n=C(e);return n&&u(n)<u("*")?this.fence(this.render(e,t)):this.render(e,t)}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.body(r,n);if(!this.o.display||n.level>0){const t=.55,r=$i(e,`${this.p}-bigsign`,`height:${Wi(2*t)};width:${Wi(.8)};vertical-align:${Wi(Mi-t)}`);return Vi(this.script(Ui(r,Mi+t,t-Mi),l,n,a),u)}const c=.68,h=Ai,p=$i(e,`${this.p}-bigsign`,`height:${Wi(1.36)};width:${Wi("sum"===e?1:1.05)}`),f=l?1.01+h*l.d:Mi-c,d=e=>this.el("script",e.html,`font-size:${Wi(h)}`),m=this.el("bigop",(l?d(l):"")+p+(a?d(a):""),`vertical-align:${Wi(f)}`);return Vi(Ui(m,.93+(l?.08+h*(l.h+l.d):0),c-Mi+(a?.08+h*(a.h+a.d):0)),u)}matrix(e,t,n){const r=t.map(e=>e.map(e=>this.render(e,n))),s=r.map(e=>({h:Math.max(ki,...e.map(e=>e.h)),d:Math.max(qi,...e.map(e=>e.d))})),i=s.reduce((e,t)=>e+t.h+t.d,0)+.3*(t.length-1),o=Mi+i/2-s[0].h,a=r.map((t,n)=>{const r=t.map(e=>this.el("matrix-cell",e.html)).join(""),s=e.args[n];return s&&"op"===s.type&&"[]"===s.op?this.wrap(s,["op","op-list","matrix-row"],Ui(r)).html:r}).join(""),l=t[0].length,u=Ui(this.el("matrix",a,`grid-template-columns:repeat(${l},auto);vertical-align:${Wi(o)}`),Mi+i/2,i/2-Mi),[c,h]=ne[e.op]??["[","]"];return this.fence(u,c,h)}cases(e,t){const n=[];let r=e;for(;"op"===r.type&&"?:"===r.op;)n.push([this.render(r.args[1],t),Vi(this.word("if"),this.text("space",""),this.render(r.args[0],t))]),r=r.args[2];"symbol"===r.type&&"unchanged"===r.value||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=Mi+i/2-s[0].h,a=n.map(([e,t])=>this.el("case-value",e.html)+this.el("case-cond",t.html)).join(""),l=Ui(this.el("cases",a,`vertical-align:${Wi(o)}`),Mi+i/2,i/2-Mi);return this.fence(l,"{","")}}function Xi(e,t=!1){return"number"===e.type?!e.value.startsWith("-")||t:"symbol"===e.type||"op"===e.type&&("abs"===e.op||re(e)?!t:!t||"neg"!==e.op&&"^"!==e.op?"*"===e.op&&!L(e)&&e.args.every(e=>"number"===e.type&&!e.value.startsWith("-")||Yi(e)||"*"===e.op&&Xi(e,t)):Xi(e.args[0],!0)&&("neg"===e.op||Xi(e.args[1],!0)))}const Qi=["=","===","≠","≠=","<",">","≤","≥","≈","≡","∈","∉"],Ji=e=>"op"===e.type&&e.args.length>=2&&(2===e.args.length&&Qi.includes(e.op)||("|"===e.op||"&"===e.op)&&e.args.every(Ji)),Yi=e=>"symbol"===e.type&&(1===e.value.length||/^[α-ωΑ-Ω]$/.test(e.value)||Boolean(T[e.value])),Ki=e=>"number"===e.type&&/^[1-9]\d*$/.test(e.value)&&Number(e.value)<10;for(const e of[Si,Oi,Ei,_i,ji,zi,Ci,Fi])Object.setPrototypeOf(e,null);function eo(e){const{id:t,from:n,...r}=e;return r.args&&(r.args=r.args.map(eo)),r}const to=e=>O(e).join(" ");function no(e,t){const n=new Set;ro(e,t,n);const r=[];return I(e,e=>{n.has(e)&&r.push(e)}),r}function ro(e,t,n){if(null!=t)if(Array.isArray(t))t.forEach(t=>ro(e,t,n));else if("number"!=typeof t)if("function"!=typeof t){if("string"==typeof t){const r=to(Rn(t));return void I(e,e=>{to(e)===r&&n.add(e)})}if(t.path){const r=so(e,t.path);return void(r&&n.add(r))}if(t.type){const r=to(t);I(e,e=>{e!==t&&to(e)!==r||n.add(e)})}}else I(e,(e,r)=>{t(e,r)&&n.add(e)});else I(e,e=>{e.id===t&&n.add(e)})}function so(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 io(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 oo(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 ao(e,t={}){const{blocks:n}=t;if("string"==typeof e)return Rn(e,n?{blocks:e=>n(e,t.scope)}:{});if(Array.isArray(e))return S(e);if(e&&"object"==typeof e&&e.type){if(void 0!==e.id)return e;const t=structuredClone(e);return I(t,e=>{"op"!==e.type&&void 0!==e.value&&(e.value=String(e.value))}),oo(t)}throw new Error("Inline Math needs an expression, standard postfix or a tree")}function lo(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(uo(r))for(const n of no(e,t))a.set(n,`color:${r}`);const l=new Set(void 0===r?[]:no(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 uo(e){return"string"==typeof e&&/^[#\w\s.,%()/+-]+$/.test(e)&&!/url\s*\(|expression/i.test(e)}function co(e,t={}){return ao(e,{...t,blocks:t.blocks??li})}function ho(e,t={}){return function(e,t={}){const n=ao(e,t);return Hi(n,lo(n,t)).html}(e,{...t,blocks:t.blocks??li})}function po(e,t,n){const r=(e,s)=>s===t.length?n:{...e,args:e.args.map((e,n)=>n===t[s]?r(e,s+1):e)};return eo(r(e,0))}function fo(e,t,{parse:n,commit:r,cancel:s,label:i="Edit",prefix:o="mv"}){const a=e.ownerDocument;if(!a||!a.body)return null;const l=a.defaultView,u=e.getBoundingClientRect(),c=a.createElement("input");c.type="text",c.className=`${o}-edit`,c.value=t,c.spellcheck=!1,c.autocomplete="off",c.setAttribute("aria-label",i);const h=()=>{c.style.width=`${Math.max(4,c.value.length+2)}ch`},p=l.getComputedStyle(e);Object.assign(c.style,{position:"absolute",left:`${u.left+l.scrollX}px`,top:`${u.top+l.scrollY+u.height/2}px`,minWidth:`${Math.max(u.width,32)}px`,fontSize:p.fontSize}),h(),a.body.appendChild(c),l.getSelection?.()?.removeAllRanges(),c.focus(),c.select();let f=!1;const d=()=>{f=!0,c.remove()};c.cancelEdit=()=>{f||(d(),s&&s())};const m=e=>{if(f)return!0;if(!e||c.value===t)return d(),s&&s(),!0;let i;try{i=n(c.value)}catch(e){return c.setAttribute("aria-invalid","true"),c.title=e.message,!1}return d(),r(i,c.value),!0};return c.addEventListener("keydown",e=>{e.stopPropagation(),"Enter"===e.key&&(e.preventDefault(),m(!0)),"Escape"===e.key&&(e.preventDefault(),m(!1))}),c.addEventListener("input",()=>{h(),c.removeAttribute("aria-invalid"),c.removeAttribute("title")}),c.addEventListener("blur",()=>{m(!0)||m(!1)}),c}class mo{constructor(e,t,n={}){this.element=e,this.options=n,this.p=n.prefix||"mv",this.handlers=[],this.clicks=[],this.active=null,this.live=go(e,n.announce,this.p),this.set(t)}set(e,{animate:t=!1,duration:n=600,easing:r="ease-in-out"}={}){const s=co(e,this.options),{html:i}=Hi(s,lo(s,this.options));if(this.editor){const e=this.editor;this.editor=null,e.cancelEdit?.()}const o=vo(t)&&this.tree?this.snapshot():null,a=void 0!==this.tree;return this.tree=s,this.element.innerHTML=i,this.root=this.element.firstElementChild,this.handlers.length&&this.root.classList.add(`${this.p}-clickable`),this.editing&&this.root.classList.add(`${this.p}-editable`),this.active=null,(this.clicks.length||this.editing)&&this.focusable(),o&&this.morph(o,{duration:n,easing:r}),a&&this.live&&this.announce(this.spoken()),this}spoken(){const e=this.root&&this.root.getAttribute&&this.root.getAttribute("aria-label");if(e)return e;try{return wi(this.tree)}catch{return""}}announce(e){return this.say(this.live,e)}say(e,t){if(!e)return this;e.textContent="";const n=()=>{e.textContent=t};return"function"==typeof requestAnimationFrame?requestAnimationFrame(()=>requestAnimationFrame(n)):setTimeout(n,50),this}nodes(e){return no(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=no(this.tree,r)[0];t({node:s,id:r,path:io(this.tree,r),element:n,event:e})};this.element.addEventListener(e,n);const r=[e,n];return this.handlers.push(r),this.root.classList.add(`${this.p}-clickable`),"click"===e&&(this.clicks.push(t),this.keyboard()),()=>{this.element.removeEventListener(e,n),this.clicks=this.clicks.filter(e=>e!==t),this.handlers=this.handlers.filter(e=>e!==r),!this.handlers.length&&this.root&&this.root.classList.remove(`${this.p}-clickable`)}}destroy(){if(this.editor){const e=this.editor;this.editor=null,e.cancelEdit?.()}for(const[e,t]of this.handlers)this.element.removeEventListener(e,t);this.handlers=[],this.clicks=[],this.keyListener&&this.element.removeEventListener("keydown",this.keyListener),this.editListener&&this.element.removeEventListener("dblclick",this.editListener),this.keyListener=this.editListener=null,this.keysOn=this.editOn=!1;for(const e of new Set([this.live,this.partsLive]))e&&"view"===e.dataset?.mvMadeBy&&e.remove();return this.live=this.partsLive=null,this}editable({toText:e,onEdit:t}={}){if("function"!=typeof e)throw new Error("editable needs { toText } (import { toText } from 'mathzetta/text')");return this.editing={toText:e,onEdit:t},this.root&&this.root.classList&&this.root.classList.add(`${this.p}-editable`),this.keyboard(),!this.editOn&&this.element.addEventListener&&(this.editOn=!0,this.editListener=e=>{const t=e.target.closest?.("[data-node]");t&&this.root.contains(t)&&(e.preventDefault(),this.edit(no(this.tree,Number(t.dataset.node))[0]))},this.element.addEventListener("dblclick",this.editListener)),this}edit(e=this.tree,{returnFocus:t=!1}={}){if(!this.editing)throw new Error("call editable({ toText }) first");const n="object"==typeof e&&e&&e.type?e:this.nodes(e)[0];if(!n)return null;const r=io(this.tree,n.id)||[],s=this.elementOf(n)||this.root;let i="Edit";try{i=`Edit ${wi(n)}`}catch{}const o=()=>{t&&this.root.focus&&this.root.focus()};return this.editor=fo(s,this.editing.toText(n),{label:i,prefix:this.p,parse:e=>co(e,this.options),commit:(e,n)=>{this.set(po(this.tree,r,e),{animate:!0});const s=so(this.tree,r);t&&s&&this.focusPart(s===this.tree?null:s),o(),this.editing.onEdit&&this.editing.onEdit({tree:this.tree,text:this.editing.toText(this.tree),path:r,part:n})},cancel:o}),this.editor}focusable(){this.root&&this.root.setAttribute&&(this.root.setAttribute("tabindex","0"),this.root.getAttribute("aria-label")||(this.root.setAttribute("role","math"),this.root.setAttribute("aria-label",this.spoken())),this.root.setAttribute("aria-description",this.editing?"Arrow keys move between parts, F2 edits one.":"Arrow keys move between parts, Enter selects one."))}keyboard(){this.focusable(),!this.keysOn&&this.element.addEventListener&&(this.keysOn=!0,this.partsLive=this.live||go(this.element,!0,this.p),this.keyListener=e=>this.key(e),this.element.addEventListener("keydown",this.keyListener))}key(e){if(!this.root||!this.root.contains(e.target))return;const t=this.active;let n;switch(e.key){case"ArrowDown":n=t?this.partsOf(t)[0]:this.partsOf(this.tree)[0];break;case"ArrowUp":n=t?this.outerOf(t):void 0;break;case"ArrowRight":n=t?this.neighbor(t,1):this.partsOf(this.tree)[0];break;case"ArrowLeft":n=t?this.neighbor(t,-1):void 0;break;case"Home":case"Escape":n=null;break;case"F2":if(!this.editing)return;return e.preventDefault(),void this.edit(t||this.tree,{returnFocus:!0});case"Enter":case" ":{e.preventDefault();const n=t||this.tree,r=this.elementOf(n)||this.root,s={node:n,id:n.id,path:io(this.tree,n.id),element:r,event:e};for(const e of this.clicks)e(s);return}default:return}e.preventDefault(),void 0!==n&&this.focusPart(n)}focusPart(e){const t=`${this.p}-focus`;this.root.querySelectorAll(`.${t}`).forEach(e=>e.classList.remove(t)),this.active=e;const n=e&&this.elementOf(e);n&&n.classList.add(t);let r="";try{r=e?wi(e):this.spoken()}catch{r=""}return this.say(this.partsLive,r),this}partsOf(e){const t=[],n=e=>{this.elementOf(e)?t.push(e):"op"===e.type&&e.args.forEach(n)};return e&&"op"===e.type&&e.args.forEach(n),t}outerOf(e){const t=io(this.tree,e.id);for(let e=t?t.length-1:-1;e>0;e--){const n=so(this.tree,t.slice(0,e));if(n&&this.elementOf(n))return n}return null}neighbor(e,t){const n=this.partsOf(this.outerOf(e)||this.tree),r=n.indexOf(e);return r<0?void 0:n[r+t]}segments(e={}){return yi(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=to(n);e.has(t)||e.set(t,[]),e.get(t).push({rect:r.getBoundingClientRect(),node:n,sig:t})}"op"===n.type&&n.args.forEach(t)};return t(this.tree),e}morph(e,{duration:t,easing:n}){if("undefined"==typeof Element||!Element.prototype.animate)return;const r=t=>{if("op"===t.type)for(const n of t.args){const t=e.get(to(n)),s=t?t.findIndex(e=>e.node===n):-1;s>-1&&t.splice(s,1),r(n)}},s=i=>{const o=this.elementOf(i),a=o&&e.get(to(i));if(a&&a.length){const{rect:e,node:s}=a.shift();r(s);const i=o.getBoundingClientRect(),l=e.left-i.left,u=e.top-i.top,c=i.width?e.width/i.width:1,h=i.height?e.height/i.height:1;return void((Math.abs(l)+Math.abs(u)>.5||Math.abs(c-1)+Math.abs(h-1)>.01)&&o.animate([{transformOrigin:"0 0",transform:`translate(${l}px, ${u}px) scale(${c}, ${h})`},{transformOrigin:"0 0",transform:"none"}],{duration:t,easing:n}))}"op"===i.type?i.args.forEach(s):o&&o.animate([{opacity:0},{opacity:0},{opacity:1}],{duration:t,easing:n})};s(this.tree)}}function go(e,t,n){if(!t)return null;if("object"==typeof t&&1===t.nodeType)return t;if("undefined"==typeof document||!e.insertAdjacentElement)return null;const r=e.nextElementSibling;if(r&&"view"===r.dataset?.mvMadeBy&&r.classList.contains(`${n}-sr-only`))return r;const s=document.createElement("span");return s.dataset.mvMadeBy="view",s.className=`${n}-sr-only`,s.setAttribute("aria-live","polite"),s.setAttribute("aria-atomic","true"),e.insertAdjacentElement("afterend",s),s}function vo(e){return!!e&&("always"===e||!("function"==typeof matchMedia&&matchMedia("(prefers-reduced-motion: reduce)").matches))}const bo=Symbol.for("inlinemath.expressions"),yo=new Set(["symbol","number"]);function wo(e){return e?"symbol"===e.type?e.value:"op"===e.type&&"_"===e.op&&2===e.args.length&&"symbol"===e.args[0].type&&yo.has(e.args[1].type)?`${e.args[0].value}_${e.args[1].value}`:null:null}function xo(e){const{id:t,...n}=e;return n.args&&(n.args=n.args.map(xo)),n}function $o(e,t){const n=(e,r)=>{if(!r&&void 0!==e.from)return t(e.from);const{id:s,from:i,...o}=e;return o.args&&(o.args=o.args.map(e=>n(e,!1))),o};return n(e,!0)}const ko=new Set;function qo(e,t){let n=!1;const r=new Set,s=(e,i=ko)=>{const o=wo(e);if(null!==o){if(!r.has(o)&&!i.has(o)){const e=t(o);if(e){n=!0,r.add(o);const t={...s(eo(e)),from:o};return r.delete(o),t}}return e}if(e.args){const t=function(e){const[t,n]=e.args,r=e=>e&&"symbol"===e.type?e.value:null;switch(e.op){case"der":return"="===n?.op?r(n.args[0])&&{name:r(n.args[0]),where:e=>0===e,index:1}:r(n)&&{name:r(n),where:e=>e<=1};case"int":{const s=r(n)??(3===e.args.length||1===e.args.length?_(t)||"x":null);return s&&{name:s,where:e=>0===e||1===e&&r(n)===s}}case"lim":return"→"===n?.op&&r(n.args[0])&&{name:r(n.args[0]),where:e=>0===e,index:1};case"\\sumidx":case"\\prodidx":return("="===n?.op||"∈"===n?.op)&&r(n.args[0])&&{name:r(n.args[0]),where:e=>0===e,index:1};default:return null}}(e);if(!t)return{...e,args:e.args.map(e=>s(e,i))};const n=new Set([...i,t.name]);return{...e,args:e.args.map((e,r)=>r===t.index?{...e,args:e.args.map((e,t)=>s(e,0===t?n:i))}:s(e,t.where(r)?n:i))}}return e},i=s(e);return{tree:n?xo(i):e,changed:n}}const Mo="[-+]?(?:\\d+\\.?\\d*|\\.\\d+)",Ao=new RegExp(`^(${Mo})\\s*\\.\\.\\s*(${Mo})(?:\\s+step\\s+(${Mo}))?(?:\\s*=\\s*(${Mo}))?$`);function No(e){const t=/^\s*\[\[([\s\S]*)\]\]\s*$/.exec(e);if(!t||/\]\s*,\s*\[/.test(t[1]))return null;const n=t[1].trim(),r=Ao.exec(n);if(r){const e=Number(r[1]),t=Number(r[2]);if(!(t>e))return null;const n=void 0!==r[3]?Number(r[3]):Number.isInteger(e)&&Number.isInteger(t)?1:(t-e)/100;if(!(n>0))return null;const s=void 0!==r[4]?Math.min(t,Math.max(e,Number(r[4]))):e;return{kind:"slider",min:e,max:t,step:n,default:String(s)}}if(n.includes("|")){const e=n.split("|").map(e=>e.trim()).filter(Boolean);if(e.length)return{kind:"dropdown",options:e,default:e[0]}}return{kind:"textbox",default:n}}const So=Symbol("set on the page");class Oo{constructor(){this.owners=new Map,this.chosen=new Map,this.listeners=new Set}definitions(e){const t=new Map;for(const[n,r]of this.owners)if(n!==e)for(const[e,n]of r)t.delete(e),t.set(e,n);return t}textOf(e){const t=this.chosen.get(e.name);return t&&t.key===e.key?t.text:e.text}get(e){const t=this.definitions().get(e);return t?this.textOf(t):void 0}names(){return[...this.definitions().keys()]}set(e,t){t=String(t);const n=this.definitions().get(e);if(n&&n.input){const r=this.chosen.get(e);if(r&&r.key===n.key&&r.text===t)return this;this.chosen.set(e,{key:n.key,text:t})}else{const n=new Map(this.owners.get(So));n.set(e,{name:e,text:t,key:`page:${t}`,input:null}),this.owners.delete(So),this.owners.set(So,n)}return this.notify(null,e),this}clear(e){return void 0===e?(this.owners.clear(),this.chosen.clear()):(this.owners.get(So)?.delete(e),this.chosen.delete(e)),this.notify(null,e),this}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}own(e,t){const n=this.owners.get(e);var r,s;(r=n,s=t,(r?.size??0)===(s?.size??0)&&[...r??[]].every(([e,t])=>s?.get(e)?.key===t.key))?t&&this.owners.set(e,t):(t&&t.size?this.owners.set(e,t):this.owners.delete(e),this.notify(e))}notify(e,t){for(const n of[...this.listeners])n(e,t)}}function Eo(){return new Oo}const Io=Eo(),_o=new RegExp("(\\d+)","g");function To(e,{delimiters:t=["$$","$","\\[","\\("]}={}){const n=[];let r="",s=0;const i=String(e).replace(/[\uE000-\uE003]/g,"�"),o=e=>0===e||"\n"===i[e-1],a=function(e){const t=new Map,n=e=>/^( {4}|\t)/.test(e);let r=0,s=!0,i=!1,o=-1;for(const a of e.split("\n")){const e=!a.trim();o>-1&&!e&&!n(a)&&(t.set(o,r-1),o=-1),o<0&&!e&&n(a)&&s&&!i&&(o=r),e||n(a)||(i=Do.test(a)||i&&/^\s/.test(a)),s=e,r+=a.length+1}o>-1&&t.set(o,e.length);return t}(i);let l=-1;const u=new Set,c=(e,t,r)=>(n.push({source:e,display:t,raw:r,start:s,end:s+r.length}),`${n.length-1}`);for(;s<i.length;){if(a.has(s)){r+=i.slice(s,a.get(s)),s=a.get(s);continue}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),a=n.exec(`\n${o}`),l=a?o.slice(0,Math.max(0,a.index-1)):o,u=e[0].length+(a?a.index-1+a[0].length:o.length),h=i.slice(s,s+u);"math"===e[3].trim()?r+=c(l,!0,h):r+=h,s+=u;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=u.has(n)?-1:i.indexOf(n,s+2);if(t<0&&u.add(n),t>-1){r+=c(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+=c(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])&&s+1>=l){const{end:e,stop:t}=jo(i,s+1);if(e>-1){r+=c(i.slice(s+1,e),!1,i.slice(s,e+1)),s=e+1;continue}l=t}r+=e,s++}return{text:r,math:n}}function jo(e,t){for(let n=t;n<e.length;n++){const t=e[n];if("\\"!==t){if("`"===t)return{end:-1,stop:n};if("\n"===t&&/^\n[ \t]*\n/.test(e.slice(n,n+64)))return{end:-1,stop:n};if("$"===t&&!/\s/.test(e[n-1])&&!/\d/.test(e[n+1]??"")&&"$"!==e[n+1])return{end:n,stop:n}}else n++}return{end:-1,stop:e.length}}const zo=e=>String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),Lo=/^\s*([A-Za-z\u0370-\u03ff](?:_\{?\w+\}?)?)\s*=\s*([^=<>≤≥]+)$/;function Co(e,t,n,r){const{text:s,math:i}=To(e,t),o=n?n.definitions(r):new Map,a=e=>n?n.textOf(e):e.text,l={...t.scope??{}},u={},c=new Map,h=new Set,p=[],f=e=>{const t=new Map;return n=>{const r=o.get(n);if(!r)return null;if(!t.has(n)){let s=null;try{s=co(a(r),e)}catch{}t.set(n,s)}return t.get(n)}};let d=!0;const m=i.map((e,n)=>{const{source:r,display:s}=e;d&&r.includes("{{")&&((()=>{for(const e of Object.keys(u))delete u[e];Object.assign(u,l);for(const e of o.keys())delete u[e];let e=[...o.values()];for(;e.length;){const t=e.filter(e=>{try{const t=ai(a(e),u);if("number"==typeof t.value||"bigint"==typeof t.value||Array.isArray(t.value))return u[e.name]=t.exact?t.text:t.value,!1}catch{}return!0});if(t.length===e.length)break;e=t}const t={},n=f({});for(const e of o.keys()){const r=n(e);if(r)try{t[e]=O(qo(r,t=>t===e?null:n(t)).tree)}catch{}}u[bo]=t})(),d=!1);const i=s?"mv-md-display":"mv-md-math",m=(e,t="")=>`<span class="${i}${t}" data-mv-md="${n}">${e}</span>`;try{const i={...t.math,display:s,blocks:t.blocks,scope:u},g=function(e){let t=e.trim();const n=t.startsWith("_");n&&(t=t.slice(1).trimStart());let r=t.indexOf(":="),s=2;r<0&&n&&(r=t.search(/(?<![<>!≤≥=])=(?!=)/),s=1);const i=n?{error:"a hidden $_…$ saves a variable: $_A := 2+2$"}:null;if(r<=0)return i;const o=t.slice(0,r).trim(),a=t.slice(r+s).trim();let l=null;try{l=/\{\{/.test(o)?null:wo(co(o))}catch{}return null!==l&&a?{hidden:n,lhs:o,name:l,rhs:a,input:No(a)}:i}(r);if(g&&g.error)throw new Error(g.error);if(g){const{name:t,input:r,hidden:s}=g,l=r?{name:t,text:r.default,input:r,key:`input:${JSON.stringify(r)}`}:{name:t,text:g.rhs,input:null,key:`expr:${g.rhs}`,start:e.start,end:e.end};let u="";if(r){const e=function(e,t){const{input:n,name:r}=e,s=`class="mv-md-input mv-md-${n.kind}" data-mv-var="${zo(r)}" aria-label="${zo(r)}"`;if("dropdown"===n.kind)return`<select ${s}>${n.options.map(e=>`<option value="${zo(e)}"${e===t?" selected":""}>${zo(e)}</option>`).join("")}</select>`;return"slider"===n.kind?`<input type="range" ${s} min="${n.min}" max="${n.max}" step="${n.step}" value="${zo(t)}"><output class="mv-md-output" data-mv-out="${zo(r)}">${zo(t)}</output>`:`<input type="text" ${s} value="${zo(t)}" size="${Math.max(4,t.length+1)}" spellcheck="false" autocomplete="off">`}(l,a(l));u=s?e:`${ho(g.lhs,i)}<span class="mv-md-assign" aria-hidden="true">≔</span>${e}`,h.add(n)}else{const e=qo(co(g.rhs,i),f(i)).tree;if(!s){const t=oo({type:"op",op:"=",args:[eo(co(g.lhs)),void 0===e.id?e:eo(e)]});p[n]=t,u=function(e,t="mv"){return e.replace(`<span class="${t}-rel">=</span>`,`<span class="${t}-rel ${t}-rel-def">≔</span>`).replace(/(aria-label="[^"]*?) equals /,"$1 is defined as ").replace("<mo>=</mo>","<mo>≔</mo>")}(ho(t,i),i.prefix)}}return o.delete(t),o.set(t,l),c.set(t,l),d=!0,s&&!r?"":m(u,r?" mv-md-input-def":"")}const{tree:v,changed:b}=qo(co(r,i),f(i));b&&oo(v),p[n]=v;const y=ho(v,i);return!b&&!1!==t.define&&function(e,t,n){const r=Lo.exec(e);if(!r||/\{\{/.test(r[2]))return!1;const s=r[1].replace(/[{}]/g,"");if(n.has(s))return!1;try{const e=ai(r[2],t);if("number"==typeof e.value||"bigint"==typeof e.value||Array.isArray(e.value))return t[s]=e.exact?e.text:e.value,!0}catch{}return!1}(r,l,o)&&(d=!0),m(y)}catch(t){return`<span class="mv-md-error" data-mv-md="${n}" title="${zo(t.message)}"><code>${zo(e.raw)}</code></span>`}});return{text:s,math:i,drawn:m,defs:c,inputs:h,trees:p}}const Fo=/^(https?:|mailto:|#|\/|\.{0,2}\/|[^:]*$)/i,Zo=e=>Fo.test(e.trim())?zo(e.trim()):"#",Ro=/\uE002(\d+)\uE003/g;function Po(e,t,n,r=[]){const s=e=>(r.push(e),`${r.length-1}`),i=e=>(e=>e.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&"))(n(e).replace(Ro,(e,t)=>(r[Number(t)]??"").replace(/<[^>]*>/g,"")));let o=e;o=o.replace(/(`+)([\s\S]*?[^`])\1(?!`)/g,(e,t,r)=>s(`<code>${zo(n(r.trim()))}</code>`)),o=o.replace(/\\([\\`*_{}[\]()#+\-.!|~$<>"'])/g,(e,t)=>s(zo(t))),o=o.replace(/<((?:https?:\/\/|mailto:)[^\s>]+)>/g,(e,t)=>s(`<a href="${Zo(t)}">${zo(t)}</a>`)),t.html&&(o=o.replace(/<\/?[A-Za-z][^>]*>/g,e=>s(e))),o=o.replace(/!\[([^\[\]]*)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,t,n,r)=>s(`<img src="${Zo(i(n))}" alt="${zo(i(t))}"${r?` title="${zo(i(r))}"`:""}>`)),o=o.replace(/\[([^\[\]]+)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,o,a,l)=>s(`<a href="${Zo(i(a))}"${l?` title="${zo(i(l))}"`:""}>${Po(o,t,n,r)}</a>`)),o=o.replace(/&(?!#\d{1,7};|#x[0-9a-f]{1,6};|[a-z][a-z0-9]{1,31};)/gi,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),o=o.replace(/(\*\*\*|___)(?=\S)([\s\S]*?\S)\1/g,"<strong><em>$2</em></strong>"),o=o.replace(/(\*\*\*|___)(?=\S)([^*_]*?\S)(\*\*|__)(?![*_])([\s\S]*?\S)(\*|_)(?![*_])/g,"<em><strong>$2</strong>$4</em>"),o=o.replace(/(\*\*\*|___)(?=\S)([^*_]*?\S)(\*|_)(?![*_])([\s\S]*?\S)(\*\*|__)(?![*_])/g,"<strong><em>$2</em>$4</strong>"),o=o.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g,"<strong>$2</strong>"),o=o.replace(/(^|[^*\w])\*(?=\S)([\s\S]*?\S)\*(?!\*)/g,"$1<em>$2</em>"),o=o.replace(/(^|[^_\w])_(?=\S)([\s\S]*?\S)_(?![_\w])/g,"$1<em>$2</em>"),o=o.replace(/~~(?=\S)([\s\S]*?\S)~~/g,"<del>$1</del>"),o=o.replace(/( {2,}|\\)\n/g,"<br>\n");for(let e=0;e<8&&/\uE002\d+\uE003/.test(o);e++)o=o.replace(Ro,(e,t)=>r[Number(t)]??"");return o}const Bo=/^( {0,3})(#{1,6}\s|>|```|~~~|([-*+]|\d{1,9}[.)])\s|(\*[ \t]*){3,}$|(-[ \t]*){3,}$|(_[ \t]*){3,}$)/,Do=/^( {0,3})([-*+]|\d{1,9}[.)])(\s+|$)/,Wo=/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/,Uo=e=>Bo.test(e)&&!/^ {0,3}[-=]+\s*$/.test(e)&&!/^ {0,3}(?!1[.)])\d{1,9}[.)]\s/.test(e);function Vo(e){const t=e.trim();let n=t.length;for(;n>0&&"#"===t[n-1];)n--;return n===t.length?t:0===n?"":/[ \t]/.test(t[n-1])?t.slice(0,n).trimEnd():t}function Ho(e,t,n,r=0){const s=[];let i=0;const o=e=>Po(e,t,n);if(r>100)return`<p>${o(e.join("\n"))}</p>`;for(;i<e.length;){const a=e[i];if(!a.trim()){i++;continue}const l=/^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)/.exec(a);if(l){const t=[];for(i++;i<e.length&&!new RegExp(`^ {0,3}${"`"===l[1][0]?"`":"~"}{${l[1].length},}\\s*$`).test(e[i]);)t.push(e[i++]);i++;const r=l[2]?` class="language-${zo(l[2])}"`:"";s.push(`<pre><code${r}>${zo(n(t.join("\n")))}</code></pre>`);continue}const u=/^ {0,3}(#{1,6})[ \t]+/.exec(a);if(u){s.push(`<h${u[1].length}>${o(Vo(a.slice(u[0].length)))}</h${u[1].length}>`),i++;continue}if(/^ {0,3}((\*[ \t]*){3,}|(-[ \t]*){3,}|(_[ \t]*){3,})$/.test(a)){s.push("<hr>"),i++;continue}if(/^ {0,3}>/.test(a)){const o=[];for(;i<e.length&&e[i].trim()&&(/^ {0,3}>/.test(e[i])||o.length);)o.push(e[i].replace(/^ {0,3}> ?/,"")),i++;s.push(`<blockquote>\n${Ho(o,t,n,r+1)}\n</blockquote>`);continue}const c=Do.exec(a);if(c){const o=/\d/.test(c[2]),a=o?parseInt(c[2],10):1,l=[];let u=!1;for(;i<e.length;){const t=Do.exec(e[i]);if(!t||/\d/.test(t[2])!==o)break;const n=t[0].length,r=[e[i].slice(n)];for(i++;i<e.length;){const t=e[i];if(!t.trim()){const t=e[i+1];if(void 0!==t&&t.startsWith(" ".repeat(Math.min(n,4)))&&t.trim()){r.push(""),u=!0,i++;continue}void 0!==t&&Do.test(t)&&(u=!0);break}if(t.startsWith(" ".repeat(Math.min(n,4))))r.push(t.slice(Math.min(n,4)));else{if(Do.test(t)||Bo.test(t))break;r.push(t)}i++}for(l.push(r);i<e.length&&!e[i].trim()&&void 0!==e[i+1]&&Do.test(e[i+1]);)i++}const h=o?"ol":"ul",p=l.map(e=>{let s=Ho(e,t,n,r+1);return u||(s=s.replace(/^<p>([\s\S]*?)<\/p>/,"$1").replace(/\n<p>([\s\S]*?)<\/p>/g,"\n$1")),`<li>${s}</li>`});s.push(`<${h}${o&&1!==a?` start="${a}"`:""}>\n${p.join("\n")}\n</${h}>`);continue}if(a.includes("|")&&void 0!==e[i+1]&&Wo.test(e[i+1])&&e[i+1].includes("-")){const t=e=>e.trim().replace(/^\|/,"").replace(/\|$/,"").split(/(?<!\\)\|/).map(e=>e.trim()),n=t(e[i+1]).map(e=>e.startsWith(":")&&e.endsWith(":")?"center":e.endsWith(":")?"right":e.startsWith(":")?"left":""),r=(e,t,r)=>`<${e}${n[r]?` style="text-align:${n[r]}"`:""}>${o(t)}</${e}>`,l=t(a);i+=2;const u=[];for(;i<e.length&&e[i].trim()&&e[i].includes("|");)u.push(t(e[i++]));s.push(`<table>\n<thead><tr>${l.map((e,t)=>r("th",e,t)).join("")}</tr></thead>\n<tbody>\n${u.map(e=>`<tr>${l.map((t,n)=>r("td",e[n]??"",n)).join("")}</tr>`).join("\n")}\n</tbody>\n</table>`);continue}if(/^( {4}|\t)/.test(a)){const t=[];for(;i<e.length&&(/^( {4}|\t)/.test(e[i])||!e[i].trim());)t.push(e[i++].replace(/^( {4}|\t)/,""));for(;t.length&&!t[t.length-1].trim();)t.pop();s.push(`<pre><code>${zo(n(t.join("\n")))}</code></pre>`);continue}const h=[];for(;i<e.length&&e[i].trim()&&(!h.length||!Uo(e[i]));){if(h.length&&/^ {0,3}(=+|-+)\s*$/.test(e[i])){const t="="===e[i].trim()[0]?1:2;s.push(`<h${t}>${o(h.join("\n"))}</h${t}>`),h.length=0,i++;break}h.push(e[i].replace(/^ {0,3}/,"")),i++}h.length&&s.push(`<p>${o(h.join("\n"))}</p>`)}return s.join("\n")}function Go(e,t={},n=e=>e){return Ho(String(e).replace(/\r\n?/g,"\n").replace(/[\uE002\uE003]/g,"�").split("\n"),t,n)}function Xo({text:e,math:t,drawn:n},r){return(r.render?r.render(e):Go(e,r,e=>e.replace(_o,(e,n)=>t[Number(n)]?.raw??""))).replace(new RegExp("<p>\\s*(\\d+)\\s*</p>","g"),(e,r)=>t[Number(r)].display&&n[Number(r)]?`<div class="mv-md-block">${n[Number(r)]}</div>`:e).replace(_o,(e,t)=>n[Number(t)]??"").replace(/<p>\s*<\/p>\n?/g,"")}const Qo=new WeakMap,Jo=new Set;function Yo(){for(const e of Jo)e.connected()&&!e.element.isConnected&&e.stop(!0)}function Ko(e){const t=e=>function(e){if(e.length>1e6)throw new Error("The output would be too long");return e}("op"===e.type?na(e,t):function(e){const t=e.value;return"symbol"!==e.type?t:T[t]?T[t]:"\\+"===t||"\\-"===t?t[1]:t}(e));return t(e)}const ea={"+":"+","-":"-","*":"*","/":"/","^":"^",mod:"mod","±":"±","=":"=","===":"===","≠":"≠","≠=":"≠","<":"<",">":">","≤":"≤","≥":"≥","∈":"∈","∉":"∉","→":"→","≈":"≈","∪":"∪","∩":"∩","≡":"≡","&":"∧","|":"∨","\\xor":"⊕","\\nand":"↑","\\nor":"↓"},ta={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]};function na(e,t){const{op:n,args:r}=e,[s,i]=r,a=(e,r)=>c(n,C(e),r)?`(${t(e)})`:t(e),l=()=>r.map(t).join(", "),u=e=>R(n,e)?`(${t(e)})`:t(e);if("*"===n&&L(e))return na({...e,op:"neg",args:[i]},t);if("+"===n&&L(i))return na({...e,op:"-",args:[s,i.args[1]]},t);if("-"===n&&L(i))return na({...e,op:"+",args:[s,i.args[1]]},t);if("^"===n){const e=a(s,"left");return`${e.startsWith("-")?`(${e})`:e}^${a(i,"right")}`}if("*"===n&&e.written)return`${a(s,"left")} ${"cross"===e.written?"×":"·"} ${a(i,"right")}`;if(ea[n])return`${a(s,"left")} ${ea[n]} ${a(i,"right")}`;if(ne[n])return`${n}(${re(e).map(e=>`[${e.map(t).join(", ")}]`).join(", ")})`;if(ta[n])return ta[n][0]+l()+ta[n][1];if(o(n))return`${X(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`${K(s)?`(${t(s)})`:t(s)} ? ${t(i)} : ${t(r[2])}`;case"sum":return r.map((e,n)=>c("+",C(e),n?"right":"left")?`(${t(e)})`:t(e)).join(" + ");case"prod":return r.map((e,n)=>c("*",C(e),n?"right":"left")?`(${t(e)})`:t(e)).join(" * ");case"der":{const{n:n,body:r,by:s,at:i,variable:o}=Q(e);if(i)return`der(${t(r)}, ${t(s)} = ${t(i)}${n>1?`, ${n}`:""})`;const a=n>1?`^${n}`:"";return o?`d${a}${t(r)}/d${t(s)}${a}`:`d${a}/d${t(s)}${a}(${t(r)})`}case"int":return function(e,t){const[n,r,s,i]=e,o=e.length>=2&&G(r)?t(r):_(n)||"x",a=`${t(n)} d${o}`;return 1===e.length||2===e.length&&G(r)?`∫ ${a}`:`int(${e.map(t).join(", ")})`}(r,t);case"lim":return function(e,t){const[n,r,s,i]=e;return 4===e.length?`lim(${t(n)}, ${t(r)}, ${t(s)}, ${j(i).toLowerCase().startsWith("r")?"r":"l"})`:`lim(${e.map(t).join(", ")})`}(r,t);case"\\sumidx":return ra("∑",r,t);case"\\prodidx":return ra("∏",r,t)}return`${n}(${l()})`}function ra(e,t,n){const[r,s,i]=t,o="∑"===e?"sum":"prod";if(3===t.length&&"op"===s.type&&"="===s.op)return`${o}(${n(r)}, ${n(s)}, ${n(i)})`;if(2===t.length&&"op"===s.type&&"∈"===s.op)return`${o}(${n(r)}, ${n(s)})`;const a=_(r);return 3===t.length&&a?`${o}(${n(r)}, ${a} = ${n(s)}, ${n(i)})`: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[ea,ta])Object.setPrototypeOf(e,null);function sa(e){return Bn(e)?"":Ko(Pn(e))}const ia=new Map,oa=-1,aa="\\:",la=e=>"string"==typeof e&&e.startsWith(aa)&&e.length>2;function ua(e){if(!e||!e.symbol)throw new Error("operator needs a symbol");if(!Number.isInteger(e.arity)||e.arity<0&&e.arity!==oa)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 ia.set(t.symbol,t),t}const ca=Object.freeze({symbol:aa,arity:oa,commutative:!1,fold:null,label:"function"});function ha(e){const t=ia.get(e);return t||(la(e)?{...ca,symbol:e,label:e.slice(2)}:null)}function pa(e){return ia.has(e)||la(e)}const fa=e=>Number.isFinite(e)&&Number.isInteger(e)?e:null,da=e=>Number.isFinite(e)?e:null;!function(){ua({symbol:"+",arity:2,commutative:!0,label:"add",fold:(e,t)=>da(e+t)}),ua({symbol:"-",arity:2,label:"subtract",fold:(e,t)=>da(e-t)}),ua({symbol:"*",arity:2,commutative:!0,label:"multiply",fold:(e,t)=>da(e*t)}),ua({symbol:"/",arity:2,label:"divide",fold:(e,t)=>0===t?null:fa(e/t)}),ua({symbol:"^",arity:2,label:"power",fold:(e,t)=>Number.isInteger(t)&&Math.abs(t)<=64?da(e**t):null}),ua({symbol:"neg",arity:1,label:"negate",fold:e=>da(-e)}),ua({symbol:"pm",arity:1,label:"plus or minus"}),ua({symbol:"±",arity:2,label:"plus or minus"}),ua({symbol:"mod",arity:2,label:"modulo",fold:(e,t)=>0===t?null:fa((e%t+t)%t)}),ua({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}),ua({symbol:"_",arity:2,label:"subscript"}),ua({symbol:"der",arity:2,label:"derivative"}),ua({symbol:"int",arity:oa,label:"integral"}),ua({symbol:"lim",arity:oa,label:"limit"}),ua({symbol:"\\sumidx",arity:oa,label:"sum over an index"}),ua({symbol:"\\prodidx",arity:oa,label:"product over an index"}),ua({symbol:"abs",arity:1,label:"absolute value",fold:e=>da(Math.abs(e))}),ua({symbol:"floor",arity:1,label:"floor",fold:e=>da(Math.floor(e))}),ua({symbol:"ceil",arity:1,label:"ceiling",fold:e=>da(Math.ceil(e))}),ua({symbol:"round",arity:2,label:"round",fold:(e,t)=>Number.isInteger(t)?da(Math.round(e*10**t)/10**t):null}),ua({symbol:"fixed",arity:2,label:"fixed",fold:()=>null}),ua({symbol:"sqrt",arity:1,label:"square root",fold:e=>fa(Math.sqrt(e))}),ua({symbol:"root",arity:2,label:"nth root",fold:(e,t)=>fa(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"])ua({symbol:e,arity:1,label:e});ua({symbol:"log",arity:2,label:"log to a base"}),ua({symbol:"atan2",arity:2,label:"atan2"}),ua({symbol:"perm",arity:2,label:"permutations"}),ua({symbol:"comb",arity:2,label:"combinations"}),ua({symbol:"random",arity:0,label:"random"});for(const e of["max","min","gcd","mean","sum","prod"])ua({symbol:e,arity:oa,label:e});for(const e of["()","[]","{}","(]","[)"])ua({symbol:e,arity:oa,label:"group"});for(const e of["pmatrix","bmatrix","vmatrix"])ua({symbol:e,arity:oa,label:"matrix"});ua({symbol:"det",arity:1,label:"determinant"});for(const e of["=","===","≠","≠=","<",">","≤","≥","∈","∉","∪","∩","≈","≡","→","pmod","&","|","\\xor","\\nand","\\nor"])ua({symbol:e,arity:2,label:e});ua({symbol:"\\not",arity:1,label:"not"}),ua({symbol:"?:",arity:3,label:"if then else"})}();const ma="num",ga="sym",va="op",ba=Object.freeze([]);class ya extends Error{constructor(e){super(e),this.name="ExprError"}}function wa(e){if("number"!=typeof e||!Number.isFinite(e))throw new ya(`not a finite number: ${e}`);const t=(n=e,Object.is(n,-0)?"0":String(n));var n;return Object.freeze({type:ma,token:t,value:e,args:ba,s:t})}function xa(e){if("string"!=typeof e||""===e)throw new ya("symbol needs a non-empty token");return Object.freeze({type:ga,token:e,value:null,args:ba,s:e})}function $a(e){const t=/^(-?)0*(\d+?)(?:\.(\d*?)0*)?$/.exec(String(e));if(!t)throw new ya(`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:ma,token:o,value:Number(o),args:ba,s:o})}const ka=/^-?\d+(\.\d+)?$/;function qa(e){const t=String(e);if(ka.test(t))return $a(t);if(""!==t&&!/\s/.test(t)){const e=Number(t);if(Number.isFinite(e))return wa(e)}return xa(t)}function Ma(e,t){const n=ha(e);if(!n)throw new ya(`unknown operator "${e}"`);if(n.arity!==oa&&t.length!==n.arity)throw new ya(`"${e}" takes ${n.arity} operand(s), got ${t.length}`);const r=Object.freeze(t.slice()),s=n.arity===oa?` ${r.length}`:"",i=`${r.length?r.map(e=>e.s).join(" "):""}${r.length,""}${s} ${e}`.trimStart();return Object.freeze({type:va,op:e,token:e,value:null,args:r,s:i})}const Aa=e=>e.type===ma,Na=e=>e.type===va;function Sa(e){return Oa(function(e){const t=String(e).trim();return""===t?[]:t.split(/\s+/)}(e))}function Oa(e){if(!Array.isArray(e))throw new ya("fromPostfix needs an array of tokens");if(0===e.length)throw new ya("empty expression");const t=[];for(let n=0;n<e.length;n++){const r=String(e[n]);if(pa(r)){let e=ha(r).arity;if(e===oa){const s=t.pop();if(e=s&&s.type===ma&&Number.isInteger(s.value)&&s.value>=0?s.value:-1,e<0)throw new ya(`"${r}" at position ${n+1} takes any number of operands, so a count must come before it`)}if(t.length<e)throw new ya(`"${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(Ma(r,s))}else t.push(qa(r))}if(1!==t.length){const n=[...new Set(e.filter(e=>!pa(e)))];throw new ya(`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 Ea(e){if(e.type!==va)return 0;let t=0;for(const n of e.args)t=Math.max(t,Ea(n));return t+1}function Ia(e){if(e.type!==va)return 1;let t=1;for(const n of e.args)t+=Ia(n);return t}function _a(e,t=[]){if(e.type!==va)t.push(e.token);else for(const n of e.args)_a(n,t);return t}function Ta(e){return e.type===ma||e.type!==ga&&e.args.every(Ta)}function ja(e,t="pre",n=[],r=[]){"pre"===t&&r.push({node:e,path:n});for(let s=0;s<e.args.length;s++)ja(e.args[s],t,n.concat(s),r);return"post"===t&&r.push({node:e,path:n}),r}function za(e,t,n){if(0===t.length)return n;const[r,...s]=t,i=e.args.slice();return i[r]=za(i[r],s,n),Ma(e.op,i)}class La extends Error{constructor(e){super(e),this.name="CasError"}}const Ca=1e5,Fa=e=>e<0n?-e:e,Za=e=>0n===e?0:Fa(e).toString(2).length;function Ra(e,t){for(e=Fa(e),t=Fa(t);t;)[e,t]=[t,e%t];return e}class Pa{constructor(e,t=1n){if(0n===t)throw new La("division by zero");t<0n&&(e=-e,t=-t);const n=Ra(e,t)||1n;if(this.n=e/n,this.d=t/n,Za(this.n)>Ca||Za(this.d)>Ca)throw new La("a number too large to keep exactly")}static of(e){return new Pa(BigInt(e))}add(e){return new Pa(this.n*e.d+e.n*this.d,this.d*e.d)}sub(e){return new Pa(this.n*e.d-e.n*this.d,this.d*e.d)}mul(e){return new Pa(this.n*e.n,this.d*e.d)}div(e){if(0n===e.n)throw new La("division by zero");return new Pa(this.n*e.d,this.d*e.n)}neg(){return new Pa(-this.n,this.d)}abs(){return this.n<0n?this.neg():this}inv(){return Pa.ONE.div(this)}pow(e){if((e=BigInt(e))<0n)return this.inv().pow(-e);if((0n===this.n||1n===Fa(this.n))&&1n===this.d)return 0n===e||-1n===this.n&&e%2n==0n?Pa.ONE:this;if(BigInt(Math.max(Za(this.n),Za(this.d)))*e>BigInt(Ca))throw new La("a power too large to work out exactly");return new Pa(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 Pa(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(Za(this.n),Za(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 Ba(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 Pa(BigInt((r||"0")+s),10n**BigInt(s.length));const a=Number(i);return a&&(o=o.mul(Pa.of(10).pow(a))),n?o.neg():o}function Da(e,t){if(e<2n)return e;if(t>=Za(e))return 1n;const n=BigInt(t);let r=1n<<BigInt(Math.ceil(Za(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}Pa.ZERO=new Pa(0n),Pa.ONE=new Pa(1n),Pa.MINUS_ONE=new Pa(-1n),Pa.HALF=new Pa(1n,2n);const Wa=(()=>{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 Ua(e,t){const n=BigInt(t);let r=1n,s=1n,i=e;for(const e of Wa){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=Da(e,t);return n**BigInt(t)===e?n:null}(i,t);null!==e?r*=e:s*=i}return{outside:r,inside:s}}const Va=new Set(["pi","e","π"]),Ha={complex:!1};function Ga(e,t){const n=Ha.complex;Ha.complex=Boolean(e);try{return t()}finally{Ha.complex=n}}const Xa=e=>Va.has(e)||Ha.complex&&"i"===e,Qa=e=>Ha.complex&&"atom"===e.k&&"sym"===e.node.type&&"i"===e.node.token,Ja=e=>({k:"num",q:e}),Ya=Ja(Pa.ONE),Ka=Ja(Pa.ZERO),el=Ja(Pa.HALF),tl=e=>"num"===e.k,nl=e=>({k:"atom",node:e}),rl=new WeakMap;function sl(e){let t=rl.get(e);return void 0===t&&rl.set(e,t=Ll(e).s),t}function il(e){if("num"===e.k)return 0;if("atom"===e.k)return"sym"===e.node.type&&Xa(e.node.token)?0:1;if("add"===e.k)return Math.max(...e.terms.map(e=>il(e.x)));let t=0;for(const n of e.fs){const e=il(n.b);e&&(t+=e*(tl(n.e)?n.e.q.toNumber():1))}return t}function ol(e,t){return"num"===e.k?t&&!tl(t)?3:0:Qa(e)?1.5:"atom"===e.k&&"sym"===e.node.type?Xa(e.node.token)?t&&!tl(t)?3:1:2:"atom"===e.k?3:4}const al=(e,t)=>e<t?-1:e>t?1:0;function ll(e){const t=new Map,n=(e,n)=>{"atom"!==e.k||"sym"!==e.node.type||Xa(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,tl(t.e)?t.e.q.toNumber():1);else n(e,1);return t}function ul(e,t){const n=il(t.x)-il(e.x);if(n)return n;const r=ll(e.x),s=ll(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 al(sl(e.x),sl(t.x))}function cl(e,t){return e.isOne?t:e.isZero?Ka:dl([Ja(e),t])}function hl(e){if("num"===e.k)return{coef:e.q,rest:null};if("mul"!==e.k||e.c.isOne)return{coef:Pa.ONE,rest:e};const t=1===e.fs.length&&tl(e.fs[0].e)&&e.fs[0].e.q.isOne?e.fs[0].b:{k:"mul",c:Pa.ONE,fs:e.fs};return{coef:e.c,rest:t}}function pl(e){let t=Pa.ZERO;const n=new Map,r=(e,t)=>{const r=sl(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}=hl(n);r(e,t)}const s=[...n.values()].filter(e=>!e.coef.isZero);return s.length?t.isZero&&1===s.length?cl(s[0].coef,s[0].x):(s.sort(ul),{k:"add",c:t,terms:s}):Ja(t)}function fl(e,t){if(!tl(t))return e.isOne?{coef:Pa.ONE,fs:[]}:{coef:Pa.ONE,fs:[{b:Ja(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 La("division by zero");return{coef:Pa.ZERO,fs:[]}}if(e.isOne)return{coef:Pa.ONE,fs:[]};if(e.sign<0){if(n.d%2n==1n){const{coef:r,fs:s}=fl(e.neg(),t);return{coef:n.n%2n==0n?r:r.neg(),fs:s}}if(Ha.complex&&2n===n.d){const{coef:r,fs:s}=fl(e.neg(),t);return{coef:r,fs:[...s,{b:vl,e:Ja(new Pa(n.n))}]}}return{coef:Pa.ONE,fs:[{b:Ja(e),e:t}]}}if(!e.isInteger){const r=fl(new Pa(e.n),t),s=fl(new Pa(e.d),Ja(n.neg()));return{coef:r.coef.mul(s.coef),fs:[...r.fs,...s.fs]}}const r=n.floor(),s=n.sub(r);if(BigInt(Za(e.n))*s.n>BigInt(Ca)||s.d>1000n)return{coef:Pa.ONE,fs:[{b:Ja(e),e:t}]};let i=r.isZero?Pa.ONE:e.pow(r.n);const{outside:o,inside:a}=Ua(e.n**s.n,Number(s.d));i=i.mul(new Pa(o));return{coef:i,fs:a>1n?[{b:Ja(new Pa(a)),e:Ja(new Pa(1n,s.d))}]:[]}}function dl(e){let t=Pa.ONE;const n=new Map,r=(e,t)=>{const r=sl(e),s=n.get(r);s?s.e=pl([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,Ya);if(t.isZero)return Ka;const s=[],i=new Map;for(const e of n.values())if(!tl(e.e)||!e.e.q.isZero){if("num"===e.b.k){if(tl(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=fl(e.b.q,e.e);t=t.mul(n.coef),s.push(...n.fs);continue}if("mul"===e.b.k&&tl(e.e)&&e.e.q.isInteger){const n=ml(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:Ya});continue}s.push(e)}for(const{n:e,e:n}of i.values()){const r=fl(new Pa(e),n);t=t.mul(r.coef),s.push(...r.fs)}if(t.isZero)return Ka;const o=new Map;for(const e of s){const t=sl(e.b),n=o.get(t);n?n.e=pl([n.e,e.e]):o.set(t,{...e})}let a=[...o.values()].filter(e=>!(tl(e.e)&&e.e.q.isZero));if(Ha.complex){a=a.flatMap(e=>{if(!Qa(e.b)||!tl(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:Ya}]:[]});const e=a.filter(e=>"add"===e.b.k&&tl(e.e)&&e.e.q.isInteger&&yl(e.b)),n=a.some(e=>Qa(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)&&!Qa(t.b));let s=n?[vl]:[Ya];for(const t of e){const e=t.e.q.sign<0?$l(t.b):t.b;for(let n=0n;n<(t.e.q.sign<0?-t.e.q.n:t.e.q.n);n++)s=wl(s,Rl(e))}return dl([Ja(t),pl(s),...r.map(e=>gl(e.b,e.e))])}}if(a.some(e=>"num"===e.b.k&&tl(e.e)&&e.e.q.compare(Pa.ONE)>=0))return dl([Ja(t),...a.map(e=>"num"===e.b.k?ml(e.b,e.e):{k:"mul",c:Pa.ONE,fs:[e]})]);if(!a.length)return Ja(t);if(1===a.length&&!t.isOne&&"add"===a[0].b.k&&tl(a[0].e)&&a[0].e.q.isOne){const e=a[0].b;return pl([Ja(t.mul(e.c)),...e.terms.map(e=>cl(t.mul(e.coef),e.x))])}return t.isOne&&1===a.length&&tl(a[0].e)&&a[0].e.q.isOne?a[0].b:(a=a.sort((e,t)=>ol(e.b,e.e)-ol(t.b,t.e)||al(sl(e.b),sl(t.b))),{k:"mul",c:t,fs:a})}function ml(e,t){if(Ha.complex&&tl(t)&&t.q.isInteger){if(Qa(e))return dl([{k:"mul",c:Pa.ONE,fs:[{b:e,e:t}]}]);if("add"===e.k&&yl(e)&&!t.q.isOne)return dl([{k:"mul",c:Pa.ONE,fs:[{b:e,e:t}]}])}if(tl(t)){if(t.q.isZero){if(tl(e)&&e.q.isZero)throw new La("0^0 is undefined");return Ya}if(t.q.isOne)return e}if(tl(e)){const n=fl(e.q,t);if(!n.fs.length)return Ja(n.coef);if(n.fs.some(e=>Qa(e.b)))return dl([Ja(n.coef),...n.fs.map(e=>({k:"mul",c:Pa.ONE,fs:[e]}))]);const r={k:"mul",c:n.coef,fs:n.fs};return n.coef.isOne&&1===n.fs.length&&tl(n.fs[0].e)&&n.fs[0].e.q.isOne?n.fs[0].b:r}if(Ha.complex&&tl(t)&&2n===t.q.d&&yl(e)){const n=xl(e);if(n&&tl(n.im)&&!n.im.q.isZero){const e=e=>ml(e,Ja(Pa.of(2))),r=ml(pl([e(n.re),e(n.im)]),el),s=ml(dl([pl([r,n.re]),Ja(Pa.HALF)]),el),i=ml(dl([pl([r,Ml(n.re)]),Ja(Pa.HALF)]),el);return ml(pl([s,dl([Ja(Pa.of(n.im.q.sign)),i,vl])]),Ja(new Pa(t.q.n)))}}if("mul"===e.k){if(tl(t)&&t.q.isInteger)return dl([Ja(e.c.pow(t.q.n)),...e.fs.map(e=>gl(e.b,dl([e.e,t])))]);if(!e.c.isOne&&e.c.sign>0)return dl([ml(Ja(e.c),t),ml({k:"mul",c:Pa.ONE,fs:e.fs},t)]);if(e.c.isOne&&1===e.fs.length){const[n]=e.fs;if(tl(n.e)&&tl(t)&&1n===n.e.q.n&&n.e.q.d%2n==1n)return gl(n.b,dl([n.e,t]))}}return{k:"mul",c:Pa.ONE,fs:[{b:e,e:t}]}}function gl(e,t){return tl(t)&&t.q.isZero?Ya:tl(e)?ml(e,t):tl(t)&&t.q.isOne?e:{k:"mul",c:Pa.ONE,fs:[{b:e,e:t}]}}const vl=nl(xa("i")),bl=e=>Ha.complex&&Ll(e).s.split(" ").includes("i");function yl(e){return Ha.complex&&bl(e)&&0===Zl(Ll(e)).size}function wl(e,t){const n=[];for(const r of e)for(const e of t)n.push(dl([r,e]));return Rl(pl(n))}function xl(e){const t=[],n=[];for(const r of Rl(e)){const{coef:e,rest:s}=hl(r),i=s?Pl(s):[],o=i.filter(e=>Qa(e)),a=i.filter(e=>!Qa(e));if(a.some(e=>bl(e)))return null;(o.length?n:t).push(dl([Ja(e),...a]))}return{re:pl(t),im:pl(n)}}function $l(e){const t=xl(e);if(!t)return ml(e,Ja(Pa.MINUS_ONE));const n=pl([ml(t.re,Ja(Pa.of(2))),ml(t.im,Ja(Pa.of(2)))]);return dl([pl([t.re,dl([Ja(Pa.MINUS_ONE),t.im,vl])]),ml(n,Ja(Pa.MINUS_ONE))])}const kl={re:([e])=>xl(e)?.re??null,im:([e])=>xl(e)?.im??null,conj:([e])=>{const t=xl(e);return t?pl([t.re,dl([Ja(Pa.MINUS_ONE),t.im,vl])]):null},arg:([e])=>{const t=xl(e);return t?Ol("atan2",[t.im,t.re]):null},abs:([e])=>{const t=xl(e);return!t||tl(t.im)&&t.im.q.isZero?null:ml(pl([ml(t.re,Ja(Pa.of(2))),ml(t.im,Ja(Pa.of(2)))]),el)}},ql={Re:"re",re:"re",Im:"im",im:"im",conj:"conj",overline:"conj",bar:"conj",arg:"arg"},Ml=e=>dl([Ja(Pa.MINUS_ONE),e]),Al=(e,t)=>dl([e,ml(t,Ja(Pa.MINUS_ONE))]),Nl=3000n,Sl={abs:([e])=>tl(e)?Ja(e.q.abs()):"mul"!==e.k||e.c.isOne?null:dl([Ja(e.c.abs()),Ol("abs",[hl(e).rest])]),floor:([e])=>tl(e)?Ja(e.q.floor()):null,ceil:([e])=>tl(e)?Ja(e.q.ceil()):null,"!":([e])=>{if(!tl(e)||!e.q.isInteger||e.q.sign<0||e.q.n>Nl)return null;let t=1n;for(let n=2n;n<=e.q.n;n++)t*=n;return Ja(new Pa(t))},mod:([e,t])=>tl(e)&&tl(t)&&!t.q.isZero?Ja(e.q.sub(t.q.mul(e.q.div(t.q).floor()))):null,max:e=>e.every(tl)&&e.length?e.reduce((e,t)=>t.q.compare(e.q)>0?t:e):null,min:e=>e.every(tl)&&e.length?e.reduce((e,t)=>t.q.compare(e.q)<0?t:e):null,gcd:e=>e.length&&e.every(e=>tl(e)&&e.q.isInteger)?Ja(new Pa(e.reduce((e,t)=>Ra(e,t.q.n),0n))):null,log:([e,t])=>{if(!tl(e)||!tl(t)||e.q.sign<=0||t.q.sign<=0||e.q.isOne)return null;if(t.q.isOne)return Ka;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 Ja(new Pa(BigInt(s),BigInt(r)))}return null},comb:([e,t])=>tl(e)&&tl(t)&&e.q.isInteger&&t.q.isInteger&&e.q.sign>=0&&t.q.sign>=0&&e.q.n<=Nl?Ja(function(e,t){if(t>e)return Pa.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 Pa(n)}(e.q.n,t.q.n)):null,perm:([e,t])=>{if(!(tl(e)&&tl(t)&&e.q.isInteger&&t.q.isInteger&&e.q.sign>=0&&t.q.sign>=0&&e.q.n<=Nl))return null;if(t.q.n>e.q.n)return Ka;let n=1n;for(let r=0n;r<t.q.n;r++)n*=e.q.n-r;return Ja(new Pa(n))}};function Ol(e,t){if(Ha.complex&&kl[e]){const n=kl[e](t);if(n)return n}const n=Sl[e];if(n){const e=n(t);if(e)return e}return nl(Ma(e,t.map(Ll)))}const El=new Map;function Il(e){const t=Ha.complex?`ℂ ${e.s}`:e.s,n=El.get(t);if(n)return n;const r=function(e){if("num"===e.type){const t=Ba(e.token);if(!t)throw new La(`not an exact number: ${e.token}`);return Ja(t)}if("sym"===e.type)return"π"===e.token?nl(xa("pi")):nl(e);const t=e.args.map(Il);switch(e.op){case"+":return pl(t);case"-":return((e,t)=>pl([e,Ml(t)]))(t[0],t[1]);case"neg":return Ml(t[0]);case"*":return dl(t);case"/":return Al(t[0],t[1]);case"^":return ml(t[0],t[1]);case"sqrt":return ml(t[0],el);case"root":return ml(t[1],ml(t[0],Ja(Pa.MINUS_ONE)));default:{const n=e.op.startsWith("\\:")?e.op.slice(2):null;return n&&Ha.complex&&ql[n]&&1===t.length?Ol(ql[n],t):n&&pa(n)&&ha(n).arity===t.length?Ol(n,t):Ol(e.op,t)}}}(e);return El.size>2e4&&El.clear(),El.set(t,r),r}const _l=e=>Ll(Il(e)),Tl=e=>$a(String(e));function jl(e){return e.isInteger?Tl(e.n):Ma("/",[Tl(e.n),Tl(e.d)])}const zl=new WeakMap;function Ll(e){let t=zl.get(e);return t||zl.set(e,t=function(e){switch(e.k){case"num":return jl(e.q);case"atom":return e.node;case"mul":return function(e,t){const n=[],r=[];for(const e of t)tl(e.e)&&e.e.q.sign<0?r.push(Cl(e.b,Ja(e.e.q.neg()))):n.push(Cl(e.b,e.e));let s=1n!==e.n&&-1n!==e.n||!n.length?Fl([Tl(e.n),...n]):Fl(n);-1n===e.n&&n.length&&(s=Ma("neg",[s]));1n!==e.d&&r.unshift(Tl(e.d));return r.length?Ma("/",[s,Fl(r)]):s}(e.c,e.fs);case"add":return function(e){let t=null;const n=e=>Ha.complex&&bl(e.x)&&0===Zl(Ll(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?Ma("-",[t,jl(s.neg())]):Ma("+",[t,jl(s)]):jl(s))};let o=!1;for(const e of r)!o&&n(e)&&(i(),o=!0),t=t?e.coef.sign<0?Ma("-",[t,Ll(cl(e.coef.neg(),e.x))]):Ma("+",[t,Ll(cl(e.coef,e.x))]):Ll(cl(e.coef,e.x));o||i();return t}(e);default:throw new Error(`bad form ${e.k}`)}}(e)),t}function Cl(e,t){const n=Ll(e);if(tl(t)){const e=t.q;if(e.isOne)return n;if(1n===e.n&&2n===e.d)return Ma("sqrt",[n]);if(1n===e.n)return Ma("root",[Tl(e.d),n])}return Ma("^",[n,Ll(t)])}const Fl=e=>e.reduce((e,t)=>e?Ma("*",[e,t]):t,null);function Zl(e,t=new Set){if("sym"===e.type)Xa(e.token)||t.add(e.token);else if(Na(e))for(const n of e.args)Zl(n,t);return t}function Rl(e){if("add"!==e.k)return[e];const t=e.terms.map(e=>cl(e.coef,e.x));return e.c.isZero||t.push(Ja(e.c)),t}function Pl(e){if("num"===e.k)return[e];if("mul"!==e.k)return[e];const t=e.c.isOne?[]:[Ja(e.c)];for(const n of e.fs)t.push(gl(n.b,n.e));return t}const Bl="_",Dl=new WeakMap;function Wl(e,t){return[...t,...ha(e.op)?.arity===oa?[String(e.args.length)]:[],e.op].join(" ")}function Ul(e,t){let n=Dl.get(e);n||Dl.set(e,n=new Map);const r=n.get(t);if(r)return r;const s=function(e,t){const n={key:Bl,slots:[e]};if(e.type!==va||t<=0)return[n];const r=e.args.map(e=>Ul(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:Wl(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 Vl(e){return e.type!==va?Bl:Wl(e,e.args.map(Vl))}function Hl(e,t=[]){if(e.type!==va)t.push(e);else for(const n of e.args)Hl(n,t);return t}const Gl=new Map,Xl=new Map;class Ql extends Error{constructor(e){super(e),this.name="RequirementError"}}function Jl(e,t,n=""){Gl.set(e,{name:e,fn:t,doc:n,arity:Math.max(0,t.length-1)})}function Yl(e,t,n=""){Xl.set(e,{name:e,fn:t,doc:n})}function Kl(e){return Gl.get(e)||null}function eu(e){return Xl.get(e)||null}const tu=e=>e.type===ma;function nu(e,t){return e.type===va&&(e.op===t||e.args.some(e=>nu(e,t)))}Jl("always",()=>!0,"matches anything"),Jl("never",()=>!1,"matches nothing"),Jl("isLeaf",e=>e.type!==va,"a bare operand, not an operation"),Jl("isCompound",e=>e.type===va,"an operation, not a bare operand"),Jl("isSymbol",e=>e.type===ga,"a non-numeric operand such as x"),Jl("isOperation",(e,t)=>e.type===va&&e.op===t,"is this specific operation"),Jl("notOperation",(e,t)=>!(e.type===va&&e.op===t),"is anything except this operation"),Jl("isNumber",tu,"a numeric literal"),Jl("isInteger",e=>tu(e)&&Number.isInteger(e.value),"a whole number"),Jl("isPositive",e=>tu(e)&&e.value>0,"greater than zero"),Jl("isNegative",e=>tu(e)&&e.value<0,"less than zero"),Jl("isNonNegative",e=>tu(e)&&e.value>=0,"zero or greater"),Jl("isZero",e=>tu(e)&&0===e.value,"exactly 0"),Jl("isOne",e=>tu(e)&&1===e.value,"exactly 1"),Jl("isNonZero",e=>tu(e)&&0!==e.value,"a number that is provably not 0"),Jl("isNotZeroLiteral",e=>!(tu(e)&&0===e.value),"anything except a literal 0"),Jl("isPositiveInteger",e=>tu(e)&&Number.isInteger(e.value)&&e.value>0,"a whole number above 0"),Jl("isNegativeInteger",e=>tu(e)&&Number.isInteger(e.value)&&e.value<0,"a whole number below 0"),Jl("isEven",e=>tu(e)&&Number.isInteger(e.value)&&e.value%2==0,"a whole even number"),Jl("isOdd",e=>tu(e)&&Number.isInteger(e.value)&&1===Math.abs(e.value%2),"a whole odd number"),Jl("greaterThan",(e,t)=>tu(e)&&e.value>Number(t),"above a given value"),Jl("lessThan",(e,t)=>tu(e)&&e.value<Number(t),"below a given value"),Jl("isValue",(e,t)=>tu(e)&&e.value===Number(t),"equals a given number"),Jl("isNumeric",Ta,"contains no symbols: a constant (it need not fold to a number: 1 sin)"),Jl("hasSymbol",e=>!Ta(e),"mentions a symbol somewhere, so it is not just a number"),Jl("isVar",(e,t)=>e.type===ga&&e.token===String(t),"is exactly this symbol"),Jl("contains",(e,t)=>_a(e).includes(String(t)),"mentions this operand somewhere"),Jl("isFree",(e,t)=>!_a(e).includes(String(t)),"never mentions this operand"),Jl("hasOperation",(e,t)=>nu(e,String(t)),"uses this operation somewhere inside"),Jl("equals",(e,t)=>e.s===String(t),"is exactly this postfix expression");const ru=e=>e.type===va?null:e.token;function su(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 Ql(`bad requirement: ${JSON.stringify(e)}`)}Yl("freeOf",(e,t)=>{const n=ru(t);return null!==n&&!_a(e).includes(n)},"the first operand never mentions the second"),Yl("dependsOn",(e,t)=>{const n=ru(t);return null!==n&&_a(e).includes(n)},"the first operand does mention the second"),Yl("sameAs",(...e)=>e.every(t=>t.s===e[0].s),"these operands are structurally identical"),Yl("differs",(...e)=>new Set(e.map(e=>e.s)).size===e.length,"these operands are all different"),Yl("sameValue",(...e)=>e.every(e=>tu(e))&&e.every(t=>t.value===e[0].value),"these operands are the same number");const iu="simplify";class ou extends Error{constructor(e,t){super(t?`rule "${t}": ${e}`:e),this.name="RuleError",this.ruleId=t}}const au=/^[A-Za-z_][A-Za-z0-9_]*$/;function lu(e,t){if(Aa(e))return{literal:e.value};const n=e.token;if(n.startsWith("=")){const e=n.slice(1);if(""===e)throw new ou('"=" needs an operand after it',t);return{token:e}}if(!au.test(n))throw new ou(`"${n}" is not a usable slot name; use letters, digits and _`,t);if(pa(n))throw new ou(`slot name "${n}" collides with an operator`,t);return{name:n}}function uu(e){if(!Na(e))return[e];const t=e.args.map(uu),n=ha(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(Ma(e.op,s)),n.commutative&&2===s.length&&s[0].s!==s[1].s&&r.push(Ma(e.op,[s[1],s[0]])),r.length>=64)break;return r}function cu(e,t=[]){return"op"===e.kind?e.args.forEach(e=>cu(e,t)):"const"===e.kind&&e.free&&t.push(e.node.token),t}function hu(e){if(!e||"object"!=typeof e)throw new ou("rule must be a mapping");const t=e.id||e.name;if(!t)throw new ou("rule needs an id");if(!e.pattern)throw new ou("rule needs a pattern",t);if(void 0===e.output||null===e.output)throw new ou("rule needs an output",t);let n;try{n=Sa(String(e.pattern))}catch(e){if(e instanceof ya)throw new ou(`bad pattern: ${e.message}`,t);throw e}const r=Hl(n).map(e=>lu(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 ou('"when" must map slot names to lists of requirements',n);for(const[e,i]of Object.entries(s)){if(!t.has(e))throw new ou(`"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}=su(t),o=Kl(s);if(!o)throw new ou(`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 ou('"require" must be a list of relations',n);for(const e of s){const{name:s,args:i}=su(e),o=eu(s);if(!o)throw new ou(`unknown relation "${s}"`,n);if(i.length<2)throw new ou(`relation "${s}" needs at least two operands`,n);for(const e of i)if("string"==typeof e&&!t.has(e)&&au.test(e))throw new ou(`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=Sa(e)}catch(t){throw new ou(`bad output "${e}": ${t.message}`,n)}const s=e=>Na(e)?{kind:"op",op:e.op,args:e.args.map(s)}:Aa(e)?{kind:"const",node:e}:t.has(e.token)?{kind:"slot",name:e.token}:e.token.startsWith("=")?{kind:"const",node:xa(e.token.slice(1))}:{kind:"const",node:e,free:!0};return s(r)}(String(e.output),s,t),l=e.commutative?uu(n):[n],u=[],c=new Set;for(const e of l){const n=Vl(e),r=Hl(e).map(e=>lu(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):iu,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:Ea(n),bindings:u,freeSymbols:cu(a),source:e};for(const e of u)e.rule=h;return h}function pu(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!==iu&&(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 fu extends Error{constructor(e,t){super(null==t?e:`${e} (line ${t+1})`),this.name="YamlError",this.line=t}}class du{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 mu=e=>"-"===e||e.startsWith("- ");function gu(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:vu(t),rest:e.slice(r+1).trim()}}}return null}function vu(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 bu(e){const t=new du(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=wu(t,n.indent),s=t.peek();if(s&&"..."!==s.text&&"---"!==s.text)throw new fu(`unexpected content "${s.text}"`,s.n);return r}const yu=/^[|>][-+]?\d*$/;function wu(e,t){const n=e.peek();return!n||n.indent<t?null:mu(n.text)?xu(e,n.indent):gu(n.text)?function(e,t){const n={};for(;;){const r=e.peek();if(!r||r.indent!==t)break;const s=gu(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]=wu(e,r.indent):r&&r.indent===t&&mu(r.text)?n[i]=xu(e,t):n[i]=null}else yu.test(o)?n[i]=$u(e,o,t):n[i]=ku(o,r.n)}return n}(e,n.indent):(e.next(),yu.test(n.text)?$u(e,n.text,n.indent-1):ku(n.text,n.n))}function xu(e,t){const n=[];for(;;){const r=e.peek();if(!r||r.indent!==t||!mu(r.text))break;if(e.next(),"-"===r.text){const r=e.peek();n.push(r&&r.indent>t?wu(e,r.indent):null);continue}if(yu.test(r.text.slice(2).trim())){n.push($u(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(wu(e,i))}return n}function $u(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 ku(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=Mu(n);if(qu(n),n.i<n.text.length)throw new fu(`unexpected "${n.text.slice(n.i)}" in flow value`,t);return r}(n,t):'"'===n[0]||"'"===n[0]?vu(n):/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(n)?Number(n):n)}const qu=e=>{for(;e.i<e.text.length&&/\s/.test(e.text[e.i]);)e.i++};function Mu(e){qu(e);const t=e.text[e.i];return"["===t?function(e){e.i++;const t=[];for(;;){if(qu(e),e.i>=e.text.length)throw new fu("unterminated [",e.line);if("]"===e.text[e.i])return e.i++,t;if(t.push(Mu(e)),qu(e),","===e.text[e.i])e.i++;else if("]"!==e.text[e.i])throw new fu(`expected , or ] near "${e.text.slice(e.i)}"`,e.line)}}(e):"{"===t?function(e){e.i++;const t={};for(;;){if(qu(e),e.i>=e.text.length)throw new fu("unterminated {",e.line);if("}"===e.text[e.i])return e.i++,t;const n=String(Mu(e));if(qu(e),":"!==e.text[e.i])throw new fu(`expected : after "${n}"`,e.line);if(e.i++,t[n]=Mu(e),qu(e),","===e.text[e.i])e.i++;else if("}"!==e.text[e.i])throw new fu(`expected , or } near "${e.text.slice(e.i)}"`,e.line)}}(e):ku(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 fu("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 Au=/^(true|false|null|yes|no|on|off|~)$/i;function Nu(e){if(null==e)return"null";if("boolean"==typeof e)return e?"true":"false";if("number"==typeof e){if(!Number.isFinite(e))throw new fu(`cannot serialize ${e}`);return String(e)}const t=String(e);return function(e){return!!(""===e||/^\s|\s$/.test(e)||/[\u0000-\u001f\u007f]/.test(e)||/^[-?:,[\]{}#&*!|>'"%@`]/.test(e)||/: |\s#/.test(e)||Au.test(e)||/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(e))}(t)?JSON.stringify(t):t}const Su=e=>null==e||"object"!=typeof e;function Ou(e){return Array.isArray(e)?`[${e.map(Ou).join(", ")}]`:e&&"object"==typeof e?`{${Object.entries(e).map(([e,t])=>`${Nu(e)}: ${Ou(t)}`).join(", ")}}`:Nu(e)}function Eu(e){return Array.isArray(e)?!!e.every(e=>Su(e)||Array.isArray(e)&&e.every(Su))&&Ou(e).length<=72:!(!e||"object"!=typeof e)&&(Object.values(e).every(e=>Su(e)||Array.isArray(e)&&e.every(Su))&&Ou(e).length<=72)}function Iu(e){const t=[];return _u(e,0,t),t.length?t.join("\n")+"\n":""}function _u(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)Tu(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)ju(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+Nu(e))}(e,r,n)}}function Tu(e,t,n){const r=" ".repeat(t);if(null!==e&&"object"==typeof e&&!Eu(e)){const s=[];if(_u(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+"- "+Nu(e));else n.push(r+"- "+Ou(e))}function ju(e,t,n,r){const s=" ".repeat(n),i=Nu(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 Eu(t)?void r.push(`${s}${i}: ${Ou(t)}`):(r.push(`${s}${i}:`),void _u(t,Array.isArray(t)?n:n+2,r));r.push(`${s}${i}: ${Nu(t)}`)}}class zu{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:hu(e);if(this.rules.some(e=>e.id===t.id))throw new ou(`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 zu(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===iu?-1:t===iu?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=bu(e);return zu.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 ou('expected a list of rules, or a mapping with a "rules" list');const s=new zu;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 ou(`${i.length} rule(s) failed to compile:\n ${i.join("\n ")}`);return s.errors=i,s}toSpecs(){return this.rules.map(pu)}toYaml(){const e=this.toSpecs();return this.name?Iu({name:this.name,rules:e}):Iu(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 Lu(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(!Aa(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 Cu(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 Fu(e,t){return t.rule.priority-e.rule.priority||t.rule.depth-e.rule.depth}function Zu(e,t){const n=[];if(0===t.maxDepth)return n;for(const{key:r,slots:s}of function(e,t){const n=Ul(e,t),r=[];for(const e of n)e.key!==Bl&&r.push(e);return r}(e,t.maxDepth)){const e=t.candidates(r);if(e)for(const t of e){const e=Lu(t,s);e&&(Cu(t.rule,e)&&n.push({rule:t.rule,binding:t,key:r,bound:e}))}}return n.sort(Fu)}function Ru(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 Ma(e.op,e.args.map(e=>Ru(e,t)));default:throw new Error(`bad output template: ${JSON.stringify(e)}`)}}const Pu=4e5,Bu=()=>new La("a number too large to approximate"),Du=e=>e<0n?-e:e;class Wu{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 La("division by zero");return e*this.S/t}sqrt(e){if(e<0n)throw new La("the square root of a negative number is not real");return Da(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 La("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(Pu))throw Bu();if(t<-BigInt(Pu))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 La("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(Du(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(Du(e)>this.S)throw new La("arcsin of a number beyond ±1 is not real");return Du(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 Uu(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 La("the argument of 0 is undefined");return t>0n?e.pi/2n:-e.pi/2n}const Vu={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 La("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=Vu.abs(e,t);if(0n===n)throw new La("the log of 0 is undefined");return[e.ln(n),Uu(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=Vu.mul(e,s,i)),i=Vu.mul(e,i,i),n>>=1n;return r.n<0n?Vu.div(e,[e.S,0n],s):s}return Vu.exp(e,Vu.mul(e,n,Vu.ln(e,t)))},sinh:(e,t)=>(e.exp(t)-e.exp(-t))/2n,cosh:(e,t)=>(e.exp(t)+e.exp(-t))/2n},Hu={sin:(e,[t,n])=>[e.mul(e.sin(t),Vu.cosh(e,n)),e.mul(e.cos(t),Vu.sinh(e,n))],cos:(e,[t,n])=>[e.mul(e.cos(t),Vu.cosh(e,n)),-e.mul(e.sin(t),Vu.sinh(e,n))],tan:(e,t)=>Vu.div(e,Hu.sin(e,t),Hu.cos(e,t)),ln:(e,t)=>Vu.ln(e,t),sqrt:(e,t)=>Vu.exp(e,Vu.mul(e,[e.S/2n,0n],Vu.ln(e,t))),sinh:(e,[t,n])=>[e.mul(Vu.sinh(e,t),e.cos(n)),e.mul(Vu.cosh(e,t),e.sin(n))],cosh:(e,[t,n])=>[e.mul(Vu.cosh(e,t),e.cos(n)),e.mul(Vu.sinh(e,t),e.sin(n))]},Gu=e=>({q:e}),Xu=([e,t])=>0n===t?{f:e}:{z:[e,t]};function Qu(e,t,n){const r=e=>((e,t)=>t.z??[Ju(e,t),0n])(n,t[e]);switch(e.op){case"+":return Xu(Vu.add(r(0),r(1)));case"-":return Xu(Vu.sub(r(0),r(1)));case"neg":return Xu([-r(0)[0],-r(0)[1]]);case"*":return Xu(Vu.mul(n,r(0),r(1)));case"/":return Xu(Vu.div(n,r(0),r(1)));case"^":return Xu(Vu.pow(n,r(0),r(1),t[1].q));case"sqrt":return Xu(Hu.sqrt(n,r(0)));case"root":return Xu(Vu.pow(n,r(1),Vu.div(n,[n.S,0n],r(0)),t[0].q?.inv()));case"abs":return{f:Vu.abs(n,r(0))};case"arg":return{f:Uu(n,r(0)[1],r(0)[0])};case"re":return{f:r(0)[0]};case"im":return{f:r(0)[1]};case"conj":return Xu([r(0)[0],-r(0)[1]]);case"log":return Xu(Vu.div(n,Vu.ln(n,r(1)),Vu.ln(n,r(0))));default:{const s=Hu[e.op];if(!s||1!==t.length)throw new La(`no complex value for ${e.op}`);return Xu(s(n,r(0)))}}}function Ju(e,t){return t.q?e.fromQ(t.q):t.f}const Yu={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 La("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(Du(t)>=e.S)throw new La("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 Ku(e,t,n){if("num"===e.type)return Gu(Ba(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&&Ha.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?Ba(String(t)):null;if(!r)throw new La(`the value of ${e.token} is not a number`);return Gu(r)}throw new La(`${e.token} has no value`)}Ha.complex&&e.op.startsWith("\\:")&&ql[e.op.slice(2)]&&(e=Ma(ql[e.op.slice(2)],e.args));const r=e.args.map(e=>Ku(e,t,n));if(r.some(e=>e.z)||["re","im","conj","arg"].includes(e.op)||function(e,t){if(!Ha.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 Qu(e,r,t);const s=r.every(e=>e.q),i=e=>Ju(t,r[e]);switch(e.op){case"+":return s?Gu(r[0].q.add(r[1].q)):{f:i(0)+i(1)};case"-":return s?Gu(r[0].q.sub(r[1].q)):{f:i(0)-i(1)};case"neg":return r[0].q?Gu(r[0].q.neg()):{f:-r[0].f};case"*":return s?Gu(r[0].q.mul(r[1].q)):{f:t.mul(i(0),i(1))};case"/":return s?Gu(r[0].q.div(r[1].q)):{f:t.div(i(0),i(1))};case"^":return tc(t,r[0],r[1]);case"sqrt":return tc(t,r[0],Gu(Pa.HALF));case"root":return tc(t,r[1],r[0].q?Gu(r[0].q.inv()):{f:t.div(t.S,r[0].f)});case"abs":return r[0].q?Gu(r[0].q.abs()):{f:Du(r[0].f)};case"floor":return Gu(r[0].q?r[0].q.floor():new Pa(ec(r[0].f,t.S)));case"ceil":return Gu(r[0].q?r[0].q.ceil():new Pa(-ec(-r[0].f,t.S)));case"log":return{f:t.div(t.ln(i(1)),t.ln(i(0)))};case"atan2":return{f:Uu(t,i(0),i(1))};case"max":case"min":if(!r.length)throw new La(`${e.op} of nothing`);return s?Gu(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?Gu(r.reduce((e,t)=>e.add(t.q),Pa.ZERO)):{f:r.reduce((e,t,n)=>e+i(n),0n)};case"prod":return s?Gu(r.reduce((e,t)=>e.mul(t.q),Pa.ONE)):{f:r.reduce((e,n,r)=>t.mul(e,i(r)),t.S)};case"mean":if(!r.length)throw new La("mean of nothing");return s?Gu(r.reduce((e,t)=>e.add(t.q),Pa.ZERO).div(new Pa(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 La("mod 0 is undefined");return Gu(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 La("mod 0 is undefined");return{f:i(0)-t.mul(e,ec(t.div(i(0),e),t.S)*t.S)}}case"round":{if(!r[1].q?.isInteger)throw new La("round needs a whole number of places");const e=10n**Du(r[1].q.n),n=r[0].q??new Pa(i(0),t.S),s=r[1].q.sign>=0,o=(s?n.mul(new Pa(e)):n.div(new Pa(e))).add(Pa.HALF).floor();return Gu(s?o.div(new Pa(e)):o.mul(new Pa(e)))}case"!":{if(!r[0].q?.isInteger||r[0].q.sign<0)throw new La("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)&&Za(e)>Pu)throw Bu();return Gu(new Pa(e))}default:{const n=Yu[e.op];if(!n||1!==r.length)throw new La(`no numeric value for ${e.op}`);return{f:n(t,i(0))}}}}const ec=(e,t)=>{const n=e/t;return e<0n&&n*t!==e?n-1n:n};function tc(e,t,n){if(n.q&&n.q.isInteger){if(t.q)return Gu(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),Za(i)>Pu+4*e.P||Za(o)>8e5){if(s)return{f:0n};throw Bu()}r>>=1n}return{f:s?e.div(e.S,i):i}}const r=Ju(e,t);if(0n===r){if(n.q?n.q.sign>0:n.f>0n)return Gu(Pa.ZERO);throw new La("0 to a power that is not positive is undefined")}if(r<0n){if(n.q&&n.q.d%2n==1n){const t=tc(e,{f:-r},n).f;return{f:n.q.n%2n==0n?t:-t}}throw new La("a negative number to a fractional power is not real")}if(n.q&&1n===Du(n.q.n)&&n.q.d<=64n){const t=Da(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(Ju(e,n),e.ln(r)))}}function nc(e,t,n){const r=e<0n?"-":"",s=Du(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 rc({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 sc(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=Du(e.n)*10n**s/e.d;if(0n===i)return 1;for(;i%10n==0n;)i/=10n;return i.toString().length}function ic(e){let t=e.d;for(;t%2n==0n;)t/=2n;for(;t%5n==0n;)t/=5n;return 1n===t}function oc(e){const t=/^(-?[\d.]+)e(-?\d+)$/.exec(e);return t?Ma("*",[$a(t[1]),Ma("^",[$a("10"),$a(t[2])])]):$a(e)}function ac(e,{digits:t=15,scope:n}={}){if(!Number.isInteger(t)||t<1||t>1e5)throw new La("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 Wu(r),a=Ku(e,o,n);if(a.z){const e=uc(a.z,o,t);if(e.retry&&i<3){r+=e.retry;continue}return void 0===e.real?e:lc(e.real,o,t,null)}if(a.q&&a.q.isInteger&&Du(a.q.n).toString().length<=t)return{text:a.q.n.toString(),node:$a(a.q.n.toString()),number:Number(a.q.n),re:Number(a.q.n),im:0,exact:!0};const l=Ju(o,a);if(0n===l&&(!a.q||!a.q.isZero)&&i<3){s=null,r*=4;continue}const u=nc(l,o,t);if(s&&u.point<-10&&s.point-u.point>=(r-s.P)/2)return{text:"0",node:$a("0"),number:0,re:0,im:0,exact:!1};if(!(u.point<-10&&i<3)||s&&s.point===u.point)return lc(l,o,t,a.q);s={point:u.point,P:r},r+=10-u.point}throw new La("could not approximate")}function lc(e,t,n,r){const s=rc(nc(e,t,n));return{text:s,node:oc(s),number:Number(s),re:Number(s),im:0,exact:Boolean(r)&&ic(r)&&sc(r)<=n}}function uc([e,t],n,r){const s=10n**BigInt(Math.max(0,n.P-r-12)),i=e=>Du(e)>s;if(!i(t))return{real:e};const o=nc(t,n,r);if(o.point<-10&&i(t))return{retry:10-o.point};const a=rc(o),l="1"===a?"i":"-1"===a?"-i":`${a}i`,u="1"===a?xa("i"):Ma("*",[oc(a.replace(/^-/,"")),xa("i")]);if(!i(e))return{text:l,node:a.startsWith("-")?Ma("neg",[u]):u,number:NaN,re:0,im:Number(a),exact:!1};const c=rc(nc(e,n,r)),h=a.startsWith("-"),p="1"===a.replace(/^-/,"")?xa("i"):Ma("*",[oc(a.replace(/^-/,"")),xa("i")]);return{text:`${c} ${h?"-":"+"} ${l.replace(/^-/,"")}`,node:Ma(h?"-":"+",[oc(c),p]),number:NaN,re:Number(c),im:Number(a),exact:!1}}function cc(e,t={}){const n=e=>(e=>0===Zl(e).size)(e)?"num"===e.type&&/^-?\d+$/.test(e.token)?e:ac(e,t).node:Na(e)?Ma(e.op,e.args.map(n)):e;return n(e)}const hc={variable:null},pc=(e,t)=>null!==t&&Zl(e).has(t);function fc(e){if("num"===e.type)return Ba(e.token);if(Na(e)&&"/"===e.op&&e.args.every(e=>"num"===e.type)){const t=Ba(e.args[0].token),n=Ba(e.args[1].token);return t&&n&&!n.isZero?t.div(n):null}return null}const dc=e=>0===Zl(e).size;function mc(e,t,n){const r=function(e){const t=Il(e);return"num"===t.k?t.q.isZero?t.q:null:"atom"===t.k&&"sym"===t.node.type&&"pi"===t.node.token?Ba("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(Ba(s).div(Ba(i))))}function gc(e){if(!dc(e))return NaN;try{const{number:t}=ac(e,{digits:30});return Math.sign(t)}catch{return NaN}}function vc(){Kl("hasVariable")||(Jl("hasVariable",e=>pc(e,hc.variable),"mentions the variable being solved for"),Jl("freeOfVariable",e=>null!==hc.variable&&!pc(e,hc.variable),"does not mention the variable being solved for"),Jl("isRational",e=>null!==fc(e),"an exact number: 3, -2, 1/2"),Jl("isWhole",e=>fc(e)?.isInteger??!1,"a whole number (any size)"),Jl("isEvenWhole",e=>{const t=fc(e);return Boolean(t?.isInteger&&t.n%2n==0n)},"an even whole number"),Jl("isOddWhole",e=>{const t=fc(e);return Boolean(t?.isInteger&&t.n%2n!=0n)},"an odd whole number"),Jl("isPositiveRational",e=>(fc(e)?.sign??0)>0,"an exact number above 0"),Jl("isNegativeRational",e=>(fc(e)?.sign??0)<0,"an exact number below 0"),Jl("isConstant",dc,"has no unknowns (numbers, π and e only)"),Jl("notOne",e=>{const t=fc(e);return!t||!t.isOne},"anything except the number 1"),Jl("notMinusOne",e=>{const t=fc(e);return!t||!t.equals(Ba("-1"))},"anything except the number -1"),Jl("hasMinusSign",e=>function(e){const t=Il(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"),Jl("piMultipleAtLeast",(e,t)=>mc(e,t,e=>e>=0),"a multiple of π, at least k·π"),Jl("piMultipleAbove",(e,t)=>mc(e,t,e=>e>0),"a multiple of π, above k·π"),Jl("piMultipleBelow",(e,t)=>mc(e,t,e=>e<0),"a multiple of π, below k·π"),Jl("piMultipleAtMost",(e,t)=>mc(e,t,e=>e<=0),"a multiple of π, at most k·π"),Jl("isPositiveConstant",e=>gc(e)>0,"no unknowns, and above 0 (e, π, √2, 3)"),Jl("isNegativeConstant",e=>gc(e)<0,"no unknowns, and below 0"),Jl("hasImaginaryPart",e=>{if(!Ha.complex)return!1;const t=xl(Il(e));return Boolean(t)&&!("num"===t.im.k&&t.im.q.isZero)},"complex mode: has a nonzero imaginary part (unknowns count as real)"),Jl("isSymbolNode",e=>"sym"===e.type&&!Va.has(e.token),"a single unknown such as x"))}function bc(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=Sa(e),n=e=>"num"===e.type||("sym"===e.type?e.token.startsWith("="):e.args.every(n)),r=e=>"sym"===e.type?xa(e.token.slice(1)):"num"===e.type?e:Ma(e.op,e.args.map(r)),s=e=>"sym"===e.type?xa(`=${e.token}`):"num"===e.type?e:Ma(e.op,e.args.map(s)),i=e=>"op"!==e.type?e:n(e)?s(_l(r(e))):Ma(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 zu.fromSpecs(n,{strict:!0})}function yc(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 wc=e=>Na(e)&&("+"===e.op||"-"===e.op),xc=e=>Na(e)&&("*"===e.op||"/"===e.op);function*$c(e,t,{order:n="pre"}={}){for(const r of function(e,t,{order:n="post"}={}){const r=[];for(const{node:s,path:i}of ja(e,n))for(const e of Zu(s,t))r.push({...e,node:s,path:i});return r}(e,t,{order:n})){const t=Ru(r.rule.outputTemplate,r.bound);yield{rule:r.rule,bound:r.bound,path:r.path,before:r.node,after:t,next:()=>_l(za(e,r.path,t))}}for(const{node:r,path:s}of ja(e,n)){const n=wc(r);if(!n&&!xc(r))continue;const i=n?Rl(Il(r)):Pl(Il(r));if(i.length<3)continue;const o=n?pl:dl;for(let n=0;n<i.length;n++)for(let r=n+1;r<i.length;r++){const a=Ll(o([i[n],i[r]]));for(const l of Zu(a,t)){const t=Ru(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:()=>_l(za(e,s,Ll(o([Il(t),...u]))))}}}}}function kc(e,t,{format:n,order:r="pre",maxSteps:s=200,variable:i=null}={}){const o=hc.variable;hc.variable=i;try{let i=_l(e);const o=new Set([i.s]),a=[];for(let e=0;e<s;e++){let e=null;for(const n of $c(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:yc(s.rule,s.bound,_l(s.after),n)}),i=l,o.add(i.s)}return{node:i,steps:a}}finally{hc.variable=o}}const qc={full:[],normal:["hidden"],brief:["hidden","tidy","identity","value","split","base","arithmetic"]},Mc=(e,t)=>"all"===t||"*"===t||Array.isArray(t)&&t.some(t=>t===e.id||e.tags?.includes(t));function Ac(e){if(!1===e)return null;if(void 0===e||!0===e)return{show:"all",hide:qc.normal,explain:!0};if("string"==typeof e){if(!qc[e])throw new Error(`steps: "${e}" is not one of ${Object.keys(qc).join(", ")}`);return{show:"all",hide:qc[e],explain:!0}}const t=e.detail??"normal";if(!qc[t])throw new Error(`steps.detail: "${t}" is not one of ${Object.keys(qc).join(", ")}`);return{show:e.show??"all",hide:[...qc[t],...e.hide??[]],explain:e.explain??!0}}function Nc(e,t){if(!t)return[];const n=[];let r=null;for(const s of e){if(!(Mc(s,t.show)&&!Mc(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&&Mc(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 Sc=Ja(Pa.ONE),Oc=(e,t)=>"atom"===e.k&&"sym"===e.node.type&&e.node.token===t;function Ec(e){switch(e.k){case"num":default:return e;case"atom":return"op"===e.node.type?Ol(e.node.op,e.node.args.map(e=>Ec(Il(e)))):e;case"add":return pl(Rl(e).map(Ec));case"mul":{let t=[Ja(e.c)];for(const n of e.fs){const e=Ec(n.b);if("add"===e.k&&tl(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=Ic(t,Rl(e));else t=Ic(t,[gl(e,n.e)])}return pl(t)}}}function Ic(e,t){const n=[];for(const r of e)for(const e of t)n.push(dl([r,e]));return Rl(pl(n))}function _c(e,t){const n=new Map;for(const r of Rl(Ec(e))){const{coef:e,rest:s}=hl(r);let i=0;const o=[Ja(e)];for(const e of s?Pl(s):[]){const{b:n,e:r}="mul"===e.k&&1===e.fs.length&&e.c.isOne?e.fs[0]:{b:e,e:Sc};if(Oc(n,t)){if(!tl(r)||!r.q.isInteger||r.q.sign<0)return null;i+=Number(r.q.n)}else{if(Tc(n,t)||Tc(r,t))return null;o.push(e)}}n.set(i,pl([n.get(i)??Ja(Pa.ZERO),dl(o)]))}for(const[e,t]of n)tl(t)&&t.q.isZero&&n.delete(e);return n}const Tc=(e,t)=>Zl(Ll(e)).has(t);function jc(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)??Ja(Pa.ZERO);if(!tl(t))return null;n.push(t.q)}return n}function zc(e,t){const n=Il(xa(t));return pl(e.map((e,t)=>dl([Ja(e),ml(n,Ja(Pa.of(t)))])))}const Lc=e=>{const t=e.slice();for(;t.length>1&&t[t.length-1].isZero;)t.pop();return t},Cc=(e,t)=>e.reduceRight((e,n)=>e.mul(t).add(n),Pa.ZERO);function Fc(e,t){const n=e.length-1,r=new Array(n);let s=Pa.ZERO;for(let i=n;i>=1;i--)s=e[i].add(s.mul(t)),r[i-1]=s;return r}function Zc(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 Rc(e){let t=Lc(e);const n=[];for(;t.length>1&&t[0].isZero;)n.push(Pa.ZERO),t=t.slice(1);if(t.length<=1)return{roots:n,rest:t};const r=t.reduce((e,t)=>e*t.d/Ra(e,t.d),1n),s=t.map(e=>e.n*r/e.d),i=Zc(s[0]),o=Zc(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 Pa(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&&Cc(t,e).isZero;)n.push(e),t=Fc(t,e);return{roots:n.sort((e,t)=>e.compare(t)),rest:t}}function Pc(e){if("num"===e.k)return{coef:e.q,factors:[],notes:[]};if("atom"===e.k)return{coef:Pa.ONE,factors:[{base:e,exp:Sc}],notes:[]};if("mul"===e.k){let t=e.c;const n=[],r=[];for(const s of e.fs)if("add"===s.b.k&&tl(s.e)&&s.e.q.isInteger){const e=Pc(s.b);t=t.mul(e.coef.pow(s.e.q.n));for(const t of e.factors)n.push({base:t.base,exp:dl([t.exp,s.e])});r.push(...e.notes)}else n.push({base:s.b,exp:s.e});return Bc(t,n,r)}return function(e){const t=Rl(e),n=[],r=t.map(e=>{const{coef:t,rest:n}=hl(e);return{coef:t,fs:n?Pl(n).map(Wc):[]}}),s=r.reduce((e,t)=>({n:Ra(e.n,t.coef.n),d:e.d*t.coef.d/Ra(e.d,t.coef.d)}),{n:0n,d:1n});let i=new Pa(s.n||1n,s.d);Dc(e)<0&&(i=i.neg());const o=[];for(const e of r[0].fs){if(!tl(e.e)||e.e.q.sign<=0)continue;let t=e.e.q;const n=sl(e.b);let s=!0;for(const e of r.slice(1)){const r=e.fs.find(e=>sl(e.b)===n&&tl(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:Ja(t)})}let a=e;if(!i.isOne||o.length){const e=dl([Ja(i),...o.map(e=>gl(e.base,e.exp))]);a=pl(t.map(t=>dl([t,ml(e,Ja(Pa.MINUS_ONE))]))),n.push({id:"factor.common",values:{common:e}})}const l="add"===a.k?function(e,t){const n=[...Uc(e)];for(const r of n){const s=jc(_c(e,r));if(!s||s.length<3)continue;if(1!==n.length)break;const{roots:i,rest:o}=Rc(s);if(!i.length)break;const a=[];let l=o[o.length-1]??Pa.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=zc([new Pa(-e.n),new Pa(e.d)],r);a.push({base:n,exp:Sc}),l=l.div(new Pa(e.d)),t.push({id:"factor.root",values:{root:Ja(e),factor:n}})}if(u.length>1){const e=u.reduce((e,t)=>e*t.d/Ra(e,t.d),1n),t=u.map(t=>t.mul(new Pa(e))),n=t.reduce((e,t)=>Ra(e,t.n),0n)||1n;l=l.mul(new Pa(n,e)),a.push({base:zc(t.map(e=>e.div(new Pa(n))),r),exp:Sc})}return Bc(l,a,[])}const r=Rl(e);if(2===r.length){const[e,n]=r;for(const r of[2,3]){const s=Vc(e,r),i=Vc(Ml(n),r),o=3===r?Vc(n,r):null;if(s&&i&&2===r){t.push({id:"factor.squares",values:{a:s,b:i}});const e=Pc(pl([s,Ml(i)])),n=Pc(pl([s,i]));return Bc(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=pl(n<0?[s,Ml(e)]:[s,e]),a=pl([ml(s,Ja(Pa.of(2))),n<0?dl([s,e]):Ml(dl([s,e])),ml(e,Ja(Pa.of(2)))]),l=Pc(r);return Bc(l.coef,[...l.factors,{base:a,exp:Sc}],l.notes)}}}return{coef:Pa.ONE,factors:[{base:e,exp:Sc}],notes:[]}}(a,n):Pc(a);return Bc(i.mul(l.coef),[...o,...l.factors],[...n,...l.notes.filter(e=>!n.includes(e))])}(e)}function Bc(e,t,n){const r=new Map;for(const e of t){const t=sl(e.base),n=r.get(t);n?n.exp=pl([n.exp,e.exp]):r.set(t,{...e})}return{coef:e,factors:[...r.values()].filter(e=>!(tl(e.exp)&&e.exp.q.isZero)),notes:n}}const Dc=e=>hl(Rl(e)[0]).coef.sign;const Wc=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length?{b:e.fs[0].b,e:e.fs[0].e}:{b:e,e:Sc},Uc=e=>Zl(Ll(e));function Vc(e,t){const{coef:n,rest:r}=hl(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 Pa(r,s):null}(n,t);if(!s)return null;const i=[Ja(s)];for(const e of r?Pl(r).map(Wc):[]){if(!tl(e.e))return null;const n=e.e.q.div(Pa.of(t));if(!n.isInteger)return null;i.push(gl(e.b,Ja(n)))}return dl(i)}function Hc({coef:e,factors:t}){const n=[],r=[];for(const e of t){const t=tl(e.exp)&&e.exp.q.sign<0,s=t?Ja(e.exp.q.neg()):e.exp,i=Ll(gl(e.base,s));(t?r:n).push(i)}const s=e=>e.reduce((e,t)=>e?Ma("*",[e,t]):t,null),i=e.n<0n?-e.n:e.n;let o=n.length?s(1n===i?n:[Ll(Ja(new Pa(i))),...n]):Ll(Ja(new Pa(i)));return e.n<0n&&(o=Ma("neg",[o])),1n!==e.d&&r.unshift(Ll(Ja(new Pa(e.d)))),r.length?Ma("/",[o,s(r)]):o}function Gc(e){if("mul"!==e.k)return{num:e,den:Sc};const t=[Ja(new Pa(e.c.n))],n=[Ja(new Pa(e.c.d))];for(const r of e.fs)tl(r.e)&&r.e.q.sign<0?n.push(gl(r.b,Ja(r.e.q.neg()))):t.push(gl(r.b,r.e));return{num:dl(t),den:dl(n)}}function Xc(e){if("add"!==e.k)return Gc(e);const t=Rl(e).map(Gc),n=new Map;let r=1n;for(const e of t){const{coef:t,rest:s}=hl(e.den);r=r*t.n/Ra(r,t.n);for(const e of s?Pl(s).map(Wc):[]){const t=sl(e.b),r=n.get(t);(!r||tl(e.e)&&tl(r.e)&&e.e.q.compare(r.e.q)>0)&&n.set(t,e)}}const s=dl([Ja(new Pa(r)),...[...n.values()].map(e=>gl(e.b,e.e))]);if(tl(s)&&s.q.isOne)return{num:e,den:Sc};const i=Ec(pl(t.map(e=>dl([e.num,s,ml(e.den,Ja(Pa.MINUS_ONE))]))));return{num:i,den:s}}function Qc(e){const{num:t,den:n}=Xc(e);if(tl(n)&&n.q.isOne)return null;const r=Pc(t),s=Pc(n),i=new Set(r.factors.map(e=>sl(e.base))),o=s.factors.filter(e=>i.has(sl(e.base))),a=[...r.factors,...s.factors.map(e=>({base:e.base,exp:Ml(e.exp)}))];return{...Bc(r.coef.div(s.coef),a,[...r.notes,...s.notes]),canceled:o.map(e=>e.base)}}const Jc=(e,t)=>Ma("=",[e,t]),Yc=_l(Ma("+",[xa("x"),Ma("neg",[xa("x")])])),Kc=e=>Na(e)&&"="===e.op;function eh(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=Kc(t)?t:Jc(t,Yc),a=Jc(_l(o.args[0]),_l(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,oh(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=>kc(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:rh(o,n,t);r?i("solve.reject","Check the answer",["check"],Jc(xa(n),t),Jc(xa(n),t),{value:t,reason:r}):h.push(t)}return h.sort(th),{solutions:h,unsolved:u,steps:s,always:u.some(e=>e.always)}}function th(e,t){const n=nh(e),r=nh(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 nh(e){if(Zl(e).size)return null;try{const{re:t,im:n}=ac(e,{digits:20});return{re:t,im:n}}catch{return null}}function rh(e,t,n){const[r,s]=e.args,i=new Set([...Zl(r),...Zl(s),...Zl(n)]);if(i.delete(t),i.size)return null;const o=e=>sh(e,t,n);try{const e=ac(o(r),{digits:40}),t=ac(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 sh(e,t,n){return"sym"===e.type?e.token===t?n:e:Na(e)?Ma(e.op,e.args.map(e=>sh(e,t,n))):e}const ih=24;function oh(e,t,n,r,s,i,o,a){if(a>ih)return fh(e,t,n,r,s,i,o);const l=function(e){const t=[],n=e=>{if(Na(e)&&"|"===e.op)return void e.args.forEach(n);if(!Kc(e))return void t.push(e);const r=e.args[1],s=ja(r,"pre").find(({node:e})=>Na(e)&&"pm"===e.op);if(!s)return void t.push(e);const i=s.node.args[0],o=_l(za(r,s.path,i)),a=_l(za(r,s.path,Ma("neg",[i])));n(Jc(e.args[0],o)),a.s!==o.s&&n(Jc(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?Ma("|",[e,t]):t,null));for(const t of l)oh(e,t,n,r,s,i,o,a+1);return}if(1===l.length&&l[0].s!==t.s)return oh(e,l[0],n,r,s,i,o,a+1);const[u,c]=t.args;if("sym"===u.type&&u.token===n&&!Tc(Il(c),n))return void i.push(c);const h=pl([Il(u),Ml(Il(c))]);if(!Tc(h,n))return tl(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=Rl(h).filter(e=>Tc(e,n)),f=Rl(h).filter(e=>!Tc(e,n)),d=pl(p),m=Ml(pl(f));if(Ha.complex){const l=_c(h,n);if(l&&[...l.values()].every(e=>!Tc(e,n))&&Math.max(...l.keys())>=2){const u=Jc(Ll(h),Yc);return u.s!==t.s&&s("solve.one-side","Everything on one side",["move"],t,u,{v:n}),hh(e,h,l,n,r,s,i,o,a,u)}}if(1===p.length)return ah(e,t,d,m,n,r,s,i,o,a);const g=Jc(Ll(h),Yc),v=_c(h,n);if(v&&[...v.values()].every(e=>!Tc(e,n))&&Math.max(...v.keys())>=2)return g.s!==t.s&&s("solve.one-side","Everything on one side",["move"],t,g,{v:n}),hh(e,h,v,n,r,s,i,o,a,g);const b=Pc(h),y=b.factors.filter(e=>Tc(e.base,n)&&!(tl(e.exp)&&e.exp.q.sign<0));if(y.length>=2||1===y.length&&b.factors.length>1){const l=Jc(Hc(b),Yc);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=>Jc(Ll(e.base),Yc));u.length>1&&s("solve.zero-product","A product is zero when a factor is",["split"],l,u.reduce((e,t)=>e?Ma("|",[e,t]):t,null),{});for(const t of u)oh(e,t,n,r,s,i,o,a+1);return}const w=Xc(h);if(Tc(w.den,n)){const l=Jc(Ll(w.num),Yc);return s("solve.clear-denominator","Clear the denominator",["move"],t,l,{den:Ll(w.den)}),oh(e,l,n,r,s,i,o,a+1)}const x=p.filter(e=>!ch(e,n));if(1===x.length&&/\b(sqrt|root|abs)\b/.test(Ll(x[0]).s))return ah(e,t,x[0],Ml(pl(Rl(h).filter(e=>e!==x[0]))),n,r,s,i,o,a);const $=function(e,t){const n=Ll(e),r=new Map;for(const{node:e}of ja(n,"pre"))if(Na(e)&&Zl(e).has(t))if("^"!==e.op||Zl(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=Il(e.args[1]),{coef:s,rest:i}=hl(n);if(i&&s.isInteger&&Ll(i).s===t){const n=Ll(ml(Il(e.args[0]),Il(xa(t))));r.set(n.s,n)}}const s="u"===t?"w":"u";for(const e of r.values()){const r=ph(n,e,t,s);if(!r||Zl(r).has(t))continue;const i=Il(r),o=_c(i,s);if(o&&Math.max(...o.keys())>=1)return{kernel:Il(e),poly:i,symbol:s}}return null}(h,n);if($){const t=$.symbol;s("solve.substitute","Substitute",["substitute"],g,Jc(Ll($.poly),Yc),{u:xa(t),kernel:Ll($.kernel)});const l=[];oh(e,Jc(Ll($.poly),Yc),t,r,s,l,o,a+1);for(const t of l)oh(e,Jc(Ll($.kernel),t),n,r,s,i,o,a+1);return}return fh(e,g,n,r,s,i,o)}function ah(e,t,n,r,s,i,o,a,l,u){let c=Jc(Ll(n),Ll(r));c.s!==t.s&&o("solve.move","Move the terms",["move"],t,c,{v:s});const{coef:h,rest:p}=hl(n),f=p?Pl(p):[],d=dl([Ja(h),...f.filter(e=>!Tc(e,s))]);if(!tl(d)||!d.q.isOne){const e=dl(f.filter(e=>Tc(e,s))),t=Jc(Ll(e),Ll(Al(r,d))),n=tl(d)&&!d.q.isInteger&&(1n===d.q.n||-1n===d.q.n);o(n?"solve.multiply":"solve.divide",n?"Multiply both sides":"Divide both sides",["move"],c,t,{by:Ll(n?Ja(d.q.inv()):d),v:s}),c=t}if("sym"===c.args[0].type&&c.args[0].token===s)return void a.push(c.args[1]);const m=Il(c.args[1]);if(tl(m)&&m.q.isZero){const t=Il(c.args[0]),n=Pl(t).filter(e=>Tc(e,s)&&!lh(e));if(n.length>1||n.length<Pl(t).filter(e=>Tc(e,s)).length){const t=n.map(e=>Jc(Ll(uh(e)),Yc));o("solve.zero-product","A product is zero when a factor is",["split"],c,t.reduce((e,t)=>e?Ma("|",[e,t]):t,null),{});for(const n of t)oh(e,n,s,i,o,a,l,u+1);return}}const g=kc(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),oh(e,g.node,s,i,o,a,l,u+1)):fh(e,c,s,i,o,a,l)}const lh=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&tl(e.fs[0].e)&&e.fs[0].e.q.sign<0,uh=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&tl(e.fs[0].e)&&e.fs[0].e.q.sign>0?e.fs[0].b:e,ch=(e,t)=>{const n=_c(e,t);return Boolean(n)&&[...n.values()].every(e=>!Tc(e,t))};function hh(e,t,n,r,s,i,o,a,l,u){const c=Math.max(...n.keys()),h=jc(n);if(Ha.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=ml(Ja(t.abs()),Ja(new Pa(1n,BigInt(c)))),s=[];for(let r=0;r<c;r++){const i=dl([Ja(new Pa(BigInt((t.sign<0?1:0)+2*r),BigInt(c))),Il(xa("pi"))]),o=Ma("*",[Ll(n),Ma("+",[Ma("cos",[Ll(i)]),Ma("*",[xa("i"),Ma("sin",[Ll(i)])])])]);s.push(kc(o,e.set.view("simplify"),{format:e.format}).node)}return i("solve.roots","All n roots",["complex"],u,s.map(e=>Jc(xa(r),e)).reduce((e,t)=>e?Ma("|",[e,t]):t),{v:r,n:String(c),last:String(c-1),r:Ll(Ja(t))}),void o.push(...s)}if(h){const{roots:n}=Rc(h);if(n.length){const n=Pc(t),c=Jc(Hc(n),Yc);if(n.factors.length>1||n.factors.some(e=>!(tl(e.exp)&&e.exp.q.isOne))){i("solve.factor","Factor",["factor"],u,c,{});const t=n.factors.filter(e=>Tc(e.base,r)).map(e=>Jc(Ll(e.base),Yc));t.length>1&&i("solve.zero-product","A product is zero when a factor is",["split"],c,t.reduce((e,t)=>e?Ma("|",[e,t]):t,null),{});for(const n of t)oh(e,n,r,s,i,o,a,l+1);return}}}if(2===c){const e=n.get(2),t=n.get(1)??Ja(Pa.ZERO),s=n.get(0)??Ja(Pa.ZERO),a=pl([ml(t,Ja(Pa.of(2))),dl([Ja(Pa.of(-4)),e,s])]);if(tl(a)&&a.q.sign<0&&!Ha.complex)return void i("solve.no-real","No real solutions",["quadratic"],u,u,{D:Ll(a)});const l=dl([Ja(Pa.of(2)),e]),c=ml(a,Ja(Pa.HALF)),h=Ll(Al(pl([Ml(t),c]),l)),p=Ll(Al(pl([Ml(t),Ml(c)]),l)),f=h.s===p.s?Jc(xa(r),h):Ma("|",[Jc(xa(r),h),Jc(xa(r),p)]);return i(Ha.complex&&tl(a)&&a.q.sign<0?"solve.quadratic-complex":"solve.quadratic","The quadratic formula",["quadratic"],u,f,{a:Ll(e),b:Ll(t),c:Ll(s),D:Ll(a),root:Ll(c),v:r}),o.push(h),void(p.s!==h.s&&o.push(p))}return fh(e,u,r,s,i,o,a)}function ph(e,t,n,r){if(e.s===t.s)return xa(r);if(!Na(e))return e;if("^"===e.op&&"^"===t.op&&e.args[0].s===t.args[0].s){const t=Il(e.args[1]),{coef:s,rest:i}=hl(t);if(i&&Ll(i).s===n&&s.isInteger)return Ma("^",[xa(r),Ll(Ja(s))])}return Ma(e.op,e.args.map(e=>ph(e,t,n,r)))}function fh(e,t,n,r,s,i,o){if(r.approximate){const e="number"==typeof r.approximate?r.approximate:15,o=Il(Ma("-",[t.args[0],t.args[1]])),a=Ha.complex?jc(_c(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=dh(e);if(0===t)return n;const r=Ma("*",[dh(Math.abs(t)),xa("i")]);return 0===e?t<0?Ma("neg",[r]):r:Ma(t<0?"-":"+",[n,r])})}(a.map(e=>e.toNumber()),Math.min(e,14)):function(e,t,n){const r=Il(Ma("-",[e.args[0],e.args[1]])),s=Ll(r),i=e=>{try{return ac(sh(s,t,mh(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(mh(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(mh(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=>Jc(xa(n),e)).reduce((e,t)=>e?Ma("|",[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 dh=e=>$a(String(e).includes("e")?e.toFixed(20):String(e)),mh=e=>$a(Number.isInteger(e)?String(e):e.toFixed(17));const gh=(e,t)=>Ma("int",[e,"string"==typeof t?xa(t):t]);function vh(e,t,n,r=0){if(r>6)throw new La("integration went too deep");const s=[],i=e.set.view("integrate"),o=kc(t,e.set.view("simplify"),{format:e.format});s.push(...o.steps);let a=_l(gh(o.node,n));for(let t=0;t<40;t++){const t=kc(a,i,{format:e.format});s.push(...t.steps),a=t.node;const n=ja(a,"pre").find(({node:e})=>{return Na(t=e)&&"int"===t.op&&2===t.args.length;var t});if(!n)return{node:a,steps:s};const o=bh(e,n.node,r);if(!o)throw new La(`no rule for ∫ ${e.format(n.node.args[0])} d${n.node.args[1].token}`);s.push(...o.steps),a=_l(za(a,n.path,o.node))}throw new La("integration did not finish")}function bh(e,t,n){const[r,s]=t.args,i=s.token,o=Il(r),a=function(e,t){const{num:n,den:r}=Xc(e),s=Pc(n),i=Pc(r),o=s.coef.div(i.coef);if(o.isOne||!Tc(e,t))return null;const a=dl([...s.factors.map(e=>gl(e.base,e.exp)),...i.factors.map(e=>gl(e.base,Ml(e.exp)))]);return{c:o,rest:a}}(o,i);if(a){const n=Ma("*",[Ll(Ja(a.c)),gh(Ll(a.rest),s)]);return{node:n,steps:[e.step("integrate.constant","Take the number out",["split"],t,n,{c:Ll(Ja(a.c))})]}}const l=Ec(o);if(Ll(l).s!==r.s&&"add"===l.k){const n=gh(Ll(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 ja(e,"pre")){if(!Na(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||!Zl(r).has(t))continue;const e=_c(Il(r),t);if(!e||1!==Math.max(...e.keys()))continue;const s=e.get(1);Tc(s,t)||tl(s)&&s.q.isZero||n.set(r.s,{node:r,a:s})}}for(const r of n.values()){if(!Zl(yh(e,r.node,xa("§"))).has(t))return r}return null}(r,i);if(u){const s="u"===i?"t":"u",o=yh(r,u.node,xa(s));if(!Zl(o).has(i)){const r=vh(e,_l(o),s,n+1),a=_l(sh(r.node,s,u.node)),l=Ll(Al(Il(a),u.a));return{node:l,steps:[e.step("integrate.substitute","Substitute",["substitute"],t,_l(gh(o,s)),{u:xa(s),inside:u.node,a:Ll(u.a),v:i}),...r.steps,e.step("integrate.back","Substitute back",["substitute"],r.node,l,{u:xa(s),inside:u.node})]}}}const c=function(e,t,n,r){const{num:s,den:i}=Xc(n);if(!Tc(i,r))return null;const o=jc(_c(s,r)),a=jc(_c(i,r));if(!o||!a||a.length<2)return null;const l=Il(xa(r)),u=e=>zc(e,r);if(o.length>=a.length){const{q:n,r:s}=function(e,t){const n=Lc(t);let r=Lc(e);const s=n[n.length-1];if(s.isZero)throw new La("division by the zero polynomial");const i=new Array(Math.max(1,r.length-n.length+1)).fill(Pa.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=Lc(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:Lc(i),r:r}}(o,a),i=gh(Ll(pl([u(n),Al(u(s),u(a))])),xa(r));return{node:i,steps:[e.step("integrate.divide","Divide the polynomials",["divide"],t,i,{})]}}const{roots:c,rest:h}=Rc(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?[Pa.ZERO]:e.slice(1).map((e,t)=>e.mul(Pa.of(t+1))))(a),d=c.map(e=>Al(Ja(Cc(o,e).div(Cc(f,e))),pl([l,Ja(e.neg())]))),m=gh(Ll(pl(d)),xa(r));return{node:m,steps:[e.step("integrate.partial-fractions","Partial fractions",["partial-fractions"],t,m,{})]}}(e,t,o,i);return c||function(e,t,n,r,s){if(s>=6)return null;const i=Pl(n),o=i.filter(e=>wh(e,r)||!Tc(e,r)),a=i.filter(e=>!o.includes(e));if(1!==a.length)return null;const l=dl(o),u=a[0];if(!Tc(l,r))return null;const c=Ll(u),h=Na(c)?c.op:"";let p,f,d;"ln"===h||"arctan"===h||"arcsin"===h?(p=u,f=l):(p=l,f=u);try{d=vh(e,Ll(f),r,s+1)}catch{return null}const m=Il(e.differentiate(Ll(p),r)),g=dl([p,Il(d.node)]),v=gh(Ll(dl([m,Il(d.node)])),xa(r)),b=_l(Ma("-",[Ll(g),v]));return{node:b,steps:[e.step("integrate.parts","Integration by parts",["parts"],t,b,{u:Ll(p),dv:Ll(f),V:d.node,du:Ll(m),v:r})]}}(e,t,o,i,n)}function yh(e,t,n){return e.s===t.s?n:Na(e)?Ma(e.op,e.args.map(e=>yh(e,t,n))):e}const wh=(e,t)=>{const n=_c(e,t);return Boolean(n)&&[...n.values()].every(e=>!Tc(e,t))&&Math.max(...n.keys())>=1};function xh(e,t,n,r,s,i){for(const e of[r,s])if(Zl(e).has("∞")||/∞|infinity/.test(e.s))throw new La("integrals to infinity need limits, which this CAS does not do yet");if(i&&!Zl(r).size&&!Zl(s).size){const o=ac(r,{digits:20}).number,a=ac(s,{digits:20}).number,l=[...Zl(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 ja(e,"pre").forEach(({node:e})=>{if(!Na(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&&Na(e.args[1])&&"neg"===e.args[1].op?s=e.args[0]:r[e.op]&&(s=Ma(r[e.op],[e.args[0]])),s&&Zl(s).has(t)&&!n.some(e=>e.s===s.s)&&n.push(s)}),n}(i,n)){let i=[];try{i=e.solve(Ma("=",[o,$a("0")]),n,{steps:!1}).solutions}catch{continue}for(const o of i){const i=ac(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 La(`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=ac(_l(sh(t,n,o)),{digits:15}).number}catch{}if(!Number.isFinite(a))throw new La(`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=ac(sh(i,n,$a(t.toFixed(15))),{digits:15}).number;if(!Number.isFinite(e))throw new La("not finite")}catch(e){throw new La(`the integrand has no value at ${n} = ${t.toPrecision(6)}, between the limits, so F(b) - F(a) would be wrong`)}}}const o=e=>_l(sh(t,n,e)),a=_l(Ma("-",[o(s),o(r)])),l=Ma("-",[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 $h={"=":1,"≠":1,"<":1,">":1,"≤":1,"≥":1,"+":2,"-":2,"±":2,"*":3,"/":3,neg:4,pm:4,"^":5},kh={pi:"π","≤":"≤","≥":"≥"};function qh(e){return Oh(e).text}function Mh(e,t,n=!1){return e.prec<t||n&&e.prec===t?`(${e.text})`:e.text}const Ah=e=>"op"===e.type?e.op:null,Nh=e=>e.text.startsWith("-"),Sh={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]};function Oh(e){if("num"===e.type)return{text:e.token,prec:e.token.startsWith("-")?4:9};if("sym"===e.type)return{text:kh[e.token]??e.token,prec:9};const t=e.args.map(Oh),n=$h[e.op];switch(e.op){case"+":case"-":case"±":{const r="+"===e.op&&["+","-"].includes(Ah(e.args[1])),s=Nh(t[1])?`(${t[1].text})`:r?t[1].text:Mh(t[1],n,!0);return{text:`${Mh(t[0],n)} ${"±"===e.op?"±":e.op} ${s}`,prec:n}}case"*":{const r=Mh(t[0],n),s=Nh(t[1])?`(${t[1].text})`:"*"===Ah(e.args[1])?t[1].text:Mh(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:`${Mh(t[0],n)}/${Mh(t[1],n,!0)}`,prec:n};case"^":return{text:`${Mh(t[0],n+1)}^${Mh(t[1],n)}`,prec:n};case"neg":return{text:`-${Mh(t[0],3)}`,prec:4};case"pm":return{text:`±${Mh(t[0],4)}`,prec:4};case"!":return{text:`${Mh(t[0],9)}!`,prec:6};case"abs":return{text:`|${t[0].text}|`,prec:9};case"root":return{text:`root(${t[0].text}, ${t[1].text})`,prec:9};case"der":return"op"===e.args[1].type&&"="===e.args[1].op?{text:`d/d${t[1].text.split(" = ")[0]} (${t[0].text}) at ${t[1].text}`,prec:1}:{text:`d/d${t[1].text} (${t[0].text})`,prec:6};case"int":return{text:4===t.length?`∫ from ${t[2].text} to ${t[3].text} of ${t[0].text} d${t[1].text}`:`∫ ${t[0].text} d${t[1].text}`,prec:1};case"|":return{text:`${t[0].text} or ${t[1].text}`,prec:0};case"_":return{text:`${Mh(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:`${Sh[e.op][0]}${t.map(e=>e.text).join(", ")}${Sh[e.op][1]}`,prec:9};case"&":return{text:`${t[0].text} and ${t[1].text}`,prec:0};default:return void 0!==n?{text:`${Mh(t[0],n)} ${e.op} ${Mh(t[1],n,!0)}`,prec:n}:{text:`${e.op.replace(/^\\:?/,"")}(${t.map(e=>e.text).join(", ")})`,prec:9}}}const Eh=['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'],Ih=['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'],_h={normal:"Work out the numbers and collect like terms.","simplify.cancel":"Cancel the factors the top and bottom share.","simplify.expand":"Multiplying out gives something shorter.","simplify.factor":"Factoring gives something shorter.",expand:"Multiply out the brackets.",factor:"Write it as a product of factors.","factor.common":"Take out the common factor {common}.","factor.polynomial":"Factor what is left: {roots}.",together:"Write it as one fraction over a common denominator.",cancel:"Cancel the factors the top and bottom share: {canceled}.","solve.move":"Keep the terms with {v} on the left and move the others to the right.","solve.divide":"Divide both sides by {by}.","solve.multiply":"Multiply both sides by {by}.","solve.one-side":"Move everything to one side, so the equation reads … = 0.","solve.factor":"Factor the left side.","solve.zero-product":"A product is 0 exactly when one of its factors is 0.","solve.split":"There are two cases; solve each.","solve.quadratic":"The quadratic formula with a = {a}, b = {b}, c = {c}: {v} = (-b ± √(b² - 4ac)) / 2a, and b² - 4ac = {D}.","solve.no-real":"b² - 4ac = {D} is negative, so there are no real solutions.","solve.quadratic-complex":"The quadratic formula with a = {a}, b = {b}, c = {c}: {v} = (-b ± √(b² - 4ac)) / 2a. b² - 4ac = {D} is negative, so its square root is imaginary: √({D}) = {root}.","solve.roots":"{v}^{n} = {r} has {n} solutions, spaced evenly round a circle: |{r}|^(1/{n})·(cos θ + i sin θ), with θ = (arg {r} + 2πk)/{n} for k = 0 … {last}.","solve.clear-denominator":"Multiply both sides by {den} (an answer that makes it 0 is not allowed).","solve.substitute":"Write {u} for {kernel}: this is a polynomial in {u}.","solve.reject":"{value} is not a solution: {reason}.","solve.always":"This is true for every {v}.","solve.never":"This is never true, so there is no solution.","solve.unsolved":"There is no exact method here for solving for {v}; try { approximate: true }.","solve.numeric":"Found {count} solution(s) numerically.","system.eliminate":"Use one equation to remove {v} from the others.","integrate.expand":"Multiply out, then integrate term by term.","integrate.substitute":"Let {u} = {inside}, so d{u} = {a} d{v}.","integrate.back":"Put {inside} back for {u}.","integrate.parts":"By parts with u = {u} and dv = {dv} d{v}: ∫ u dv = u·v - ∫ v du, where v = {V} and du = {du} d{v}.","integrate.constant":"The number {c} comes out of the integral.","integrate.divide":"The top has at least the degree of the bottom: divide first.","integrate.partial-fractions":"Split the fraction into simple fractions, one for each factor below.","integrate.evaluate":"Evaluate {F} at {b} and at {a}, and subtract.",substitute:"Put in the values."},Th=["normal","rewrite","simplify","expand","factor","cancel","diff","differentiate","integrate","solve","solveSystem","substitute","approximate","equivalent"];class jh{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 Th){const t=jh.prototype[e];this[e]=(...e)=>Ga(s,()=>t.apply(this,e))}}node(e){return this.atPoints(this.read_(e))}read_(e){if(e&&"object"==typeof e&&!Array.isArray(e)&&e.type)return e;if(Array.isArray(e))return Oa(e);if("string"!=typeof e)throw new La("expected an expression");if(this.read){const t=this.read(e);return Array.isArray(t)?Oa(t):"string"==typeof t?Sa(t):t}return Sa(e)}atPoints(e){if(!e||!Na(e)||!e.s.includes("= der"))return e;const t=e.args.map(e=>this.atPoints(e)),[n,r]=t;if("der"===e.op&&Na(r)&&"="===r.op&&"sym"===r.args[0].type){const e=r.args[0].token;return this.substitute(this.diff(n,e).result,{[e]:r.args[1].s}).result}return Ma(e.op,t)}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=cc(s,{digits:"number"==typeof n.approximate?n.approximate:15})}return{result:s,text:s?this.format(s):"",steps:Nc(t,Ac(n.steps)),...r}}variable(e,t){if(t&&!/^\\?[A-Za-z\u0370-\u03FF][A-Za-z0-9_\u0370-\u03FF′]*$/.test(t))throw new La(`"${t}" is not a variable name; for a derivative at a point write der(f, x = a)`);if(t)return t;const n=[...Zl(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 _l(this.node(e))}rewrite(e,t,n={}){const r=this.node(e),s=this.set.view(t);if(!s.size)throw new La(`no rules in mode "${t}" (modes: ${this.set.modes().join(", ")})`);const i=kc(r,s,{format:this.format,order:n.order,variable:n.variable});return this.result(i.node,[...this.tidyStep(r,_l(r)),...i.steps],n)}simplify(e,t={}){const n=this.node(e),r=[...this.tidyStep(n,_l(n))],s=kc(n,this.set.view("simplify"),{format:this.format});r.push(...s.steps);let i=s.node,o=null;const a=Il(i),l=[],u=0===Zl(i).size,c=u?null:Qc(a);c&&l.push({node:Hc(c),id:"simplify.cancel",name:"Cancel"});const h=kc(Ll(Ec(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:Hc(Pc(a)),id:"simplify.factor",name:"Factor"});for(const e of l)Ia(e.node)<Ia(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=Ll(Ec(Il(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=Pc(Il(n)),s=Hc(r),i=[],o=r.notes.find(e=>"factor.common"===e.id);return s.s!==_l(n).s&&i.push(this.step(o?"factor.common":"factor","Factor",["factor"],n,s,o?{common:Ll(o.values.common)}:{})),this.result(s,i,t)}cancel(e,t={}){const n=this.node(e),r=Il(n),s=Qc(r);if(!s)return this.result(_l(n),this.tidyStep(n,_l(n)),t);const i=Hc(s),o=Xc(r),a=Ma("/",[Ll(o.num),Ll(o.den)]),l=[];return"/"===n.op&&a.s===_l(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,{canceled:s.canceled.length?s.canceled.map(e=>this.format(Ll(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=kc(Ma("der",[i,xa(s)]),this.set.view("differentiate"),{format:this.format,order:"pre"}),t=kc(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=kc(Ma("der",[e,xa(t)]),this.set.view("differentiate"),{format:this.format,order:"pre"});return kc(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(Na(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=vh(this,r,a),u=kc(l.node,this.set.view("simplify"),{format:this.format}),c=[...l.steps,...u.steps];if(i&&o){const e=xh(this,u.node,a,i,o,r);c.push(e.step);const t=kc(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=Ma("+",[h,xa(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=eh(this,r,s,n);let o=i.solutions;if(n.approximate){const e="number"==typeof n.approximate?n.approximate:15;o=o.map(t=>cc(t,{digits:e}))}const a=o.map(e=>Ma("=",[xa(s),e])),l=a.length?a.reduce((e,t)=>e?Ma("|",[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:Nc(i.steps,Ac(n.steps))}}solveSystem(e,t,n={}){const r=e.map(e=>this.node(e)),s=t??[...new Set(r.flatMap(e=>[...Zl(e)]))].sort(),i=function(e,t,n){const r=[],s=t.map(t=>{const r=Kc(t)?pl([Il(t.args[0]),Ml(Il(t.args[1]))]):Il(t),s=n.map(t=>{const n=_c(r,t);if(!n||Math.max(0,...n.keys())>1)throw new La(`not linear in ${t}`);const s=n.get(1)??Ja(Pa.ZERO);if(!tl(s))throw new La(`the coefficient of ${t} must be a number (it is ${e.format(Ll(s))})`);return s.q});let i=r;for(let e=0;e<n.length;e++)i=pl([i,dl([Ja(s[e].neg()),Il(xa(n[e]))])]);for(const e of n)if(Tc(i,e))throw new La(`not linear in ${e}`);return{coeffs:s,rhs:Ml(i)}}),i=()=>s.map(e=>Jc(Ll(pl(e.coeffs.map((e,t)=>dl([Ja(e),Il(xa(n[t]))])))),Ll(e.rhs))).reduce((e,t)=>e?Ma("&",[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=dl([Ja(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=pl([s[e].rhs,dl([Ja(n.neg()),c.rhs])])}r.push(e.step("system.eliminate","Eliminate",["eliminate"],u,i(),{v:xa(n[t])})),a.push(t),o++}for(const e of s.slice(o))if(!tl(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],Ll(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:Nc(i.steps,Ac(n.steps))}}substitute(e,t,n={}){const r=this.node(e);let s=r;for(const[e,n]of Object.entries(t))s=sh(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:[...Nc(o,Ac(n.steps)),...i.steps]}}defined(e){const t=this.set.view("define");return t.size?kc(e,t,{format:this.format}).node:e}approximate(e,t={}){const n=this.defined(this.node(e));if(Zl(n).size&&!t.scope){const e=cc(_l(n),t);return{result:e,text:this.format(e),number:null,exact:!1}}const r=ac(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(Ma("-",[n,r])),i=this.simplify(s,{steps:!1}).result;if("num"===i.type&&"0"===i.token)return{equal:!0,how:"exact"};const o=[...Zl(s)];if(!o.length)try{return{equal:Math.abs(ac(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=ac(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 zh(e={}){const t=!1===e.defaults?[]:[...Eh,...e.complex?Ih:[]],{specs:n,messages:r}=function(e){vc();const t=[],n={};for(const r of e){const e="string"==typeof r?bu(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");pa(t.symbol)||ua({symbol:String(t.symbol),arity:"any"===t.arity?oa: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=Ga(e.complex,()=>bc(n));return new jh(s,{..._h,...r},e.format??qh,e.read??null,Boolean(e.complex))}const Lh=Symbol.for("inlinemath.expressions"),Ch=new Map,Fh={re:"Re",im:"Im",conj:"overline"},Zh=["Re","Im","re","im","conj","arg"];function Rh(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),`\\:${Fh[e.op]??e.op}`)):t.push(e.token)};return n(e),t}function Ph(e={}){const t=e.rules||e.names?null:e.complex?"complex":"default";if(t&&Ch.has(t))return Ch.get(t);const n=[...e.names??[],...e.complex?Zh:[]],r=zh({...e,read:e=>function(e,t={}){const n=Fn(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 "${Zn(e)}": ${n.error}`)}(e,n.length?{names:n}:{}),format:qh});return t&&Ch.set(t,r),r}const Bh=new Set(["simplify","expand","factor","cancel","diff","integrate","solve","approx"]),Dh={integral:"integrate",differentiate:"diff",approximate:"approx",simp:"simplify"};const Wh=e=>String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");var Uh='/*\n * Inline Math stylesheet. Everything is under .mv; colors are left to the page.\n *\n * The numbers marked "metric" must match the constants at the top of\n * src/layout.js (line-height 1, bar 0.06em, gap 0.1em); everything else can\n * be changed freely.\n *\n * Handy hooks:\n * .mv-n[data-node="4"] one node (ids from MathZetta)\n * .mv-var .mv-num .mv-word variables, numbers, function names\n * .mv-op-frac .mv-op-pow … a kind of operation\n * .mv-hl the class highlight() adds\n * --mv-hl highlight color\n */\n\n.mv {\n display: inline-block;\n font-family: "Inline Math Roman", "Latin Modern Roman", "STIX Two Text", "Cambria", "Times New Roman", serif;\n font-size: 1.2em;\n font-style: normal;\n font-weight: normal;\n line-height: 1; /* metric */\n white-space: nowrap;\n text-indent: 0;\n text-align: left;\n letter-spacing: 0;\n}\n.mv-display { display: block; text-align: center; margin: 0.6em 0; }\n.mv span, .mv svg { line-height: 1; }\n.mv-n { display: inline-block; border-radius: 0.12em; }\n\n/* ---- letters and signs -------------------------------------------------- */\n.mv-var { font-style: italic; padding-right: 0.03em; }\n.mv-num, .mv-word, .mv-name, .mv-ord, .mv-text, .mv-d, .mv-conj { font-style: normal; }\n.mv-prime { margin-left: 0.04em; }\n.mv-bin { margin: 0 0.22em; }\n.mv-rel { margin: 0 0.28em; }\n.mv-conj { margin: 0 0.6em; } /* x = 2 or x = 3 */\n.mv-punct { margin-right: 0.17em; }\n.mv-sign { margin-right: 0.04em; }\n.mv-times { display: inline-block; width: 0.06em; }\n.mv-callgap { display: inline-block; width: 0.05em; }\n.mv-fnspace { display: inline-block; width: 0.17em; }\n.mv-space { display: inline-block; width: 0.33em; }\n.mv-dx { display: inline-block; margin-left: 0.17em; }\n.mv-text { margin: 0 0.25em; }\n/* Tighter spacing in limits and exponents: n=1, x→0. */\n.mv-script .mv-rel, .mv-sup .mv-rel, .mv-sub .mv-rel { margin: 0 0.12em; }\n.mv-script .mv-bin, .mv-sup .mv-bin, .mv-sub .mv-bin { margin: 0 0.1em; }\n\n/* ---- fractions (metric: padding and border) ------------------------------ */\n.mv-frac { display: inline-flex; flex-direction: column; align-items: stretch; margin: 0 0.12em; }\n.mv-numer, .mv-denom { display: block; text-align: center; padding: 0 0.1em; }\n.mv-numer { padding-bottom: 0.1em; }\n.mv-denom { padding-top: 0.1em; border-top: 0.06em solid currentColor; }\n.mv-frac-nobar > .mv-denom { border-top: 0; }\n.mv-scaled { display: inline-block; }\n\n/* ---- scripts ----------------------------------------------------------------- */\n.mv-sup, .mv-sub { display: inline-block; margin-left: 0.04em; }\n.mv-subsup, .mv-limits { display: inline-flex; flex-direction: column; justify-content: space-between; align-items: flex-start; margin-left: 0.04em; }\n.mv-limits { margin-left: 0.02em; margin-right: 0.12em; }\n.mv-limits > .mv-lower { margin-left: -0.3em; }\n.mv-script { display: block; }\n.mv-under { display: inline-flex; flex-direction: column; align-items: center; margin-right: 0.15em; }\n.mv-under > .mv-script { margin-top: 0.05em; }\n.mv-bigop { display: inline-flex; flex-direction: column; align-items: center; margin: 0 0.12em; }\n.mv-bigop > .mv-script { display: block; margin: 0.08em 0; }\n.mv-bigop > svg { display: block; }\n\n/* ---- radicals (metric: border and padding-top) ----------------------------- */\n.mv-sqrt { display: inline-block; white-space: nowrap; }\n.mv-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.mv-matrix { display: inline-grid; column-gap: 0.8em; row-gap: 0.3em; align-items: baseline; justify-items: center; margin: 0 0.15em; }\n.mv-matrix-row { display: contents; }\n.mv-matrix-cell { display: block; }\n\n/* ---- decorations: \\boxed \\cancel \\overline \\vec … --------------------------- */\n.mv-boxed { display: inline-block; border: 0.06em solid currentColor; padding: 0.16em 0.2em; }\n.mv-over { display: inline-block; position: relative; padding-top: 0.14em; }\n.mv-over::before { content: \'\'; position: absolute; left: 0; right: 0; top: 0.21em; border-top: 0.06em solid currentColor; } /* metric */\n.mv-over-low::before { top: 0.48em; }\n.mv-underline { display: inline-block; border-bottom: 0.06em solid currentColor; padding-bottom: 0.06em; }\n.mv-cancel { display: inline-block; position: relative; }\n.mv-cancel-line { position: absolute; left: 0; top: 0; width: 100%; height: 100%; overflow: visible; pointer-events: none; }\n.mv-accent { display: inline-block; position: relative; padding-top: 0.3em; }\n.mv-accent-mark { position: absolute; top: -0.27em; left: 0; right: 0; text-align: center; font-size: 0.7em; line-height: 0.6; } /* metric: measured over F, h, A */\n/* ˆ ˜ ˙ ¨ are spacing marks that sit high in their em: full size, pulled down onto the letter */\n.mv-accent-hat, .mv-accent-widehat, .mv-accent-tilde, .mv-accent-dot, .mv-accent-ddot { font-size: 1em; line-height: 1; top: 0.02em; }\n/* over an italic letter the mark leans with it, right of the box\'s center */\n.mv-accent:has(> .mv-var) > .mv-accent-mark { transform: translateX(0.1em); }\n/* a letter with no ascender (x, u, α; layout.js adds -low): the mark comes down to its top */\n.mv-accent-low > .mv-accent-mark { top: 0.08em; }\n.mv-accent-low > .mv-accent-hat, .mv-accent-low > .mv-accent-widehat, .mv-accent-low > .mv-accent-tilde, .mv-accent-low > .mv-accent-dot, .mv-accent-low > .mv-accent-ddot { top: 0.31em; }\n\n/* ---- interaction -------------------------------------------------------------- */\n.mv-hl { background: var(--mv-hl, rgba(255, 200, 0, 0.35)); box-shadow: 0 0 0 0.08em var(--mv-hl, rgba(255, 200, 0, 0.35)); }\n/* Windows high contrast (and other forced colors) drops backgrounds and shadows: outline a highlight instead */\n@media (forced-colors: active) {\n .mv-hl { outline: 0.08em solid Highlight; outline-offset: 0.04em; }\n}\n.mv-clickable .mv-n { cursor: pointer; }\n.mv-editable .mv-n:hover { outline: 1px dashed rgba(0, 0, 0, 0.25); }\n/* the box editing a part in place (view.editable, or a Markdown textbox variable) */\n.mv-edit { transform: translateY(-50%); z-index: 1000; box-sizing: content-box; padding: 0.1em 0.35em; font-family: inherit;\n border: 1px solid #1a5fb4; border-radius: 0.25em; background: #fff; color: #111; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.18); }\n.mv-edit[aria-invalid="true"] { border-color: #c33; outline: 2px solid #c33; }\n/* the live region a view announces steps through ({ announce: true }): read, never seen */\n.mv-sr-only, .mv-sr-math { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }\n.mv-clickable .mv-n:hover { outline: 1px dashed rgba(0, 0, 0, 0.25); }\n/* the keyboard: the expression is one tab stop, and the part the arrow keys are on is ringed */\n.mv[tabindex]:focus-visible { outline: 0.1em solid #1a5fb4; outline-offset: 0.12em; }\n.mv[tabindex]:focus .mv-focus { outline: 0.1em solid #1a5fb4; outline-offset: 0.06em; border-radius: 0.1em; }\n/* while a part is ringed, the whole expression\'s ring steps back so the part is the one that stands out */\n.mv[tabindex]:focus-visible:has(.mv-focus) { outline: 1px dashed #1a5fb4; }\n@media (forced-colors: active) {\n .mv[tabindex]:focus-visible, .mv[tabindex]:focus .mv-focus { outline-color: Highlight; }\n}\n\n/* ---- steps (stepsHTML from \'@mathzetta/inlinemath/cas\') ---------------------------------------- */\n.mv-steps { margin: 0; padding-left: 1.6em; }\n.mv-step { margin: 0.5em 0 0.9em; }\n.mv-step-name { display: block; font-size: 0.85em; font-weight: 600; color: #555; }\n.mv-step-maths { display: flex; flex-wrap: wrap; align-items: center; gap: 0.4em 0.8em; margin: 0.15em 0; }\n.mv-step-arrow { color: #888; }\n.mv-step-why { margin: 0.1em 0 0; font-size: 0.9em; color: #444; }\n\n/* ---- Markdown with math (markdownToHTML from \'@mathzetta/inlinemath/markdown\') ------------------- */\n.mv-md-math { display: inline-block; vertical-align: middle; }\n.mv-md-display { display: block; text-align: center; margin: 0.6em 0; overflow-x: auto; }\n.mv-md-block { margin: 0.8em 0; }\n.mv-md-error code { background: rgba(200, 60, 0, 0.08); color: #a33; border-bottom: 1px dotted #a33; }\n/* saved variables: $A := 2+2$ draws A ≔ 2 + 2; $A := [[…]]$ an input that sets A */\n.mv-md-input-def { display: inline-flex; align-items: center; gap: 0.3em; }\n.mv-md-assign { margin: 0 0.1em; }\n.mv-md-input { font: inherit; font-size: 0.9em; }\ninput.mv-md-textbox { font-family: inherit; padding: 0.05em 0.3em; field-sizing: content; min-width: 3ch; }\ninput.mv-md-textbox[aria-invalid="true"] { outline: 2px solid #c33; outline-offset: 1px; }\ninput.mv-md-slider { vertical-align: middle; }\n.mv-md-output { font-variant-numeric: tabular-nums; min-width: 2ch; }\n';const Vh=Uh;if("undefined"!=typeof document&&!document.getElementById("inlinemath-css")){const e=document.createElement("style");e.id="inlinemath-css",e.textContent=Uh,document.head.append(e)}return e.CSS=Vh,e.DEFAULTS=Bi,e.PATHS=xi,e.View=mo,e.casBlocks=function(e={}){const t=e.cas??Ph(),n=void 0===e.steps?{}:{steps:e.steps},r=(e,s)=>{let i;try{i=t.read(e)}catch{return li(e,s)}const o=s&&s[Lh];o&&(i=i.flatMap(e=>Object.hasOwn(o,e)?o[e]:[e]));const a=i[i.length-1],l=a?.startsWith("\\:")?Dh[a.slice(2)]??a.slice(2):null,u=l&&Bh.has(l),c="der"===a||"int"===a;if(!u&&!c)return li(e,s);const h=t.node(i),p=c&&h.op!==a,f=u?h.args:[h],d=e=>e?e.s:void 0,m=(e,r,s)=>{if(!r||"="!==r.op)return t.diff(e,d(r),{...n,order:s});const i=r.args[0].s,o=t.diff(e,i,{...n,order:s}),a=t.substitute(o.result,{[i]:r.args[1].s},n);return{...a,steps:[...o.steps??[],...a.steps??[]]}};let g;try{switch(p?"simplify-read":u?l:"der"===a?"derivative":"antiderivative"){case"simplify-read":g=t.simplify(h,n);break;case"simplify":g=t.simplify(f[0],n);break;case"expand":g=t.expand(f[0],n);break;case"factor":g=t.factor(f[0],n);break;case"cancel":g=t.cancel(f[0],n);break;case"diff":g=m(f[0],f[1],f[2]?Number(f[2].s):1);break;case"integrate":g=t.integrate(f[0],d(f[1]),{...n,...f[3]?{from:f[2].s,to:f[3].s}:{}});break;case"solve":g=t.solve(f[0],d(f[1]),n);break;case"approx":g=t.approximate(f[0],{...n,digits:f[1]?Number(f[1].s):15});break;case"derivative":g=m(h.args[0],h.args[1],1);break;default:g=t.integrate(h,void 0,n)}}catch(t){return`(${e})`}if(r.last=g,!g.result)return`"${g.text}"`;const v=sa(Rh(g.result));return/^-?\d+(\.\d+)?$/.test(v)?v:`(${v})`};return r},e.createVariables=Eo,e.extractMath=To,e.layout=Hi,e.markdownToHTML=function(e,t={}){return Xo(Co(e,t,t.variables||null),t)},e.mathCAS=Ph,e.nodeAt=so,e.numberTree=oo,e.pathOf=io,e.render=function(e,t,n={}){return new mo(e,t,n)},e.renderMarkdown=Go,e.renderMarkdownInto=function(e,t,n={}){const r=void 0===n.variables?Io:n.variables||null;Yo();const s=Qo.get(e);s&&s.stop(s.store!==r);let i=Co(t,n,r,e);if(e.innerHTML=Xo(i,n),!r)return Qo.delete(e),e;r.own(e,i.defs);let o=e.isConnected;const a=t=>{const s=t.target,i=s&&s.dataset&&s.dataset.mvVar;if(void 0!==i&&e.contains(s)){if("text"===s.type)try{co(s.value,{blocks:n.blocks,scope:{}}),s.removeAttribute("aria-invalid")}catch{return void s.setAttribute("aria-invalid","true")}r.set(i,s.value)}},l=s=>{const o=s.target.closest?.("[data-node]"),a=o&&o.closest("[data-mv-md]");if(!a||!e.contains(a))return;const l=Number(a.dataset.mvMd),u=i.trees[l];if(!u)return;const c=Number(o.dataset.node),h=io(u,c)||[];let p=null;for(let e=h.length;e>=0&&!p;e--){const t=so(u,h.slice(0,e));t&&void 0!==t.from&&(p={node:t,depth:e})}const f=p&&r.definitions().get(p.node.from);if(f&&f.input&&"textbox"===f.input.kind){s.preventDefault();const t=f.name,i=e.ownerDocument.querySelector(`[data-mv-var="${CSS.escape(t)}"]`),a=n.editable&&n.editable.toText;if(!a)return void(i&&(i.focus(),i.select()));const l=e=>co(e),c=so(u,h);return void fo(o,a($o(c,l)),{label:`Edit ${t}`,parse:e=>co(e,{blocks:n.blocks}),commit:e=>{const n=po($o(p.node,l),h.slice(p.depth),e);r.set(t,a(n))}})}const d=f&&i.defs.get(f.name),m=d&&d.key===f.key&&void 0!==d.start?{...i.math[l],start:d.start,end:d.end,raw:t.slice(d.start,d.end)}:i.math[l];e.dispatchEvent(new CustomEvent("inlinemath:select",{bubbles:!0,detail:{index:l,start:m.start,end:m.end,raw:m.raw,source:m.source,id:c,path:h}}))};e.addEventListener("input",a),e.addEventListener("change",a),e.addEventListener("dblclick",l);const u=r.subscribe(s=>{s!==e&&(e.isConnected?(o=!0,Yo(),(()=>{const s=Co(t,n,r,e);s.drawn.forEach((t,n)=>{if(t===i.drawn[n]||s.inputs.has(n))return;const r=e.querySelector(`[data-mv-md="${n}"]`);r&&(r.outerHTML=t)});for(const t of e.querySelectorAll("[data-mv-var], [data-mv-out]")){const e=s.defs.get(t.dataset.mvVar??t.dataset.mvOut);if(!e)continue;const n=r.textOf(e);void 0!==t.dataset.mvOut?t.textContent=n:t.value!==n&&t!==t.ownerDocument?.activeElement&&(t.value=n)}i=s})()):o&&c(!0))});function c(t){u(),e.removeEventListener("input",a),e.removeEventListener("change",a),e.removeEventListener("dblclick",l),Jo.delete(h),Qo.delete(e),t&&r.own(e,null)}const h={element:e,store:r,stop:c,connected:()=>o};return Jo.add(h),Qo.set(e,h),e},e.select=no,e.shouldAnimate=vo,e.signature=to,e.stepsHTML=function(e,t={}){return`<ol class="mv-steps">${e.map(e=>{const n=ho(Rh(Sa(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>${ho(Rh(Sa(e.to)),t)}`,s=e.explanation?`<p class="mv-step-why">${Wh(e.explanation)}</p>`:"";return`<li class="mv-step" data-rule="${Wh(e.id)}"><span class="mv-step-name">${Wh(e.name)}</span><div class="mv-step-maths">${n}${r}</div>${s}</li>`}).join("")}</ol>`},e.toHTML=ho,e.toText=sa,e.tokensOf=Rh,e.treeOf=co,e.variables=Io,e}({});