@mathzetta/inlinemath 0.4.1 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -3
- package/dist/cas.external.js +2 -2
- package/dist/cas.js +2 -2
- package/dist/chunks/{calculate-HWNd7HTQ.js → calculate-BPhXubl4.js} +2 -2
- package/dist/chunks/{draw-SJQZoo2a.js → draw-BlziYtHI.js} +1 -1
- package/dist/chunks/{edit-lks88rjH.js → edit-Bc3TgjS_.js} +2 -2
- package/dist/chunks/{edit-BPcpKq9t.js → edit-DUPFxM7f.js} +2 -2
- package/dist/chunks/html-B5rAcnpJ.js +2 -0
- package/dist/chunks/{html-CzXOU7ql.js → html-ItSMWpG6.js} +2 -2
- package/dist/chunks/{lite-OfhVrBim.js → lite-Dl7abp_j.js} +2 -2
- package/dist/inlinemath-cas.external.global.min.js +2 -2
- package/dist/inlinemath-cas.global.min.js +2 -2
- package/dist/inlinemath-lite-calc.global.min.js +2 -2
- package/dist/inlinemath-lite.external.global.min.js +1 -1
- package/dist/inlinemath-lite.global.min.js +2 -2
- package/dist/inlinemath.external.global.min.js +1 -1
- package/dist/inlinemath.external.js +2 -2
- package/dist/inlinemath.global.min.js +2 -2
- package/dist/inlinemath.js +2 -2
- package/dist/lite-calc.js +2 -2
- package/dist/lite.external.js +2 -2
- package/dist/lite.js +2 -2
- package/dist/markdown.external.js +2 -2
- package/dist/markdown.js +2 -2
- package/package.json +1 -1
- package/dist/chunks/html-hyetRykq.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/* Inline Math 0.4.
|
|
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),arcsec:r(1),arccsc:r(1),arccot: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),evaluated:r(4),setbuilder: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"},"\\implies":{prec:15,assoc:"right",arity:2,fixity:"infix"},"\\iff":{prec:14,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,f="",p="",m={[f]:"dot",[p]:"cross"},d="",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,evaluated:h,setbuilder:h,arcsin:h,arccos:h,arctan:h,arcsec:h,arccsc:h,arccot:h,arcsinh:h,arccosh:h,arctanh:h,atan2:h,_:h,"!":90,"\\not":85,"^":80,"*":70,"/":70,frac:70,[f]:70,[p]: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,"\\implies":15,"\\iff":14,"?:":10,"?":9,",":5},v=e=>Object.prototype.hasOwnProperty.call(g,e),b=new Set(["^","?:","?","log"]),y=["(","{","["],w=[")","}","]"];function x(e,t=!1){return"string"==typeof e&&(t?k:$).test(e)}const $=/^(?:\d+\.?\d*|\.\d+|\d*\.\d+\.\.)$/,k=/^-?(?:\d+\.?\d*|\.\d+|\d*\.\d+\.\.)$/;for(const e of[g])Object.setPrototypeOf(e,null);const q=e=>({type:"number",value:String(e)}),M=e=>({type:"symbol",value:e}),A=(e,t)=>({type:"op",op:e,args:t}),S=['"',"'","`"];function N(e){return x(e,!0)?q(e):S.includes(e[0])?{type:"string",value:e}:M(e)}const O={"0-":"neg",sqrtpow:"root",pow:"^","==":"=","!==":"≠="};function E(e){if(!Array.isArray(e)||0===e.length)throw new Error("Empty postfix");const n=[],r=[];if(e.forEach((e,s)=>{const i=O[e]??String(e),l=a(i);if(!l)return n.push({...N(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({...A(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 I(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 z(e){if(Array.isArray(e))return E(e);if(e&&"object"==typeof e&&e.type)return e;throw new Error("Expected a postfix array or an expression tree")}function _(e,t,n=null){t(e,n),"op"===e.type&&e.args.forEach(n=>_(n,t,e))}function j(e){let t="";return _(e,e=>{!t&&"symbol"===e.type&&1===e.value.length&&/[a-zA-Zʹ-Ͽ]/.test(e.value)&&(t=e.value)}),t}for(const e of[O])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 L(e){for(;"op"===e.type&&e.args.length;)e=e.args[0];return"op"===e.type?"":e.value}function F(e,t,n){const r=e=>"symbol"===e.type?e.value===t?n:e:"op"!==e.type?e:Z.has(e.op)&&function(e,t){if("setbuilder"===e.op){const n=e.args[0];return("symbol"===n.type?n.value:n.args?.[0]?.value)===t}const n=e.args[1];return"symbol"===n?.type?n.value===t:"op"===n?.type&&["=","→"].includes(n.op)&&"symbol"===n.args[0]?.type&&n.args[0].value===t}(e,t)?{...e,id:void 0,args:e.args.map((t,n)=>function(e,t,n,r){if("setbuilder"===e)return 0===n&&"op"===t.type&&"∈"===t.op?{...t,id:void 0,args:[t.args[0],r(t.args[1])]}:t;if(0===n)return t;if(1===n)return"op"!==t.type||"="!==t.op&&"→"!==t.op?t:{...t,id:void 0,args:[t.args[0],...t.args.slice(1).map(r)]};return r(t)}(e.op,t,n,r))}:{...e,id:void 0,args:e.args.map(r)};return r(e)}const Z=new Set(["der","int","lim","\\sumidx","\\prodidx","evaluated","setbuilder"]);function C(e){if("op"!==e.type||"∈"!==e.op&&"∉"!==e.op)return null;const[t,n]=e.args;if("op"!==n.type||"setbuilder"!==n.op)return null;let[r,s]=n.args,i=null;if("op"===r.type&&"∈"===r.op&&"symbol"===r.args[0].type&&([r,i]=r.args),"symbol"!==r.type)return null;const o=F(s,r.value,t),a=i?{type:"op",op:"&",args:[{type:"op",op:"∈",args:[t,i]},o]}:o;return"∉"===e.op?{type:"op",op:"\\not",args:[a]}:a}function R(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 B(e){if("*"!==e.op)return!1;const[t,n]=e.args;return"number"===t.type&&"-1"===t.value&&"-1"!==L(n)}function P(e){return"op"!==e.type||a(e.op)?.group?null:"sum"===e.op?"+":"prod"===e.op?"*":B(e)?"neg":e.op}const D=new Set(["=","===","≠","≠=","<",">","≤","≥","≈","≡","→"]),W=(e,t,n)=>("op"!==t.type||"?:"!==t.op||!D.has(e.op))&&c(e.op,P(t),n);function U(e,t){const n=P(t),r=n&&a(n)?.prec;return r?"!"===e?r<=a("!").prec:"\\not"===e?r<a("\\not").prec:r<70||Y(t)||"\\not"===n:"\\not"!==e&&Y(t)}function V(e,t,n={}){const r=n.left?"bracket":X(e),s=n.right?"bracket":Q(t);return"digit"!==s&&"sign"!==s&&"word"!==r&&"word"!==s&&"other"!==r&&("frac"!==s||"digit"!==r&&"frac"!==r)}function H(e){return 1===e.length||Boolean(T[e])||/^Δ.$/.test(e)||/^d[A-Za-z\u03B1-\u03C9]$/.test(e)||/^.′+$/.test(e)}function G(e){return"op"===e.type&&!a(e.op)?.group&&(a(e.op)?.prec??100)<70&&!["sum","prod"].includes(e.op)}function Q(e){if("number"===e.type)return e.value.startsWith("-")?"sign":"digit";if("op"!==e.type)return"symbol"===e.type&&H(e.value)?"name":"word";const t=e.op;return"neg"===t||"pm"===t||B(e)?"sign":"/"===t?"frac":a(t)?.group||G(e)?"bracket":J(e)||["der","int","lim","comb"].includes(t)?"call":["^","!","_"].includes(t)?G(e.args[0])?"bracket":Q(e.args[0]):["*","sum","prod","perm"].includes(t)?Q(e.args[0]):"other"}function X(e){if("number"===e.type)return"digit";if("op"!==e.type)return"symbol"===e.type&&H(e.value)?"name":"word";const t=e.op;return"/"===t?"frac":"^"===t||"_"===t?"script":a(t)?.group||G(e)||J(e)||["der","int","lim","comb","perm"].includes(t)?"bracket":["*","neg","pm","sum","prod"].includes(t)?X(e.args[e.args.length-1]):"other"}function J(e){if("op"!==e.type)return!1;const t=a(e.op);return"prefix"===t?.fixity&&100===t.prec}function Y(e){if("number"===e.type)return e.value.startsWith("-");if("op"!==e.type)return!1;if("neg"===e.op||B(e))return!0;const t=a(e.op);return"infix"===t?.fixity&&!W(e,e.args[0],"left")&&Y(e.args[0])}const K=e=>"symbol"===e.type&&1===e.value.length&&/[a-zA-Zʹ-Ͽ]/.test(e.value),ee=e=>e.slice(2),te=new Set(["{}","()","[]","(]","[)","setbuilder","∪","∩"]);const ne=e=>"string"==typeof e&&e.startsWith("\\:")&&"startswith"===e.slice(2).toLowerCase(),re=e=>(null==e?"":String(e)).replace(/[A-Z]/g,e=>String.fromCharCode(e.charCodeAt(0)+32));function se(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&&ie(i.args[1],n);)s++,i=i.args[0];return{n:s,body:i,by:n,at:r,variable:"symbol"===i.type&&H(i.value)}}const ie=(e,t)=>e.type===t.type&&e.value===t.value&&"op"!==e.type,oe=new Set(["<",">","≤","≥","=","===","≠","≠=","&","|","\\not","\\xor","\\nand","\\nor","\\implies","\\iff","∈","∉","≈","≡"]);function ae(e){return"op"===e.type&&(!!("="===e.op&&(t=e.args[1],"op"===t.type&&oe.has(t.op)||"symbol"===t.type&&("true"===t.value||"false"===t.value)))||e.args.some(ae));var t}const le=new Set(["<",">","≤","≥","=","≠"]);function ue(e){if("op"!==e.type||!le.has(e.op)||2!==e.args.length)return null;const[t,n]=e.args;if("op"!==t.type||!le.has(t.op)||2!==t.args.length)return null;return{type:"op",op:"&",args:[ue(t)??t,{type:"op",op:e.op,args:[t.args[1],n]}]}}for(const e of[T])Object.setPrototypeOf(e,null);const ce={pmatrix:["(",")"],bmatrix:["[","]"],vmatrix:["|","|"]};function he(e){if(!e||"op"!==e.type)return null;if(Object.prototype.hasOwnProperty.call(ce,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 fe(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 pe=e=>Array.isArray(e)&&e.length>0&&!e.some(Array.isArray);function me(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 fe(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 de(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 ve(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=ge(n,e,s);i?(r+=t.get(e.slice(s,s+i)),s+=i):r+=e[s++]}return r}}function ge(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 ve(e){const t=new Set([e.toLowerCase(),e.toUpperCase(),be(e)]);return t.delete(e),t}function be(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 ye=[["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.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("],["asec(","arcsec("],["acsc(","arccsc("],["acot(","arccot("],["\\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",f],["\\times",p],["×",p],["·",f],["÷","/"],["->","→"],["\\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 "],["\\Longrightarrow"," \\implies "],["\\Rightarrow"," \\implies "],["\\implies"," \\implies "],["⇒"," \\implies "],["⟹"," \\implies "],["\\Longleftrightarrow"," \\iff "],["\\Leftrightarrow"," \\iff "],["\\iff"," \\iff "],["⇔"," \\iff "],["⟺"," \\iff "],["\\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.",d],["\\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 "],["∞","∞"],["⋅",f],["−","-"],["\\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 we=e=>" "===e||"\t"===e||"\n"===e,xe="({[",$e=")}]";const ke="ⅆ",qe=new RegExp(String.raw`(\\(?:mathrm|operatorname|text)\{d\}\s*|d)([A-Za-zα-ω](?![A-Za-z0-9])|\\(?:${"alpha|beta|gamma|delta|epsilon|varepsilon|zeta|eta|theta|vartheta|iota|kappa|lambda|mu|nu|xi|rho|sigma|tau|upsilon|phi|varphi|chi|psi|omega"})(?![A-Za-z]))`,"g");function Me(e){const t=[String.raw`\left\{`,String.raw`\left\lbrace`,String.raw`\{`,String.raw`\lbrace`,"{"],n=[String.raw`\right\}`,String.raw`\right\rbrace`,String.raw`\}`,String.raw`\rbrace`,"}"],r=/\\[A-Za-z{]/.test(e);for(let s=0,i=0;s<50;s++){let s=-1,o="";for(let n=i;n<e.length&&s<0;n++){const i=t.find(t=>e.startsWith(t,n));i&&("{"===i&&(r||/[\\^_A-Za-z]$/.test(e.slice(0,n)))||("{"!==i||"{"!==e[n+1]?(s=n,o=i):n++))}if(s<0)return e;let a=0,l=null,u=null,c=-1,h=0;for(let t=s+o.length;t<e.length;t++){const s=n.find(n=>e.startsWith(n,t));if(0===a&&s&&("{"===o?"}"===s:"}"!==s)){c=t,o+="|"+s;break}if(!"([{".includes(e[t])||"{"===e[t]&&"\\"===e[t-1]?")]}".includes(e[t])&&"\\"!==e[t-1]&&a--:a++,0===a&&"?"===e[t]&&h++,0===a&&!l){const n=/^(?:\\middle\s*\||\\mid(?![A-Za-z])|:(?!=)|\|)/.exec(e.slice(t));n&&":"===n[0]&&h?h--:n&&"|"!==n[0]?l={at:t,length:n[0].length}:n&&r&&!u&&!/\\left\s*$|\\right\s*$|\\middle\s*$/.test(e.slice(0,t))&&(u={at:t,length:1})}}if(l??=u,c<0||!l){i=s+1;continue}const f=e.slice(s+o.split("|")[0].length,l.at).trim(),p=e.slice(l.at+l.length,c).trim();if(!f||!p){i=s+1;continue}const m=o.split("|")[1];e=`${e.slice(0,s)}setbuilder((${f}),(${p}))${e.slice(c+m.length)}`,i=s}return e}const Ae=String.raw`\\(?:[Bb]igg?|right)[lrm]?`,Se=new RegExp(`(?:${Ae}\\s*([\\]|])|(\\]))\\s*(?=[_^])`,"g");function Ne(e,t){let n=t;for(;" "===e[n];)n++;if("{"===e[n]){let t=0;for(let r=n;r<e.length;r++)if("{"===e[r])t++;else if("}"===e[r]&&0===--t)return{value:e.slice(n+1,r).trim(),end:r+1};return null}const r=/^\\[A-Za-z]+/.exec(e.slice(n));return r?{value:r[0],end:n+r[0].length}:"-"===e[n]&&/\d/.test(e[n+1]??"")?{value:e.slice(n,n+2),end:n+2}:e[n]?{value:e[n],end:n+1}:null}function Oe(e,t){let n=t;for(;" "===e[n];)n++;const r=e[n];if("_"!==r&&"^"!==r)return null;const s=Ne(e,n+1);if(!s)return null;let i=s.end;for(;" "===e[i];)i++;const o="_"===r?"^":"_";if(e[i]!==o)return null;const a=Ne(e,i+1);return a?"_"===r?{lo:s.value,hi:a.value,end:a.end}:{lo:a.value,hi:s.value,end:a.end}:null}function Ee(e,t,n){let r=0;for(let s=t-1;s>=0;s--){if(n){if("]"===e[s])r++;else if("["===e[s]){if(0===r)return{start:s,end:s+1};r--}continue}const i=e.slice(0,s+1),o=/\\right\s*[\]|)}.]$|\\[Bb]igg?r?\s*[\]|]$/.exec(i),a=/\\left\s*(?:[[(.]|\\\{)$|\\[Bb]igg?l?\s*\[$/.exec(i);if(o&&s+1<t)r++,s-=o[0].length-1;else if(a){if(0===r)return{start:s+1-a[0].length,end:s+1};r--,s-=a[0].length-1}}return null}function Ie(e,t){let n=0;for(let r=t-1;r>=0;r--){const t=e[r];if(")]}".includes(t))n++;else if("([{".includes(t)){if(0===n)return r+1;n--}else{if(0===n&&/[=<>&,]/.test(t))return r+1;if(0===n&&/\\(?:approx|leq?|geq?|neq?|to|quad|qquad)$/.test(e.slice(0,r+1)))return r+1}}return 0}function ze(e){for(let t=0;t<50;t++){Se.lastIndex=0;let t=null;for(let n=Se.exec(e);n;n=Se.exec(e)){const r=Oe(e,n.index+n[0].length);if(!r)continue;const s=Boolean(n[2]),i="|"===(n[1]??n[2]),o=Ee(e,n.index,s);if((o||i&&!/^\\right/.test(n[0]))&&(!o||!/\\left\s*\|$/.test(e.slice(o.start,o.end)))){t={m:n,limits:r,opener:o};break}}if(!t)return e;const{m:n,limits:r,opener:s}=t,i=s?s.start:Ie(e,n.index),o=e.slice(s?s.end:i,n.index).trim(),a=/^\s*([A-Za-zα-ωΑ-Ω]|\\[A-Za-z]+)\s*=\s*([\s\S]+)$/.exec(r.lo),l=r.hi.replace(/^\s*(?:[A-Za-zα-ωΑ-Ω]|\\[A-Za-z]+)\s*=\s*/,""),u=a?`evaluated((${o}),${a[1]},${a[2]},${l})`:`evaluated((${o}),${r.lo},${l})`;e=`${e.slice(0,i)}${i>0&&/[^\s(=]/.test(e[i-1])?" ":""}${u}${e.slice(r.end)}`}return e}const _e={__proto__:null,sine:"sin",cosine:"cos",tangent:"tan",secant:"sec",cosecant:"csc",cotangent:"cot"};const je=100;const Te={__proto__:null},Le={__proto__:null};[..."⁰¹²³⁴⁵⁶⁷⁸⁹"].forEach((e,t)=>{Te[e]=String(t)}),[..."₀₁₂₃₄₅₆₇₈₉"].forEach((e,t)=>{Le[e]=String(t)}),Object.assign(Te,{"⁺":"+","⁻":"-","⁼":"=","⁽":"(","⁾":")","ᵃ":"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(Le,{"₊":"+","₋":"-","₌":"=","₍":"(","₎":")","ₐ":"a","ₑ":"e","ₕ":"h","ᵢ":"i","ⱼ":"j","ₖ":"k","ₗ":"l","ₘ":"m","ₙ":"n","ₒ":"o","ₚ":"p","ᵣ":"r","ₛ":"s","ₜ":"t","ᵤ":"u","ᵥ":"v","ₓ":"x"});const Fe=new RegExp(`[${Object.keys(Te).join("")}]+|[${Object.keys(Le).join("")}]+`,"g");const Ze={__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"},Ce=new RegExp(`(?<![\\w.,^_])(\\d+)[ \\t]?([${Object.keys(Ze).join("")}])`,"g"),Re=/(?<![\w.,^_/])(\d+)[ \t]+([1-9]\d*)\/(\d+)(?![\d./^!])/g,Be=/(?<![\w.,^_])(\d+)\s*\\[dtc]?frac\s*(?:\{\s*(\d+)\s*\}\s*\{\s*(\d+)\s*\}|(\d)(\d)(?!\d))/g;function Pe(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 De(e,t){const n=[];let r=0,s=0;for(let i=0;i<e.length;i++)xe.includes(e[i])?r++:$e.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 We(e,t,n){let r=0;const s=new RegExp(`\\b${n}\\b`,"iy");for(let n=t;n<e.length;n++)if(xe.includes(e[n]))r++;else if($e.includes(e[n])){if(--r<0)return-1}else if(0===r&&(s.lastIndex=n,s.test(e)))return n;return-1}function Ue(e,t){let n=0;for(let r=t;r<e.length;r++)if(xe.includes(e[r]))n++;else if($e.includes(e[r])&&--n<0)return r;return e.length}function Ve(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(xe.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 Ge(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 Qe(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 Xe=new Set(["pmatrix","bmatrix","vmatrix"]);function Je(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 Xe.has(r)?r+"("+o.join(", ")+")"+a:"["+o.join(", ")+"]"+a}function Ye(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 Ke(e){const{lower:t,upper:n,next:r}=function(e){let t="",n="",r=0;return"_"===e[0]&&([t,r]=Ye(e,0),"^"===e[r]&&([n,r]=Ye(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(xe.includes(e[n]))t++;else if($e.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 et(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($e.includes(n[e])?r--:xe.includes(n[e])&&r++,0===r)return"("+n.slice(0,e)+","+t+")"+n.slice(e+1);return!1}function tt(e){return"{"===e[0]||e.length<2?e:"{"+e[0]+"}{"+e[1]+"}"+e.slice(2)}const nt=/[A-Za-z\u0370-\u03FF]/;function rt(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 st(e,t){const n=/^\^(?:\{(\d+)\}|(\d))/.exec(e.slice(t));return n?[Number(n[1]??n[2]),t+n[0].length]:[1,t]}function it(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 ot(e,t){if(xe.includes(e[t])){let n=0;for(let r=t;r<e.length;r++)if(xe.includes(e[r]))n++;else if($e.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(xe.includes(e[r]))n++;else{if($e.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 at=(e,t,n)=>`der(${e},${t}${n>1?","+n:""})`;const lt="strtktk",ut="ABCDEFGHIJ",ct=e=>lt+[...String(e)].map(e=>ut[e]).join(""),ht=new RegExp(`^${lt}[${ut}]+$`);function ft(e){let t="";for(let n=0;n<e.length;n++){const r=e[n];if('"'===r||"`"===r){const r=pt(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=pt(e,n);t+=e.slice(n,r+1),n=r}else t+=r}return t}function pt(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 mt=new RegExp(`${lt}[${ut}]+|§\\d+§`,"g");function dt(e,t){return t&&0!==t.size?e.map(e=>"string"!=typeof e?e:e.replace(mt,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 gt={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; })",times:"((a, b) => { const L = Array.isArray; const m = (v) => L(v) && v.length > 0 && v.every((r) => L(r) && r.length > 0 && r.length === v[0].length && !r.some(L)) && (v.length > 1 || v[0].length > 1); const l = (v) => L(v) && v.length > 0 && !v.some(L); const p = (A, B) => (A[0].length === B.length ? A.map((r) => B[0].map((_, j) => r.reduce((s, x, k) => s + x * B[k][j], 0))) : NaN); const e = (x, y) => (L(x) && L(y) ? (x.length === y.length ? x.map((t, i) => e(t, y[i])) : NaN) : L(x) ? x.map((t) => e(t, y)) : L(y) ? y.map((t) => e(x, t)) : x * y); if (m(a) && m(b)) return p(a, b); if (m(a) && l(b)) { const c = p(a, b.map((y) => [y])); return L(c) ? c.map((r) => r[0]) : c; } if (l(a) && m(b)) { const c = p([a], b); return L(c) ? c[0] : c; } return e(a, b); })",same:"((a, b) => { const s = (x, y) => (Array.isArray(x) && Array.isArray(y) ? x.length === y.length && x.every((v, i) => s(v, y[i])) : x == y); return s(a, b); })",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.abs(n % 2) === 1 ? -Math.pow(-x, 1 / n) : Math.pow(x, 1 / n)))",contains:"((s, t) => { const f = (x) => (x == null ? String() : String(x)).replace(/[A-Z]/g, (c) => String.fromCharCode(c.charCodeAt(0) + 32)); return f(s).includes(f(t)); })",startswith:"((s, t) => { const f = (x) => (x == null ? String() : String(x)).replace(/[A-Z]/g, (c) => String.fromCharCode(c.charCodeAt(0) + 32)); return f(s).startsWith(f(t)); })"},vt="lambda x: str().join(chr(ord(c) + 32) if 65 <= ord(c) <= 90 else c for c in (str() if x is None or x != x else str(int(x)) if isinstance(x, float) and x.is_integer() else str(x)))",bt=`lambda s, t, f=${vt}: f(t) in f(s)`,yt=`lambda s, t, f=${vt}: f(s).startswith(f(t))`,wt={contains:`(${bt})`,startswith:`(${yt})`},xt={contains:`np.vectorize(${bt}, otypes=[bool])`,startswith:`np.vectorize(${yt}, otypes=[bool])`};for(const e of[gt,wt,xt])Object.setPrototypeOf(e,null);const $t="([{",kt=")]}";function qt(e,t){let n=0;for(let r=t;r<e.length;r++)if($t.includes(e[r]))n++;else if(kt.includes(e[r])&&0===--n)return r;return-1}function Mt(e){if(!e.trim())return[];const t=[];let n=0,r=0;for(let s=0;s<e.length;s++)$t.includes(e[s])?n++:kt.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 At(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=qt(e,i);if(o<0)continue;const a=n(Mt(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 St=e=>new RegExp(`(?<![\\w.])(${e})\\s*\\(`,"g"),Nt=e=>`(${e})`,Ot=e=>/^\[.*\]$/s.test(e.trim())?`{${e.trim().slice(1,-1)}}`:e,Et=[...Object.entries(gt),...Object.entries(xt),...Object.entries(wt)];const It={IF:e=>e.length>=2&&`((${e[0]}) ? (${e[1]}) : (${e[2]??"false"}))`,AND:e=>e.length&&`(${e.map(Nt).join(" & ")})`,OR:e=>e.length&&`(${e.map(Nt).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]})`,MMULT:e=>2===e.length&&`((${e[0]}) * (${e[1]}))`};function zt(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 _t(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=qt(e,o)+1;else{const t=n.exec(e.slice(o));i=t?o+t[0].length:0,t&&"("===e[i]&&(i=qt(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=zt(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),At(e,/(?<![\w.])([A-Z][A-Z0-9]*(?:\.[A-Z]+)?)\s*\(/g,(e,t)=>It[t[1]]?.(e)||null)}const jt={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"},Tt="strtktk[A-J]+";function Lt(e){for(let t=!0;t;){const n=e;t=(e=e.replace(new RegExp(`(${Tt})\\s*\\|\\|\\s*(${Tt})`,"g"),"$1 + $2"))!==n}const t=new RegExp(`^\\(typeof\\(([^()]*)\\)\\s+IN\\s+\\(${Tt},\\s*${Tt}\\)\\s+AND\\s+(.*)\\)$`,"s");for(let n=e.lastIndexOf("(typeof(");n>=0;n=n>0?e.lastIndexOf("(typeof(",n-1):-1){const r=qt(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=At(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=At(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})`,Nt(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=>jt[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=qt(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 Ft={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"},Zt={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",dot:"np_times",matmul:"np_times",multiply:"np_times",array_equal:"np_equal"};const Ct=e=>e.replace(/(?<![\w.])set\s*\(\s*\)/g,"∅"),Rt={inf:"∞",nan:"NaN"};function Bt(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)=>Ft[t]?`Math.${Ft[t]}`:Zt[t]?Zt[t]:Rt[t]??e),e=e.replace(/(?<![\w.])(?:math|Math)\.(factorial|isfinite|isclose|prod|inf|nan|abs|trunc)\b/g,(e,t)=>Rt[t]??t),e=e.replace(/(?<![\w.])Number\.(isInteger|isFinite)\b/g,(e,t)=>t.toLowerCase()),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)=>Dt[t]??e),e=e.replace(/(?<![\w.])sympy\.(Reals|Integers|Naturals0?|Rationals|Complexes)\b/g,(e,t)=>Dt[t]),e.replace(/(?<![\w.])sympy\.(\w+)/g,(e,t)=>Wt[t]??Pt[t]??e)}(e=e.replace(/(?<![\w.])scipy\.(?:special|integrate)\.(\w+)/g,"$1")),(e=e.replace(/\bMZ_INFINITY\b/g,"∞")).replace(/(?<![\w.])mz_(?=\w+\s*\()/g,"")}const Pt={pi:"π",E:"e",oo:"∞",true:"true",false:"false",nan:"NaN",I:"i"},Dt={Reals:"ℝ",Integers:"ℤ",Naturals:"ℕ",Naturals0:"ℕ",Rationals:"ℚ",Complexes:"ℂ"},Wt={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",Implies:"sympy_implies",Equivalent:"sympy_iff",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:""},Ut={open:"()",Lopen:"(]",Ropen:"[)"};const Vt=e=>{const t=/^\((.*)\)$/s.exec(e.trim());return t?Mt(t[1]):null},Ht=e=>t=>2===t.length&&`${e[0]}${t[0]}, ${t[1]}${e[1]}`,Gt=e=>Vt(e)??[e],Qt={where:e=>3===e.length&&`((${e[0]}) ? (${e[1]}) : (${e[2]}))`,both:e=>2===e.length&&`((${e[0]}) & (${e[1]}))`,either:e=>2===e.length&&`((${e[0]}) ∨ (${e[1]}))`,np_times:e=>2===e.length&&`((${e[0]}) * (${e[1]}))`,np_equal:e=>2===e.length&&`((${e[0]}) = (${e[1]}))`,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]}) ∈ ${Ot(e[1])})`,contains:e=>2===e.length&&`((${e[1]}) ∈ ${Ot(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]}))`,radians:e=>1===e.length&&`((${e[0]})°)`,degrees:e=>1===e.length&&`((${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]}))`,...Object.fromEntries([2,3,4].map(e=>[`mat${e}`,t=>t.length===e*e&&`[${Array.from({length:e},(n,r)=>`[${Array.from({length:e},(n,s)=>t[s*e+r]).join(", ")}]`).join(", ")}]`])),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(Nt).join(" & ")})`,sympy_or:e=>e.length&&`(${e.map(Nt).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_implies:e=>2===e.length&&`((${e[0]}) \\implies (${e[1]}))`,sympy_iff:e=>2===e.length&&`((${e[0]}) \\iff (${e[1]}))`,sympy_nor:e=>2===e.length&&`((${e[0]}) \\nor (${e[1]}))`,sympy_piecewise:e=>{const t=e.map(Vt);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:Ht("[]"),sympy_interval_open:Ht("()"),sympy_interval_Lopen:Ht("(]"),sympy_interval_Ropen:Ht("[)"),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=Gt(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&&Gt(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&&Gt(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:Xt("sum"),prod:Xt("prod")};function Xt(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=Mt(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 Jt(e){e=function(e){for(let t=e.lastIndexOf("(lambda");t>=0;t=t>0?e.lastIndexOf("(lambda",t-1):-1){const n=qt(e,t);if(n<0||"("!==e[n+1])continue;const r=qt(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=Mt(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=At(e,St("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=At(e,St(Object.keys(Qt).join("|")),(e,t)=>Qt[t[1]](e)||null);for(let t=(e=At(e,St("float"),(e,t,n)=>{if(1!==e.length)return null;const r=/^\s*\.is_integer\(\s*\)/.exec(n);return r?[`((${e[0]}) ∈ ℤ)`,r[0].length]:`(${e[0]})`})).lastIndexOf(".includes(");t>=0;t=t>0?e.lastIndexOf(".includes(",t-1):-1){const n=t+9,r=qt(e,n);let s=t;if(kt.includes(e[t-1])){let n=0;for(s=t-1;s>=0;s--)if(kt.includes(e[s]))n++;else if($t.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)}) ∈ ${Ot(e.slice(s,t))})${e.slice(r+1)}`)}return e}for(const e of[It,jt,Ft,Zt,Pt,Dt,Wt,Ut,Qt,Rt])Object.setPrototypeOf(e,null);const Yt=String.raw`(?:\([^()]*\)|\[[^\[\]]*\]|\{[^{}]*\}|(?<![\w.′^])[\w.′^]+)`,Kt=e=>e.trim().split(/\s+/).join(String.raw`\s+`),en=e=>new RegExp(String.raw`(?<![\w.])${Kt(e)}(?![\w.])`,"gi"),tn=[["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","="]],nn="[<>≤≥=≠≈]",rn={second:2,third:3,fourth:4,fifth:5,sixth:6,seventh:7,eighth:8,ninth:9,tenth:10};Object.setPrototypeOf(rn,null);const sn=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",arcsecant:"arcsec",arccosecant:"arccsc",arccotangent:"arccot","hyperbolic sine":"sinh","hyperbolic cosine":"cosh","hyperbolic tangent":"tanh",floor:"floor",ceiling:"ceil"}).sort((e,t)=>t[0].length-e[0].length),on=[["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 an integer","∈ ℤ"],["is not an integer","∉ ℤ"],["is a natural number","∈ ℕ"],["is a real number","∈ ℝ"],["is real","∈ ℝ"],["is a rational number","∈ ℚ"],["is rational","∈ ℚ"],...[["the integers","ℤ"],["the natural numbers","ℕ"],["the real numbers","ℝ"],["the rational numbers","ℚ"],["the complex numbers","ℂ"]].flatMap(([e,t])=>[[`is not in ${e}`,`∉ ${t}`],[`is in ${e}`,`∈ ${t}`]])],an=/(?<![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;tn.map(([e])=>e),on.map(([e])=>e),sn.map(([e])=>`${e} of`);const ln=de([[" 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 ","→"],["===","=...="]]),un=de([...ye,...function(){const e=[],t=(t,n)=>{e.push([t,n],[t+"(",n+"("])};for(const n of["sin","cos","tan","cot","csc","sec"]){e.push(["Math."+n+"(",n+"("],["\\"+n+"(",n+"("],["\\"+n,n]);for(const e of["sin","cos","tan"].includes(n)?["","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}()]),cn=[["code",function(e){return/^\s*=|[(.%^<_eE]|\|\||\bif\b|\b(?:True|False|None|TRUE|FALSE|NULL)\b/.test(e)?(/^\s*=(?!=)/.test(e)&&(e=_t(e)),e=function(e){for(const[t,n]of Et)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]?qt(e,s):-1;if(i<0)continue;let o=e.slice(s+1,i);"gcd"===t&&(o=o.trim().replace(/^\[|\]$/g,""));const a="times"===t||"same"===t?Mt(o):null,l="factorial"===t?`((${o})!)`:2===a?.length?`((${a[0]}) ${"times"===t?"*":"="} (${a[1]}))`:`${t}(${o})`;e=e.slice(0,r)+l+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=qt(e,n),s=e.lastIndexOf("Number(",t);r<0||s<0||qt(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),e=function(e){return e.includes("set")?Ct(At(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&&qt(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=Bt(e=Lt(e=(e=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($t.includes(e[t]))s++;else{if(kt.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(kt.includes(e[t]))s++;else{if($t.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=Jt(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(!an.test(e))return e;let t=e;const n=(e,n,r,s="∈")=>{t=t.replace(new RegExp(String.raw`(?<![\w.])${Kt(e)}\s+(${Yt})\s+(?:and|to)\s+(${Yt})(?:\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+(${Yt})\s+to\s+(${Yt})`,"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`(${Yt})\s+`;t=t.replace(new RegExp(r+String.raw`is\s+(not\s+)?within\s+(${Yt})\s*(%|\s+percent)?\s+of\s+(${Yt})`,"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+(${Yt})`,"gi"),"(($1) mod ($2) = 0)"),t=t.replace(new RegExp(r+String.raw`is\s+(not\s+)?divisible\s+by\s+(${Yt})`,"gi"),(e,t,n,r)=>`((${t}) mod (${r}) ${n?"≠":"="} 0)`),t=t.replace(new RegExp(String.raw`(${Yt})\s+divides\s+(${Yt})`,"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)`),t=t.replace(new RegExp(r+String.raw`is\s+(not\s+)?a\s+whole\s+number(?![\w.])`,"gi"),(e,t,n)=>n?`((${t}) ∉ ℤ ∨ (${t}) < 0)`:`((${t}) ∈ ℤ & (${t}) ≥ 0)`);for(const[e,n]of on)t=t.replace(en(e),` ${n} `);t=t.replace(en("is not in")," ∉ ").replace(en("is in")," ∈ ").replace(en("is an element of")," ∈ ");for(const[e,n]of tn)t=t.replace(en(e),` ${n} `);t=t.replace(en("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`(${Yt})\s*(${nn})\s*(${Yt})\s+(and|or)\s+(${nn})`,"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+(${Yt})`,"gi"),"abs($1)"),t=t.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?square\s+root\s+of\s+(${Yt})`,"gi"),"sqrt($1)"),t=t.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?cube\s+root\s+of\s+(${Yt})`,"gi"),"root(3, $1)"),t=t.replace(new RegExp(String.raw`(${Yt})\s+to\s+the\s+power\s+of\s+(${Yt})`,"gi"),"($1)^($2)"),t=t.replace(new RegExp(String.raw`(${Yt})\s+to\s+the\s+(${Object.keys(rn).join("|")}|(\d+|n)(?:st|nd|rd|th))(?:\s+power)?(?![\w.])`,"gi"),(e,t,n,r)=>`(${t})^(${rn[n.toLowerCase()]??r})`),t=t.replace(new RegExp(String.raw`(${Yt})\s+to\s+the\s+(${Yt})(?![\w.])`,"gi"),"($1)^($2)");for(const[e,n]of sn)t=t.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?${Kt(e)}\s+of\s+(${Yt})`,"gi"),`${n}($1)`);t=t.replace(new RegExp(String.raw`(${Yt})\s+squared(?![\w.])`,"gi"),"($1)^2"),t=t.replace(new RegExp(String.raw`(${Yt})\s+cubed(?![\w.])`,"gi"),"($1)^3"),t=t.replace(new RegExp(String.raw`(?<![\w.])half\s+of\s+(${Yt})`,"gi"),"($1)/2"),t=t.replace(new RegExp(String.raw`(?<![\w.])twice\s+(${Yt})`,"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+)${Kt(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",ln],["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(;we(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(;we(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(Ce,(e,t,n)=>`(${t}+${Ze[n]})`),e=e.replace(Re,(e,t,n,r)=>Number(n)<Number(r)&&3!==n.length?`(${t}+${n}/${r})`:e),e.replace(Be,(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(Fe,e=>{const t=e[0]in Te;return`${t?"^":"_"}{${[...e].map(e=>(t?Te:Le)[e]).join("")}}`})}(e))),e=function(e){return e.replace(/(?:\{\s*\}|(?<![\w}\])′]))_\s*(?:\{\s*([^{}]+?)\s*\}|([A-Za-z0-9]+?))\s*(?:\\mathrm\{([CP])\}|([CP]))\s*_\s*(?:\{\s*([^{}]+?)\s*\}|([A-Za-z0-9]))/g,(e,t,n,r,s,i,o)=>`${"C"===(r??s)?"comb":"perm"}(${t??n},${i??o})`)}(function(e){return e.replace(/(?<![A-Za-z\\])([A-Za-z])\^\s*\{?\s*\(\s*([1-9]\d*)\s*\)\s*\}?(?=\s*\()/g,(e,t,n)=>{if(n.length>3||Number(n)>je)throw new Error(`A derivative f^{(n)} is read up to n = ${je}`);return t+"′".repeat(Number(n))})}(function(e){return e.replace(/(?<![A-Za-z\\])(arc)?(sine|cosine|tangent|secant|cosecant|cotangent)(?![A-Za-z])(?=\s*\(|\s+(?:[A-Za-z](?![A-Za-z])|\d|\\))/gi,(e,t,n)=>(t?"arc":"")+_e[n.toLowerCase()])}(e))),e=function(e){if(/\\[io]*int|∫|(?<![A-Za-z])int\(|\\partial|∂|(?<![A-Za-z])d\s*\/\s*d|frac\s*\{\s*(?:\\mathrm\s*\{\s*d\s*\}|\\operatorname\s*\{\s*d\s*\}|d)/.test(e))return e;const t=[];for(const n of e.matchAll(qe)){const r=e.slice(0,n.index),s=e.slice(n.index+n[0].length),i="d"!==n[1];if(!i&&(/[A-Za-z0-9\\^_/]$|frac\s*\{$/.test(r)||/^\s*[/}]/.test(s)&&!/\{\s*$/.test(r)))continue;const o=i||/\\[,;:! ]\s*$/.test(r);t.push({m:n,strong:o})}const n=t.length>=2?t:t.filter(e=>e.strong);for(const{m:t}of n.reverse())e=e.slice(0,t.index)+ke+t[2]+e.slice(t.index+t[0].length);return e}(e),/\\/.test(e)||(e=Me(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=We(e,n+2,"then");if(r<0)return e;const s=e.slice(n+2,r),i=We(e,r+4,"else"),o=Ue(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.replace(/(?<![.\w=])\.\.\.(?![.\w=])/g,"⋯").replace(/∅/g,"\\{\\}")),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=He(e);for(let t=0;t<e.length-1;t++)if("?"===e[t]&&":"!==e[t+1])e=Ve(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=e.replace(/(?<![\d.])\d{1,3}(?:[ \u00A0\u202F]\d{3})+(?![\d])/g,e=>e.replace(/[ \u00A0\u202F]/g,""))).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)||/[A-Za-z\u0370-\u03FF′]/.test(r)&&/^\\[A-Za-z]/.test(e.slice(n+t.length,n+t.length+2))&&!/\\[A-Za-z]+$/.test(e.slice(0,n))||/[A-Za-z\u0370-\u03FF′]/.test(r)&&/\d/.test(s)&&!/\\[A-Za-z]+$/.test(e.slice(0,n))?" ":/\d/.test(r)&&/\d/.test(s)&&!/\\[A-Za-z]+\s*\d*$/.test(e.slice(0,n))?"*":""})}],["symbols",un],["bar",function(e){let t=0;for(let n=e.indexOf(d,t);n>=0;n=e.indexOf(d,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&&hn(),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)+at(e.slice(r,t+1),"x",s)+e.slice(t+1+s),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&&nt.test(e[t-1]);let r,s=null,i=t;if(e.startsWith("frac{",t)){const n=rt(e,t+4),r=n&&rt(e,n[1]);s=r&&it(n[0],r[0]),s&&(i=r[1])}else if("d"===e[t]&&!n){let[n,r]=st(e,t+1),o="";if(nt.test(e[r]??"")&&"/"===e[r+1]&&(o=e[r++]),"/"===e[r]&&"d"===e[r+1]&&nt.test(e[r+2]??"")){const t=e[r+2],[,a]=st(e,r+3);s={n:n,of:o,by:t},i=a}}if(s){if(s.of)r=at(s.of,s.by,s.n);else{const[t,n]=ot(e,i);if(!t)continue;r=at(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=Je(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"+Qe(e.slice(t+1)):"sqrt"===r(4)&&(e=e.slice(0,t-4)+"sqrt"+Qe(e.slice(t+1)));else if("⌊"===n||"⌈"===n)e=e.slice(0,t)+Ge(e.slice(t));else if("t"===n)"\\int"===s(3)&&(e=e.slice(0,t-3)+Ke(e.slice(t+1)));else if("m"===n)"\\binom"===s(5)&&(e=e.slice(0,t-5)+"\\binom"+tt(e.slice(t+1)));else if("d"===n&&"dd"===s(1)&&"("===e[t+2]){const n=et(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(d);t>=0;t=e.indexOf(d)){const n=hn;e.startsWith("(der(",t+1)||n();const r=fn(e,t+1,"(",")"),s=fn(e,t+5,"(",")");(s<0||r!==s+1)&&n();const i=pn(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=fn(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 f=a.includes("=")?a:`${c}=${a}`;e=`${e.slice(0,t)}der(${u},${f}${h?`,${h}`:""})${e.slice(l+1)}`}return e}],["tidy",e=>e.replace(/ {2,}/g," ").trim()]],hn=()=>{throw new Error("A bar with one limit (\\left. … \\right|_{x = a}) is read only after a derivative, \\left.\\frac{d}{dx} f\\right|_{x=a}; with two, \\left. F \\right|_a^b, it is F at b minus F at a")};function fn(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 pn(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 mn(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=ct(t.size);t.set(l,s+o+s),n+=l,r=i+1}return{text:n,strings:t}}(ft(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&&dn.test(e.slice(0,i));if(gn(e,i)||a&&"{"===e[i+2]?i+=1:o=a,!e.startsWith("{{",i)){s=i;continue}const l=vn(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=ct(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 cn){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 dn=/(?:\\[A-Za-z]+\*?|[\^_}\]])$/;function gn(e,t){let n=0;for(;"\\"===e[t-1-n];)n++;return n%2==1}function vn(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 bn=Object.keys(g).filter(e=>100===g[e]&&/^[a-z]{2,}$/.test(e)),yn=["frac"],wn=[...Object.keys(T),"pi","tau","inf","infinity","exp"],xn="\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+/),$n=new Set([...wn,...xn,"simplify","expand","factor","cancel","diff","integrate","solve","approx","limit","true","false","null","undefined","unchanged","deg","mod","pmod","NaN","Infinity"]),kn=/^[a-zA-ZͰ-Ͽ]$/,qn=new Set(["f","g","h","u","v","F","G","H"]),Mn=e=>bn.includes(e)||yn.includes(e),An=[...bn,...yn,...wn].sort((e,t)=>t.length-e.length),Sn=[...bn,...yn,"pi"].sort((e,t)=>t.length-e.length);function Nn(e,t=An){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 On(e){if(Mn(e))return!0;const t=Nn(e,Sn);return t.length>1&&Mn(t[t.length-1])&&!$n.has(e)}function En(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=>kn.test(e)))||1===e.length||$n.has(e)||Mn(e))return[e];var r;if("Δ"===e[0]&&2===e.length)return[e];if("latex"===t)return In(Nn(e),n);if(e.length<=2)return[...e];const s=In(Nn(e,Sn),n),i=s.findIndex(e=>e.length>1);if(i<0)return[e];if("pi"===s[i]&&!s.some(e=>bn.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 In(e,t){const n=e[e.length-1];return t||!bn.includes(n)?e:[...e.slice(0,-1),...n]}const zn="§",_n=/[A-Za-zͰ-Ͽ′]/,jn=e=>/^[A-Za-zͰ-Ͽ][A-Za-zͰ-Ͽ′]*$/.test(e);function Tn(e,t="plain"){if("string"!=typeof e)throw new Error("Tokenizer input must be a string");const n=[];let r="";const s=e=>{r&&(jn(r)?n.push(...function(e,t,n){if((e=>ht.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 qn.has(e)?[i+e]:[e];if(v(e))return[e];const n=En(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 En(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===zn){s(o);const r=e.indexOf(zn,t+1);if(r<0)throw new Error(`An unmatched ${zn}`);const a=e.slice(t,r+1);n.push(y.includes(e[r+1])?i+a:a),t=r;continue}if("ⅆ"===o&&/[A-Za-z\u0370-\u03FF]/.test(e[t+1]??""))r&&s(o),r="",n.push("d"+e[t+1]),t+=1;else{if(jn(r)&&/[0-9]/.test(o)&&v(r+o)){const{op:s,end:i}=Ln(e,t,r+o);n.push(s),r="",t=i;continue}if(_n.test(o)&&"′"!==o&&x(r)&&(n.push(r),r=""),_n.test(o)&&(""===r?"′"!==o:jn(r)))r+=o;else if(/[0-9]/.test(o)&&jn(r)&&!On(r))r+=o;else if(jn(r)&&s(" "===o?e[t+1]:o),"(){}[]".includes(o))r&&n.push(...Fn(r,o)),r="",n.push(o);else if("_"!==o&&" "!==o){if(v(r+o)){const{op:s,end:i}=Ln(e,t,r+o);n.push(s),r="",t=i;continue}if(v(o)){s(o);const{op:r,end:i}=Ln(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 Ln(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 Fn(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)||Mn(e)||x(e[0])?[e]:[i+e]}const Zn=70,Cn=100,Rn="%mod",Bn=/^d[A-Za-z\u0370-\u03FF]$/,Pn=e=>y.includes(e),Dn=e=>w.includes(e),Wn=e=>o(e)||g[e]===Cn&&"_"!==e,Un=new Set(["\\comb","\\perm","comb","perm"]),Vn={frac:"/","\\binom":"\\binom"},Hn=new Set(["<",">","≤","≥","=","==","===","≠","≠=","!=","!==","&","|","\\not","\\xor","\\implies","\\iff","∈","∉","true","false"]),Gn={"\\comb":"comb","\\perm":"perm",deg:"°","π":"pi","∨":"|"};class Qn{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(Dn(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||Dn(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===Rn)return{lbp:Zn,run:()=>{this.next(),this.parseExpression(Zn),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:Cn,run:()=>{this.next(),this.parseScript(),this.emit("_")}};if(Un.has(e))return{lbp:Cn,run:()=>{this.next(),this.parseExpression(Cn),this.emit(e)}};const n=g[e];if("="===e&&void 0!==n)return{lbp:n,run:()=>this.equals(n)};if(void 0!==n&&!Wn(e)&&"\\not"!==e&&!(e in Vn)){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||Wn(e)||Bn.test(e)?Zn:71,run:()=>{this.parseExpression(Zn),this.emit("*")}}}startsOperand(e){return void 0===e||Dn(e)||"|"===e?"|"===e:e!==Rn&&(!!(Pn(e)||Wn(e)||e in Vn)||!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(Zn,!0),this.emit("mod")}equals(e){this.next(),this.parseExpression(e),Hn.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(Pn(n))e++;else if(Dn(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(Pn(e))return this.bracket(e,"{"===e&&("∈"===t||"∉"===t));if("|"===e)return this.absolute();if("-"===e||"+"===e){return"^"===t&&(void 0===n||Dn(n))||Pn(t)&&Dn(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 Vn)return this.parseScript(),this.parseScript(),this.emit(Vn[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(Wn(e))return this.functionCall(e);if(e===Rn)throw new Error("'%' is missing an operand");if(Dn(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(Dn(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();Dn(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(Pn(e))return this.parseOperand();if("-"===e||"+"===e)return this.parseOperand();if(Wn(e))return this.parseOperand();if(this.next(),void 0===e||Dn(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&&!Pn(this.peek()))return this.emit(e);this.argument(),this.emit(e),t&&this.emit(...t,"^")}argument(){const e=this.peek();if(Pn(e))return this.next(),this.bracket(e);this.parseExpression(Zn,!0)}}function Xn(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(qn.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)||Pn(r)||Dn(r)||"_"===r||o(r)||x(r)?n.push(r):n.push(...Jn(r,t));return n}function Jn(e,t){if("%"===e)return[Rn];if(!e.includes("%"))return Yn(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(Rn),""!==e&&r.push(...Yn(e,t))}),r}function Yn(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,Xn(Tn(s,t),t))];var s}for(const e of[Vn,Gn])Object.setPrototypeOf(e,null);const Kn=new Set(["()","[]","{}","(]","[)"]),er={pow:"^",sqrtpow:"root","\\binom":"comb","\\comb":"comb","\\perm":"perm",frac:"/","==":"=","!==":"≠=",...Object.fromEntries(Object.keys(m).map(e=>[e,"*"]))},tr=new Set(["round","fixed","der"]),nr=e=>o(e)||100===g[e];function rr(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(Kn.has(o)){const t=s(r(o));if(!t.length&&"{}"!==o&&!nr(e[l+1]))throw new Error("Empty brackets");return void n.push(A(o,t))}const u=er[o]??o,c=a(u);if(!c){if("?"===o||"abs("===o)throw new Error(`Unmatched '${o[0]}'`);return void n.push(N(o))}let h;if(nr(o)&&Kn.has(e[l-1])&&n[n.length-1]?.op===e[l-1])h=n.pop().args;else{let e=c.arity===t||tr.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 f=function(e,t){switch(e){case"sqrt":if(2===t.length)return A("root",t);break;case"round":if(1===t.length)return A("round",[t[0],q(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 A("sum"===e?"\\sumidx":"\\prodidx",t);break}case"evaluated":if(3===t.length)return A("evaluated",[t[0],M(j(t[0])||"x"),t[1],t[2]]);break;case"det":if(t.length>1&&t.every(e=>"op"===e.type&&"[]"===e.op))return A("det",[A("[]",t)]);break;case"fixed":if(1===t.length)return A("fixed",[t[0],q(2)]);break;case"der":if(1===t.length)return A("der",[t[0],M("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=A("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 A("ln",[t[1]]);break;case"lim":return ir(e,t),A("lim",function(e){const t=e=>{if("op"!==e.type)return null;if("^"===e.op&&"symbol"===e.args[1].type&&sr[e.args[1].value])return{point:e.args[0],side:sr[e.args[1].value]};const n=e.args.length?t(e.args[e.args.length-1]):null;return n&&{point:{...e,args:[...e.args.slice(0,-1),n.point]},side:n.side}},[n,r,s]=e;if(2===e.length&&"op"===r.type&&"→"===r.op){const[e,s]=r.args,i=t(s);if(i)return[n,e,i.point,M(i.side)]}const i=3===e.length&&t(s);return i?[n,r,i.point,M(i.side)]:e}(t));case"\\:if":if(2===t.length||3===t.length)return A("?:",[t[0],t[1],t[2]??M("unchanged")]);throw new Error("if() takes a condition, a value, and optionally an alternative")}return ir(e,t),A(e,t)}(u,h);m[o]&&"*"===f.op&&(f.written=m[o]),n.push(f)}),1!==n.length)throw new Error(n.length?"Some values are not connected by an operator":"Empty expression");const o=["=","<",">","≤","≥","≠","≈","≡","∈","∉"],l=n[0];return l.list&&l.list.length>1&&l.list.every(e=>"op"===e.type&&o.includes(e.op))?l.list.reduce((e,t)=>A("&",[e,t])):i(n[0],"end")}const sr={"\\+":"r","\\-":"l"};function ir(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[er,sr])Object.setPrototypeOf(e,null);const or=new RegExp(`[${Object.keys(m).join("")}]`,"g"),ar=e=>e.replace(or,"*"),lr=/\\(?:text|textrm|textit|mathrm|mathit|operatorname)\{\s*([A-Za-z][A-Za-z0-9 ]*[A-Za-z0-9])\s*\}/g;const ur=e=>/^[a-z][a-z0-9]*$/.test(e)&&v(e);function cr(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=De(e.slice(t+13,n),"\\\\").map(e=>De(e,"&")).filter(e=>e.join("").trim());let s=null;const i=/=|<|>|\\(?:le|ge|leq|geq|neq|ne|lt|gt)(?![A-Za-z])/;if(r.length>1&&r.every(e=>1===e.length&&i.test(e[0])))s=r.map(e=>`(${e[0].trim().replace(/\s*[,;.]$/,"")})`).join(" \\land "),e=e.slice(0,t)+`(${s})`+e.slice(n+11);else{for(let e=r.length-1;e>=0;e--){const t=r[e][0].trim().replace(/\s*[,;]$/,""),n=Pe(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=function(e){return e=ze(e),e=Me(e),e=e.replace(/\\(?:[Bb]igg?)[lrm]?(?![A-Za-z])\s*/g,""),e=e.replace(/\^\s*(?:\\circ\b|\{\s*\\circ\s*\})|\\degree\b|\\textdegree\b/g,"°"),e=e.replace(/\\(?:cdots|ldots|dotsb|dotsc|dots)(?![A-Za-z])/g,"⋯"),e=e.replace(/(\d*)\.(\d*)\\overline\s*\{\s*(\d+)\s*\}/g,(e,t,n,r)=>`${t||"0"}.${n}${r}${r}..`),e=e.replace(/\\(?:emptyset|varnothing)(?![A-Za-z])/g,"\\{\\}"),e=e.replace(/\(\s*([A-Za-z])\s*\\circ\s*([A-Za-z])\s*\)\s*\(([^()]*)\)/g,"$1($2($3))"),e}(e),e.replace(/\{\}\^\{([^{}]*)\}\s*\\mathrm\{P\}\s*_\{([^{}]*)\}/g,"\\perm($1,$2)")):/[\]|]\s*_/.test(e)?ze(e):e}let hr=null;function fr(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=ft(e);let s="";for(let i=0;i<r.length;i++){const o=r[i];if('"'===o||"`"===o||"'"===o){const o=pt(r,i);s+=e.slice(i,o+1).replaceAll(t,n),i=o}else s+=e[i]}return s}(e,zn,"")).includes(zn))throw new Error(`The character ${zn} 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=`${zn}${r.size}${zn}`,r.set(t,e),s.set(e,t)),t};e=e.replace(lr,(e,t)=>ur(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}}(cr(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?hr:t.blocks;return mn(e,{evaluate:n?e=>n(e,t.scope):void 0})}(o,{blocks:t.blocks,scope:t.scope}),f=e=>dt(dt(e,c),a).map(e=>"string"==typeof e?e.replaceAll("",zn):e);n.mode=l,n.cleaned=ar(f([u])[0]),n.cleanSteps=h.map(([e,t])=>[e,ar(t)]);const p=Tn(u,l);n.tokens=p.map(ar);const m=f(function(e,t="plain"){return new Qn(Xn(e,t)).parseAll().map(e=>Gn[e]??e)}(p,l));n.rawPostfix=m.map(ar);const d={},g=I(rr(m),d);n.postfix=g,n.written=d,n.tree=E(g),Object.keys(d).length&&_(n.tree,e=>{d[e.id]&&(e.written=d[e.id])})}catch(e){n.error=e instanceof RangeError?"Nested too deeply":e.message}return n}const pr=e=>"string"==typeof e&&e.length>80?`${e.slice(0,77)}…`:e;function mr(e,t={}){const n=fr(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 "${pr(e)}": ${n.error}`)}function dr(e,t={}){const n=fr(e,t);if(n.error)throw new Error(`Failed to parse expression "${pr(e)}": ${n.error}`);return n.tree}const gr=(e,t)=>"string"==typeof e?dr(e,t):z(e),vr=e=>Array.isArray(e)&&0===e.length,br=me({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(Tr+=e/16,Tr>jr)throw new Error("Too much to work out")},fail:e=>{throw new Error(e)}}),yr=e=>fe(e)&&(e.length>1||e[0].length>1),wr=e=>pe(e)&&!yr(e),xr=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},$r=(e,t)=>yr(e)&&yr(t)?br.times(e,t):yr(e)&&wr(t)?br.timesVector(e,t):wr(e)&&yr(t)?br.vectorTimes(e,t):xr((e,t)=>e*t)(e,t),kr=(e,t)=>n=>{const r=n.length>1&&n.every(wr)?n:n[0];if(!fe(r))throw new Error(`${t}() needs a matrix`);return e(r)},qr=(e,t)=>([n,r])=>{if(!pe(n)||!pe(r))throw new Error(`${t}() needs two lists`);return e(n,r)},Mr={det:kr(br.det,"det"),inv:kr(br.inverse,"inv"),inverse:kr(br.inverse,"inverse"),transpose:kr(br.transpose,"transpose"),trace:kr(br.trace,"trace"),tr:kr(br.trace,"tr"),rank:kr(br.rank,"rank"),rref:kr(br.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 br.identity(e)},dot:qr(br.dot,"dot"),cross:qr(br.cross,"cross"),linsolve:([e,t])=>{if(!fe(e)||!Array.isArray(t))throw new Error("linsolve() needs a matrix and a list");return br.solve(e,t)}},Ar=(e,t)=>e.args.map(e=>"op"===e.type&&"[]"===e.op?e.args.map(e=>Fr(e,t)):[Fr(e,t)]),Sr={pi:Math.PI,"π":Math.PI,e:Math.E,tau:2*Math.PI,"τ":2*Math.PI,"∞":1/0,"-∞":-1/0,true:!0,false:!1,"°":Math.PI/180},Nr=(e,t)=>t?Nr(t,e%t):Math.abs(e),Or=(e,t)=>(e%t+t)%t,Er=(e,t)=>Array.isArray(e)&&Array.isArray(t)?e.length===t.length&&e.every((e,n)=>Er(e,t[n])):e==t,Ir={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=>Mr.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,arcsec:e=>Math.acos(1/e),arccsc:e=>Math.asin(1/e),arccot:e=>Math.PI/2-Math.atan(e),arcsinh:Math.asinh,arccosh:Math.acosh,arctanh:Math.atanh},zr={"+":(e,t)=>Array.isArray(e)||Array.isArray(t)?xr((e,t)=>e+t)(e,t):e+t,"-":(e,t)=>Array.isArray(e)||Array.isArray(t)?xr((e,t)=>e-t)(e,t):e-t,"*":$r,"/":(e,t)=>yr(t)?$r(e,br.inverse(t)):Array.isArray(e)||Array.isArray(t)?xr((e,t)=>e/t)(e,t):e/t,"^":(e,t)=>{if(!yr(e))return Array.isArray(e)?xr((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 br.power(e,BigInt(t))},mod:Or,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)},"=":Er,"===":(e,t)=>e===t,"≠":(e,t)=>!Er(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),"\\implies":(e,t)=>!e||Boolean(t),"\\iff":(e,t)=>Boolean(e)===Boolean(t)},_r={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(Nr,0),"()":e=>e,"[]":e=>e,"{}":e=>e};const jr=5e6;let Tr=0,Lr=0;function Fr(e,t){if(++Tr>jr)throw new Error("Too much to work out");switch(e.type){case"number":return e.value.endsWith("..")?Number(function(e){const t=function(e){const t=/^(-?)(\d*)\.(\d+)\.\.$/.exec(e);if(!t)return null;const[,n,r,s]=t;let i=1;for(let e=1;2*e<=s.length;e++)if(s.slice(-e)===s.slice(-2*e,-e)){i=e;break}const o=s.slice(-i);let a=s;for(;a.endsWith(o);)a=a.slice(0,-i);return{sign:n,whole:r||"0",prefix:a,block:o}}(e);if(!t)return e.replace(/\.+$/,"");const{sign:n,whole:r,prefix:s,block:i}=t;return`${n}${r}.${(s+i.repeat(Math.ceil(20/i.length)+1)).slice(0,Math.max(s.length+i.length,17))}`}(e.value)):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(Sr,e.value))return Sr[e.value];if(R(e.value))return Number(R(e.value));throw new Error(`No value for '${e.value}'`)}const n=ue(e);if(n)return Fr(n,t);const{op:r,args:s}=e;if("?:"===r)return Fr(s[0],t)?Fr(s[1],t):Fr(s[2],t);if("setbuilder"===r)throw new Error("A set described by a condition has no list of values (test membership in it: y ∈ {x | P})");if(("∈"===r||"∉"===r)&&C(e))return Fr(C(e),t);if("∈"===r||"∉"===r){const n=function(e){if("op"!==e.type||"∈"!==e.op&&"∉"!==e.op||2!==e.args.length)return null;const[t,n]=e.args;return"string"===n.type||e.textSearch?{text:t,within:n}:"string"!==t.type||("op"===n.type?te.has(n.op):"symbol"===n.type&&/^[ℝℤℕℚℂ∅]$/u.test(n.value))?null:{text:t,within:n}}(e);if(n){const e=Fr(n.within,t);if(!Array.isArray(e))return re(e).includes(re(Fr(n.text,t)))===("∈"===r)}else if("symbol"===s[1].type&&t&&Object.prototype.hasOwnProperty.call(t,s[1].value)){const e=Fr(s[1],t);if("string"==typeof e)return re(e).includes(re(Fr(s[0],t)))===("∈"===r)}return function(e,t){const[n,r]=e.args,s=Fr(n,t);let i;if("symbol"===r.type&&Zr[r.value])return i=Zr[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=>Fr(e,t)),o="["===r.op[0]?s>=e:s>e,a="]"===r.op[1]?s<=n:s<n;i=o&&a}else{const e=Fr(r,t);i=Array.isArray(e)&&e.includes(s)}return"∈"===e.op?i:!i}(e,t)}if(ne(r)){const[n,r]=function(e){if(2!==e.args.length)throw new Error('startswith takes a value and the text it starts with: startswith(name, "Mc")');return e.args}(e).map(e=>Fr(e,t));return re(n).startsWith(re(r))}if("random"===r)return Math.random();if("evaluated"===r){const[e,n,r,i]=s,o=r=>Fr(e,{...t,[n.value]:Fr(r,t)});return o(i)-o(r)}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:j(n);if(!a)throw new Error(`Can't evaluate '${r}' without an index`);const l=Fr(i,t),u=Fr(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=Fr(n,{...t,[a]:e});c="\\sumidx"===r?c+s:c*s}return c}if("pmod"===r){const[e,n]=s,r=Fr(n,t);if("op"===e.type&&["≡","="].includes(e.op)){const[n,s]=e.args.map(e=>Fr(e,t));return(n-s)%r===0}return Or(Fr(e,t),r)}if("pmatrix"===r||"bmatrix"===r)return Ar(e,t);if("vmatrix"===r)return br.det(Ar(e,t));if("^"===r&&"symbol"===s[1].type&&"T"===s[1].value&&!Object.prototype.hasOwnProperty.call(t,"T")){const e=Fr(s[0],t);if(yr(e))return br.transpose(e)}const i=s.map(e=>Fr(e,t));if(r.startsWith("\\:")&&Object.prototype.hasOwnProperty.call(Mr,r.slice(2)))return Mr[r.slice(2)](i);if(Ir[r]&&1===i.length)return Ir[r](i[0]);if(zr[r]&&2===i.length)return zr[r](i[0],i[1]);if(_r[r])return _r[r](i);throw new Error(`Can't evaluate '${r}'`)}const Zr={"ℝ":Number.isFinite,"ℤ":Number.isInteger,"ℕ":e=>Number.isInteger(e)&&e>0,"ℚ":Number.isFinite,"ℂ":e=>"number"==typeof e&&!Number.isNaN(e)};for(const e of[Sr,Ir,zr,_r,Zr,Mr])Object.setPrototypeOf(e,null);class Cr extends Error{}class Rr extends Error{}class Br extends Rr{}const Pr={bits:2e5,factorial:2e4,terms:1e5,rootIndex:12,steps:5e6,places:1e4};let Dr=0;function Wr(e){if(Dr+=e,Dr>Pr.steps)throw new Rr("too much to work out")}const Ur=(e,t)=>Wr(Number(e)*(t/64)/128);let Vr=0;const Hr=e=>e<0n?-e:e,Gr=0xFFFFFFFFFFFFn,Qr=e=>0n===e?0:Hr(e).toString(2).length;function Xr(e,t){for(e=Hr(e),t=Hr(t);t;)[e,t]=[t,e%t];return e}function Jr(e,t=1n){if(0n===t)throw new Cr("division by zero");if(t<0n&&(e=-e,t=-t),t>Gr&&(e>Gr||-e>Gr)){const n=Math.min(e.toString(16).length-(e<0n?1:0),t.toString(16).length)/16;if(Dr+=1+n*n/2,Dr>Pr.steps)throw new Rr("too much to work out")}const n=Xr(e,t)||1n;return{n:e/n,d:t/n}}const Yr=Jr(0n),Kr=Jr(1n),es=(e,t)=>Jr(e.n*t.d+t.n*e.d,e.d*t.d),ts=(e,t)=>Jr(e.n*t.n,e.d*t.d),ns=(e,t)=>Jr(e.n*t.d,e.d*t.n),rs=e=>({n:-e.n,d:e.d}),ss=(e,t)=>{const n=e.n*t.d-t.n*e.d;return n<0n?-1:n>0n?1:0},is=e=>{const t=e.n/e.d;return e.n<0n&&t*e.d!==e.n?t-1n:t};function os(e){if(e.n<0n)return-os(rs(e));const t=Qr(e.n),n=Qr(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 as(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 Rr(`'${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=es(Jr(BigInt(o||"0")),Jr(s-r,(10n**BigInt(e)-1n)*10n**BigInt(n.length)))}else l=Jr(BigInt(o+a||"0"),10n**BigInt(a.length));if(Math.abs(s)>Pr.bits/3)throw new Rr("too large to calculate");return s&&(l=s>0?ts(l,Jr(10n**BigInt(s))):ns(l,Jr(10n**BigInt(-s)))),n<0n?rs(l):l}function ls(e,t=0,n=0,r=null){return 0n===e.n?{kind:"x",c:Yr,pi:0,e:0,root:null}:{kind:"x",c:e,pi:t,e:n,root:r}}const us=(e,t=1n)=>ls(Jr(BigInt(e),BigInt(t))),cs=ls(Kr,1),hs=ls(Kr,0,1),fs=e=>null!==e&&"object"==typeof e&&"x"===e.kind,ps=e=>fs(e)&&!e.pi&&!e.e&&!e.root,ms=e=>fs(e)?0n===e.c.n:0===e,ds=e=>ps(e)&&1n===e.c.d?e.c.n:null,gs=(e,t)=>Object.assign(e,{group:t}),vs=e=>({kind:"s",text:e});function bs(e,t){return e&&t?e.n===t.n&&e.r===t.r:e===t}const ys=(e,t)=>0===ss(e.c,t.c)&&e.pi===t.pi&&e.e===t.e&&bs(e.root,t.root);function ws(e){const t=Math.max(0,Qr(e)-60);return t+Math.log2(Number(e>>BigInt(t)))}function xs(e){if("number"==typeof e)return e;if(Hs(e)&&ei(e),fs(e)){let t=os(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**(ws(e)/t)}(e.root.r,e.root.n);if(!(0n===e.c.n||0!==t&&Number.isFinite(t)&&Number.isFinite(n))){const t=ws(e.c.n<0n?-e.c.n:e.c.n)-ws(e.c.d)+ws(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 Rr("not a number")}function $s(e,...t){if(Number.isNaN(e))throw new Cr("undefined");if(!Number.isFinite(e)&&t.every(Number.isFinite))throw new Rr("too large to calculate");return e}const ks=e=>"boolean"==typeof e?e:fs(e)?0n!==e.c.n:"number"==typeof e?0!==e:Boolean(e);function qs(e){if("bigint"==typeof e)return ls(Jr(e));if("number"==typeof e)return Number.isFinite(e)?ls(Number.isInteger(e)&&Math.abs(e)<=Number.MAX_SAFE_INTEGER?Jr(BigInt(e)):as(String(e))):e;if("boolean"==typeof e)return e;if("string"==typeof e)return/^-?(\d+\.?\d*|\.\d+)(\.\.)?$/.test(e.trim())?ls(as(e)):Xi(dr(e),{});if(Array.isArray(e))return!e.group&&fe(e)?gs(e.map(e=>gs(e.map(qs),"[]")),"[]"):gs(e.map(qs),e.group||"()");if(fs(e)||"function"==typeof e)return e;throw new Rr(`can't use ${typeof e} as a value`)}function Ms(e){if(Array.isArray(e))return e.map(Ms);if(Gs(e)){const{re:t,im:n}=ti(e);return{re:xs(t),im:xs(n)}}return Hs(e)?fo(e,{decimal:!1,places:null,digits:12,maxDigits:50}):e&&"s"===e.kind?e.text:"boolean"==typeof e?e:xs(e)}function As(e,t){if(e<2n)return e;const n=BigInt(t);let r=1n<<BigInt(Math.ceil(Qr(e)/t));for(;;){const t=((n-1n)*r+e/r**(n-1n))/n;if(t>=r)return r;r=t}}function Ss(e,t,n,r=0,s=0){if(0n===n)return ls(Yr);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++}Dr+=o/4;const a=As(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=As(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?ls(ts(e,Jr(i*o.r)),r,s):ls(ts(e,Jr(i)),r,s,o)}function Ns(e,t){const n=ts(e.c,t.c);if(Qr(n.n)+Qr(n.d)>Pr.bits)return null;const r=e.pi+t.pi,s=e.e+t.e;if(!e.root||!t.root)return ls(n,r,s,e.root||t.root);const i=zi(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 Qr(o)>4e3?null:Ss(n,i,o,r,s)}function Os(e){if(0n===e.c.n)throw new Cr("division by zero");const t=ls(ns(Kr,e.c),-e.pi,-e.e);if(!e.root)return t;const{n:n,r:r}=e.root;return Qr(r)*(n-1)>4e3?null:Ns(t,Ss(Jr(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 ls(Kr)}if(t<0n){const n=Os(e);return n&&Es(n,-t)}if((Qr(e.c.n)+Qr(e.c.d)+(e.root?Qr(e.root.r):0))*Number(t)>Pr.bits||t>100000n)return null;const n=Jr(e.c.n**t,e.c.d**t),r=Number(t);if(!e.root)return ls(n,e.pi*r,e.e*r);const{n:s,r:i}=e.root,o=i**(t/BigInt(s));return Ss(ts(n,Jr(o)),s,i**(t%BigInt(s))||1n,e.pi*r,e.e*r)}function Is(e,t,n){if(!ps(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 Qr(n)>4e3?null:Ss(Jr(1n,e.d),t,n)}({n:s,d:i},Number(n));return a?o?ls(rs(a.c),a.pi,a.e,a.root):a:null}function zs(e){return t=>Array.isArray(t)?gs(t.map(t=>zs(e)(t)),t.group):e(t)}function _s(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 gs(n.map((e,n)=>t(e,r[n])),n.group)}return s?gs(n.map(e=>t(e,r)),n.group):i?gs(r.map(e=>t(n,e)),r.group):e(n,r)};return t}const js=(e,t)=>fs(e)&&fs(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||!bs(e.root,t.root))return null;const n=es(e.c,t.c);return Qr(n.n)+Qr(n.d)>Pr.bits?null:ls(n,e.pi,e.e,e.root)}(e,t)||$s(xs(e)+xs(t),xs(e),xs(t)),Ts=e=>fs(e)?ls(rs(e.c),e.pi,e.e,e.root):-xs(e),Ls=(e,t)=>fs(e)&&fs(t)&&Ns(e,t)||$s(xs(e)*xs(t),xs(e),xs(t)),Fs=_s((e,t)=>Hs(e)||Hs(t)?ci(e,t):js(e,t)),Zs=zs(e=>Hs(e)?hi(e):Ts(e)),Cs=(e,t)=>Fs(e,Zs(t)),Rs=_s((e,t)=>Hs(e)||Hs(t)?pi(e,t):Ls(e,t)),Bs=_s((e,t)=>Hs(e)||Hs(t)?function(e,t){if(!Hs(t)){if(ms(t))throw new Cr("division by zero");return Js(Ys(e).map(e=>({vars:e.vars,re:Ps(e.re,t),im:Ps(e.im,t)})))}if(Gs(t))return pi(e,ni(si(ti(t))));const n=function(e,t){const n=new Set(t.flatMap(e=>e.vars.map(([e])=>e)));if(1!==n.size)return null;const[r]=n,s=e=>e.vars.find(([e])=>e===r)?.[1]??0,i=t.reduce((e,t)=>s(t)>s(e)?t:e),o=s(i);if(1!==i.vars.length)return null;let a=e;const l=[];for(let e=0;e<1e3&&a.length;e++){const e=a.reduce((e,t)=>s(t)>s(e)?t:e);if(s(e)<o)return null;const n={vars:fi(e.vars,[[r,-o]]),...ri(e,si(i))};l.push(n);const u=ci(Js(a),hi(pi(Js([n]),Js(t))));a=ms(u)?[]:Ys(u)}return a.length?null:Js(l)}(Ys(e),[...t.terms.values()]);if(null===n)throw new Rr(`no value for '${Ks(t)}'`);return n}(e,t):Ps(e,t));function Ps(e,t){if(ms(t))throw new Cr("division by zero");if(fs(e)&&fs(t)){const n=Os(t),r=n&&Ns(e,n);if(r)return r}return $s(xs(e)/xs(t),xs(e),xs(t))}const Ds=_s((e,t)=>{if(Hs(e)||Hs(t))return function(e,t){if(Hs(t)){Gs(t)||ei(t),Hs(e)&&!Gs(e)&&ei(e);const n=ti(t);return fs(e)&&ys(e,hs)?ai(n):ai(ri(n,li(ti(e))))}const n=ds(t);if(null!==n)return n>=0n?mi(e,n):(Gs(e)||ei(e),mi(ni(si(ti(e))),-n));Gs(e)||ei(e);return ui(ti(e),t)}(e,t);try{return Ws(e,t)}catch(n){if(Us&&n instanceof Cr&&"not a real number"===n.message)return ui({re:e,im:us(0)},t);throw n}});function Ws(e,t){if(fs(e)&&ps(t)){const{n:n,d:r}=t.c,s=1n===r?Es(e,n):Is(e,n,r);if(s)return s}const n=xs(e),r=xs(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 Br("too small to calculate");return $s(s,n,r)}let Us=!1;const Vs=5e3,Hs=e=>null!==e&&"object"==typeof e&&"p"===e.kind,Gs=e=>Hs(e)&&1===e.terms.size&&e.terms.has(""),Qs=()=>Js([{vars:[],re:us(0),im:us(1)}]),Xs=e=>e.map(([e,t])=>1===t?e:`${e}^${t}`).join("*");function Js(e){const t=new Map;for(const n of e){const e=Xs(n.vars),r=t.get(e);t.set(e,r?{vars:n.vars,re:js(r.re,n.re),im:js(r.im,n.im)}:n)}for(const[e,n]of t)ms(n.re)&&ms(n.im)&&t.delete(e);if(t.size>Vs)throw new Rr("too many terms to work out");return t.size?1===t.size&&t.has("")&&ms(t.get("").im)?t.get("").re:{kind:"p",terms:t}:us(0)}function Ys(e){if(Hs(e))return[...e.terms.values()];if("boolean"==typeof e)return[{vars:[],re:us(e?1:0),im:us(0)}];if(!fs(e)&&"number"!=typeof e)throw new Rr("not a number");return[{vars:[],re:e,im:us(0)}]}const Ks=e=>[...e.terms.values()].find(e=>e.vars.length)?.vars[0][0];function ei(e){if(Gs(e))throw new Rr("a complex number has no real value here");throw new Rr(`no value for '${Ks(e)}'`)}const ti=e=>Gs(e)?e.terms.get(""):{re:e,im:us(0)},ni=({re:e,im:t})=>Js([{vars:[],re:e,im:t}]),ri=(e,t)=>({re:js(Ls(e.re,t.re),Ts(Ls(e.im,t.im))),im:js(Ls(e.re,t.im),Ls(e.im,t.re))});function si(e){const t=js(Ls(e.re,e.re),Ls(e.im,e.im));if(ms(t))throw new Cr("division by zero");return{re:Ps(e.re,t),im:Ts(Ps(e.im,t))}}const ii=e=>ms(e.im)?di(e.re,us(0))<0?Ts(e.re):e.re:Ws(js(Ls(e.re,e.re),Ls(e.im,e.im)),us(1,2));function oi(e){return ms(e.im)?di(e.re,us(0))<0?cs:us(0):ms(e.re)?di(e.im,us(0))>0?ls(Jr(1n,2n),1):ls(Jr(-1n,2n),1):Math.atan2(xs(e.im),xs(e.re))}function ai(e){const t=ms(e.re)?us(1):Ws(hs,e.re);return ni({re:Ls(t,xi("cos",e.im)),im:Ls(t,xi("sin",e.im))})}function li(e){if(ms(e.re)&&ms(e.im))throw new Cr("ln 0 is undefined");return{re:ki(ii(e)),im:oi(e)}}function ui(e,t){if(ms(e.re)&&ms(e.im))return Ws(us(0),t);const n=Ws(ii(e),t),r=Ls(t,oi(e));return ni({re:Ls(n,xi("cos",r)),im:Ls(n,xi("sin",r))})}function ci(e,t){return Js([...Ys(e),...Ys(t)])}function hi(e){return Js(Ys(e).map(e=>({vars:e.vars,re:Ts(e.re),im:Ts(e.im)})))}function fi(e,t){const n=new Map(e);for(const[e,r]of t)n.set(e,(n.get(e)??0)+r);return[...n].filter(([,e])=>0!==e).sort(([e],[t])=>e<t?-1:e>t?1:0)}function pi(e,t){const n=Ys(e),r=Ys(t);Wr(n.length*r.length);const s=[];for(const e of n)for(const t of r)s.push({vars:fi(e.vars,t.vars),...ri(e,t)});return Js(s)}function mi(e,t){if(!Gs(e)&&t>1000n)throw new Rr("too large to calculate");if(Hs(e)&&!Gs(e)&&function(e,t){const n=e.terms.size;let r=1;for(let e=1;e<=Math.min(t,n-1)&&r<=Vs;e++)r=r*(t+e)/e;const s=new Map;for(const t of e.terms.values())for(const[e]of t.vars)s.set(e,[0,0]);for(const t of e.terms.values())for(const[e,n]of s){const r=t.vars.find(([t])=>t===e)?.[1]??0;n[0]=Math.min(n[0],r),n[1]=Math.max(n[1],r)}let i=1;for(const[e,n]of s.values())if((i*=t*(n-e)+1)>Vs)break;return Math.min(r,i)}(e,Number(t))>Vs)throw new Rr("too many terms to work out");if(Gs(e)&&t>1n){const{re:n,im:r}=ti(e),s=e=>fs(e)?Qr(e.c.n)+Qr(e.c.d)+(e.root?Qr(e.root.r):0):64;if(Number(t)*Math.max(s(n),s(r),1)>2e4)return ui(ti(e),us(t))}let n=us(1),r=e;for(let e=t;e>0n;e>>=1n)1n&e&&(n=pi(n,r)),e>1n&&(r=pi(r,r));return n}function di(e,t){if(Gs(e)||Gs(t))throw new Rr("complex numbers have no order");if(ps(e)&&ps(t))return ss(e.c,t.c);if(fs(e)&&fs(t)&&ys(e,t))return 0;const n=xs(e),r=xs(t);if(n===r)return 0;const s=fs(e)&&fs(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 gi(e,t,n=!1){return Array.isArray(e)||Array.isArray(t)?Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,r)=>gi(e,t[r],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:"boolean"==typeof e||"boolean"==typeof t?!!n&&gi("boolean"==typeof e?us(e?1:0):e,"boolean"==typeof t?us(t?1:0):t):Hs(e)||Hs(t)?function(e,t){const n=Cs(e,t);return Hs(n)?!Gs(n)&&ei(n):ms(n)}(e,t):0===di(e,t)}const vi={0:()=>us(0),2:()=>us(1,2),3:()=>Ss(Jr(1n,2n),2,2n),4:()=>Ss(Jr(1n,2n),2,3n),6:()=>us(1)};function bi(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=vi[t];return r?n<0?Zs(r()):r():null}const yi=e=>bi(e+6),wi=(e,t)=>Math.abs(e)<1e-15&&Math.abs(t)>1e-6?0:e;function xi(e,t){const n=function(e){if(ms(e))return 0;if(!fs(e)||1!==e.pi||e.e||e.root)return null;const t=ts(e.c,Jr(12n));return 1n!==t.d?null:Number((t.n%24n+24n)%24n)}(t);if(null!==n){const t=bi(n),r=yi(n);if(t&&r)switch(e){case"sin":return t;case"cos":return r;case"tan":return Bs(t,r);case"cot":return Bs(r,t);case"sec":return Bs(us(1),r);case"csc":return Bs(us(1),t)}}const r=xs(t),s=wi(Math.sin(r),r),i=wi(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 $s(o)}function $i(e,t){const n={arcsin:[-6,6],arccos:[0,12],arctan:[-5,5]}[e],r=t=>"arcsin"===e?bi(t):"arccos"===e?yi(t):yi(t)&&!ms(yi(t))?Bs(bi(t),yi(t)):null;if(fs(t))for(let e=n[0];e<=n[1];e++){const n=r(e);if(n&&fs(n)&&ys(n,t))return ls(Jr(BigInt(e),12n),1)}const s=xs(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 ki(e){if(Hs(e))return Gs(e)?ni(li(ti(e))):ei(e);if(Us&&di(e,us(0))<0)return ni({re:ki(Ts(e)),im:cs});if(fs(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 us(e.e)}const t=xs(e);if(t<=0)throw new Cr(0===t?"ln 0 is undefined":"not a real number");return Math.log(t)}function qi(e){if(e<.5)return Math.PI/(Math.sin(Math.PI*e)*qi(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 Mi(e,t){Hs(e)&&ei(e);const n=ds(e)??("number"==typeof e&&Number.isInteger(e)?BigInt(e):null);if(null===n)throw new Cr(`${t} needs whole numbers`);return n}const Ai=(e,t)=>Number(t)*Qr(e)>Pr.bits;const Si=zs(e=>ps(e)?ls(Jr(is(e.c))):qs(Math.floor(xs(e)))),Ni=zs(e=>ps(e)?ls(Jr(-is(rs(e.c)))):qs(Math.ceil(xs(e))));function Oi(e,t){const n=Number(Mi(t,"round"));if(Math.abs(n)>Pr.places)throw new Rr("too many decimal places");if(ps(e)){const t=Jr(10n**BigInt(Math.abs(n))),r=n>=0?ts(e.c,t):ns(e.c,t),s=is(es(ts(Jr(2n),Jr(Hr(r.n),r.d)),Kr))/2n,i=Jr(r.n<0n?-s:s);return ls(n>=0?ns(i,t):ts(i,t))}if(n>15)return xs(e);const r=10**n;return 0===r?0:Math.sign(xs(e))*Math.round(Math.abs(xs(e))*r)/r}const Ei=(e,t)=>e.toFixed(Math.min(t,100))+(t>100?"0".repeat(t-100):"");function Ii(e,t){if(ms(t))throw new Cr("division by zero");if(ps(e)&&ps(t))return ls(es(e.c,rs(ts(t.c,Jr(is(ns(e.c,t.c)))))));const n=xs(e),r=xs(t);return $s((n%r+r)%r)}const zi=(e,t)=>e/_i(e,t)*t,_i=(e,t)=>t?_i(t,e%t):e,ji={pi:()=>cs,"π":()=>cs,tau:()=>ls(Jr(2n),1),"τ":()=>ls(Jr(2n),1),e:()=>hs,"∞":()=>1/0,"-∞":()=>-1/0,true:()=>!0,false:()=>!1,"°":()=>ls(Jr(1n,180n),1)},Ti={abs:e=>Gs(e)?ii(ti(e)):fs(e)?ls(Jr(Hr(e.c.n),e.c.d),e.pi,e.e,e.root):Math.abs(xs(e)),floor:Si,ceil:Ni,sqrt:e=>Ds(e,us(1,2)),ln:zs(ki),loglog:zs(e=>ki(ki(e))),logloglog:zs(e=>ki(ki(ki(e)))),expm1:zs(e=>ms(e)?us(0):Math.expm1(xs(e))),sinh:zs(e=>ms(e)?us(0):Math.sinh(xs(e))),cosh:zs(e=>ms(e)?us(1):Math.cosh(xs(e))),tanh:zs(e=>ms(e)?us(0):Math.tanh(xs(e))),arcsinh:zs(e=>ms(e)?us(0):Math.asinh(xs(e))),arccosh:zs(e=>{const t=xs(e);if(t<1)throw new Cr("not a real number");return 1===t?us(0):Math.acosh(t)}),arctanh:zs(e=>{const t=xs(e);if(Math.abs(t)>=1)throw new Cr("undefined");return ms(e)?us(0):Math.atanh(t)}),"!":zs(function(e){const t=ds(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 Rr("too large to calculate");Ur(t,Number(t)*Math.log2(Number(t)+1));let e=1n;for(let n=2n;n<=t;n++)e*=n;return ls(Jr(e))}const n=xs(e);if(n<0&&Number.isInteger(n))throw new Cr("factorial of a negative number");return $s(qi(n+1),n)}),neg:Zs,pm:e=>gs([e,Zs(e)],"pm"),"\\not":e=>!ks(e),det:e=>Wi.det(e)};for(const e of["sin","cos","tan","csc","sec","cot"])Ti[e]=zs(t=>xi(e,t));for(const e of["arcsin","arccos","arctan"])Ti[e]=zs(t=>$i(e,t));const Li=e=>{if(ms(e))throw new Cr("not a real number");return Bs(us(1),e)};Ti.arcsec=zs(e=>$i("arccos",Li(e))),Ti.arccsc=zs(e=>$i("arcsin",Li(e))),Ti.arccot=zs(e=>Cs(ls(Jr(1n,2n),1),$i("arctan",e)));const Fi=new Set(["pmatrix","bmatrix"]),Zi=e=>fe(e)&&(Fi.has(e.group)||"[]"===e.group&&e.every(e=>"[]"===e.group)&&(e.length>1||e[0].length>1)),Ci=e=>pe(e)&&!Zi(e)&&"pm"!==e.group,Ri=me({add:Fs,sub:Cs,mul:Rs,div:Bs,charge:Wr,isZero:e=>fs(e)?0n===e.c.n:Math.abs(xs(e))<1e-12,zero:()=>us(0),one:()=>us(1),size:e=>Math.abs(xs(e)),fail:e=>{throw new Cr(e)},make:(e,t)=>gs(e.map(e=>gs(e,"[]")),t&&t.group?t.group:"bmatrix")}),Bi=(e,t)=>gs(e,t&&t.group?t.group:"[]"),Pi=(e,t)=>(...n)=>{const r=n.length>1&&n.every(Ci)?gs(n.map(e=>gs(e,"[]")),"[]"):n[0];if(n.length>1&&r===n[0])throw new Rr(`${e} of more than one thing`);if(!Zi(r))throw new Rr(`${e} of something that isn't a matrix`);return t(r)};function Di(e,t){return Zi(e)&&Zi(t)?Ri.times(e,t):Zi(e)&&Ci(t)?Bi(Ri.timesVector(e,t),t):Ci(e)&&Zi(t)?Bi(Ri.vectorTimes(e,t),e):Rs(e,t)}const Wi={det:Pi("det",e=>Ui(e)),inv:Pi("inv",Ri.inverse),inverse:Pi("inverse",Ri.inverse),transpose:Pi("transpose",Ri.transpose),trace:Pi("trace",Ri.trace),tr:Pi("tr",Ri.trace),rank:Pi("rank",e=>us(Ri.rank(e))),rref:Pi("rref",Ri.rref),identity:e=>{const t=ds(e);if(null===t||t<1n||t>100n)throw new Rr("identity(n) needs a whole number n");return Ri.identity(Number(t))},dot:(e,t)=>{if(!Ci(e)||!Ci(t))throw new Rr("dot of something that isn't a vector");return Ri.dot(e,t)},cross:(e,t)=>{if(!Ci(e)||!Ci(t))throw new Rr("cross of something that isn't a vector");return Bi(Ri.cross(e,t),e)},linsolve:(e,t)=>{if(!Zi(e)||!Zi(t)&&!Ci(t))throw new Rr("linsolve(A, b) needs a matrix and a vector");return Zi(t)?Ri.solve(e,t):Bi(Ri.solve(e,t),t)}};function Ui(e){if(!e.some(e=>e.some(Hs)))return Ri.det(e);if(e.length!==e[0].length)throw new Cr(`a ${e.length} by ${e[0].length} matrix has no determinant`);if(e.length>6)throw new Rr("too large to calculate");const t=e=>1===e.length?e[0][0]:e[0].reduce((n,r,s)=>{const i=e.slice(1).map(e=>e.filter((e,t)=>t!==s)),o=Rs(r,t(i));return s%2?Cs(n,o):Fs(n,o)},us(0));return t(e)}function Vi(e,t){const n=e.args.map(e=>gs("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 gs(n,"vmatrix"===e.op?"bmatrix":e.op)}const Hi={"+":Fs,"-":Cs,"*":Di,"/":(e,t)=>Zi(t)?Di(e,Ri.inverse(t)):Bs(e,t),"^":function(e,t){if(!Zi(e))return Ds(e,t);const n=ds(t);if(null===n)throw new Rr("a matrix to a power that is not a whole number");return Ri.power(e,n)},"±":(e,t)=>gs([Fs(e,t),Cs(e,t)],"pm"),mod:_s(Ii),log:_s(function(e,t){if(fs(e)&&ys(e,hs))return ki(t);const n=xs(e),r=xs(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(ps(e)&&ps(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&&ys(i,o))return ls(Jr(BigInt(r),n))}return s}),root:_s((e,t)=>Ds(t,Bs(us(1),e))),atan2:(e,t)=>Math.atan2(xs(e),xs(t)),round:Oi,fixed:function(e,t){const n=Number(Mi(t,"fixed"));if(n<0)throw new Cr("fixed needs 0 or more decimal places");const r=Oi(e,t);if(ps(r)){const e=r.c.n*10n**BigInt(n)/r.c.d,t=(e<0n?-e:e).toString().padStart(n+1,"0");return vs(`${e<0n?"-":""}${t.slice(0,t.length-n)}${n?"."+t.slice(-n):""}`)}return vs(Ei(xs(r),n))},perm:function(e,t){const n=Mi(e,"permutations"),r=Mi(t,"permutations");if(r<0n||r>n)throw new Cr("undefined");if(r>BigInt(Pr.terms)||Ai(n,r))throw new Rr("too large to calculate");Ur(r,Number(r)*Qr(n));let s=1n;for(let e=n-r+1n;e<=n;e++)s*=e;return ls(Jr(s))},comb:function(e,t){const n=Mi(e,"combinations");let r=Mi(t,"combinations");if(r<0n||r>n)throw new Cr("undefined");if(n-r<r&&(r=n-r),r>BigInt(Pr.terms)||Ai(n,r))throw new Rr("too large to calculate");Ur(2n*r,Number(r)*Qr(n));let s=1n;for(let e=1n;e<=r;e++)s=s*(n-r+e)/e;return ls(Jr(s))},"=":(e,t)=>gi(e,t,!0),"===":(e,t)=>gi(e,t),"≠":(e,t)=>!gi(e,t,!0),"≠=":(e,t)=>!gi(e,t),"≈":(e,t)=>Math.abs(xs(e)-xs(t))<=1e-9*Math.max(1,Math.abs(xs(e)),Math.abs(xs(t))),"<":(e,t)=>di(e,t)<0,">":(e,t)=>di(e,t)>0,"≤":(e,t)=>di(e,t)<=0,"≥":(e,t)=>di(e,t)>=0,"&":(e,t)=>ks(e)&&ks(t),"|":(e,t)=>ks(e)||ks(t),"\\xor":(e,t)=>ks(e)!==ks(t),"\\nor":(e,t)=>!(ks(e)||ks(t)),"\\nand":(e,t)=>!(ks(e)&&ks(t)),"\\implies":(e,t)=>!ks(e)||ks(t),"\\iff":(e,t)=>ks(e)===ks(t)},Gi={sum:e=>e.reduce((e,t)=>Fs(e,t),us(0)),prod:e=>e.reduce((e,t)=>Rs(e,t),us(1)),max:e=>e.reduce((e,t)=>di(t,e)>0?t:e),min:e=>e.reduce((e,t)=>di(t,e)<0?t:e),mean:e=>Bs(Gi.sum(e),us(e.length)),gcd:e=>ls(Jr(e.map(e=>Mi(e,"gcd")).reduce(Xr)))},Qi=["∈","∉","∪","∩","pmod","random","(]","[)"];function Xi(e,t){if(++Dr>Pr.steps)throw new Rr("too much to work out");switch(e.type){case"number":return ls(as(e.value));case"string":return vs(e.value.slice(1,-1));case"symbol":return Ji(e.value,t)}const n=ue(e);if(n)return Xi(n,t);const{op:r,args:s}=e,i=e=>Xi(e,t);if("?:"===r)return ks(i(s[0]))?i(s[1]):i(s[2]);if("_"===r){if(s.every(e=>"op"!==e.type))return Ji(`${s[0].value}_${s[1].value}`,t);throw new Rr("subscript")}if("der"===r)return function(e,t){const[n,r]=e.args;if("op"===r.type&&"="===r.op){const e=no(r.args[0]);if(!e)throw new Rr("a derivative at a point names its variable: der(f, x = a)");return ro(n,e,xs(Xi(r.args[1],t)),t)}const s=no(r);if(!s||!t[Ki]?.has(s))throw new Rr(`a derivative needs a point: der(f, ${s||"x"} = a)`);return ro(n,s,xs(t[s]),t)}(e,t);if("evaluated"===r){const[e,n,r,o]=s;return Cs(Xi(e,eo(t,n.value,i(o))),Xi(e,eo(t,n.value,i(r))))}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]=[no(r),s,i];else{if(3!==e.length||o(r))throw new Rr("an integral needs limits to be calculated");[a,l,u]=[j(n)||"x",r,s]}let c=xs(Xi(l,t)),h=xs(Xi(u,t));if(c===h)return us(0);let f=1;c>h&&([c,h]=[h,c],f=-1);const p=to(n,a,t),{value:m,error:d}=so(p,c,h);return uo(f*m,d)}(s,t);if("lim"===r)return function(e,t){const[n,r,s,i]=e;let o,a,l=0;if(2===e.length&&"op"===r.type&&"→"===r.op)[o,a]=[no(r.args[0]),r.args[1]];else if(2===e.length)[o,a]=[j(n),r];else{if(!(e.length>=3))throw new Rr("a limit needs a point");[o,a]=[no(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 Rr("a limit needs a variable");const u=Xi(a,t),c=xs(u),h=to(n,o,t);let f,p;if(Number.isFinite(c))if(l){({value:f,error:p}=oo(e=>h(c+l*e*Math.max(1,Math.abs(c)))));try{const e=Xi(n,eo(t,o,u));if(Math.abs(xs(e)-f)<=Math.max(p,1e-6*Math.max(1,Math.abs(f))))return e}catch(e){if(!(e instanceof Cr))throw e}}else{const e=oo(e=>h(c+e*Math.max(1,Math.abs(c)))),r=oo(e=>h(c-e*Math.max(1,Math.abs(c))));if(e.value===r.value)({value:f,error:p}=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");f=(e.value+r.value)/2,p=Math.max(e.error,r.error,Math.abs(e.value-r.value))}try{const e=Xi(n,eo(t,o,u));if(Math.abs(xs(e)-f)<=1e-6*Math.max(1,Math.abs(f)))return e}catch(e){if(!(e instanceof Cr))throw e}}else({value:f,error:p}=oo(e=>h(Math.sign(c)/e)));return Number.isFinite(f)?uo(f,p):f}(s,t);if("\\sumidx"===r||"\\prodidx"===r)return function(e,t,n){const[r,s,i]=t;if(t.length<3)throw new Rr("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=j(r)||"n";const l=Mi(Xi(a,n),"a sum"),u=Xi(i,n),c=e?Fs:Rs;if(u===1/0){if(!e)throw new Rr("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]&&!lo(e,t,i))return uo(s,0)}if(lo(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 Rr("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),f=r.slice(-8,-1),p=(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]},m=p(c,h),d=p(n.slice(-8,-1).map(e=>1/e),f);return uo(m,Math.abs(m-d))}(to(r,o,n),Number(l))}const h=Mi(u,"a sum");if(h-l+1n>BigInt(Pr.terms))throw new Rr("too many terms to add one by one");let f=us(e?0:1);for(let e=l;e<=h;e++)f=c(f,Xi(r,eo(n,o,ls(Jr(e)))));return f}("\\sumidx"===r,s,t);if(["()","[]","{}"].includes(r))return gs(s.map(i),r);if("pmatrix"===r||"bmatrix"===r)return Vi(e,i);if("vmatrix"===r)return Ui(Vi(e,i));if("^"===r&&"symbol"===s[1].type&&"T"===s[1].value&&!Object.prototype.hasOwnProperty.call(t,"T")){const e=i(s[0]);if(Zi(e))return Ri.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?ms(Ii(Cs(n(e.args[0]),n(e.args[1])),r)):Ii(n(e),r)}(s,i);if("setbuilder"===r)throw new Rr("a set described by a condition has no list of values");if(C(e))return i(C(e));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)&&fs(s))i="ℝ"===r.value||("ℚ"===r.value?ps(s):ps(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=di(s,e),a=di(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=>gi(s,t(e)))}return"∈"===e.op?i:!i}(e,i);if(void 0!==t)return t}if(Qi.includes(r))return Yi(e,t);if(r.startsWith("\\:")){const n=r.slice(2),o=Object.prototype.hasOwnProperty.call(t,n)?t[n]:void 0;if("function"!=typeof o&&Object.prototype.hasOwnProperty.call(Wi,n))return Wi[n](...s.map(i));if("function"!=typeof o&&ne(r))return Yi(e,t);if("function"!=typeof o)throw new Rr(`no function ${r.slice(2)}`);return qs(o(...s.map(e=>Ms(i(e)))))}if(Ti[r]&&1===s.length)return Ti[r](i(s[0]));if(Hi[r]&&2===s.length)return Hi[r](i(s[0]),i(s[1]));if(Gi[r])return Gi[r](s.map(i));throw new Rr(`can't calculate '${r}'`)}function Ji(e,t){if(Object.prototype.hasOwnProperty.call(t,e))return t[e];if(Object.prototype.hasOwnProperty.call(ji,e))return ji[e]();if(R(e))return ls(as(R(e)));if("i"===e)return Qs();if(/^[A-Za-z\u0370-\u03FF][A-Za-z0-9_\u0370-\u03FF′]*$/.test(e))return Js([{vars:[[e,1]],re:us(1),im:us(0)}]);throw new Rr(`no value for '${e}'`)}function Yi(e,t){const n={};for(const[e,r]of Object.entries(t))"function"!=typeof r&&(n[e]=Ms(r));try{return qs(function(e,t={}){0===Lr&&(Tr=0),Lr++;try{return Fr(gr(e),t)}finally{Lr--}}(e,n))}catch(e){throw new Rr(e.message)}}const Ki=Symbol("bound"),eo=(e,t,n)=>({...e,[t]:n,[Ki]:new Set([...e[Ki]??[],t])});function to(e,t,n){return r=>{try{return xs(Xi(e,eo(n,t,r)))}catch(e){if(e instanceof Cr)return NaN;if(e instanceof Br)return 0;throw e}}}const no=e=>"symbol"===e.type?e.value:null;function ro(e,t,n,r){const s=to(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],f=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<=f&&(f=r,h=c[e][n])}if(Math.abs(c[e][e]-c[e-1][e-1])>=2*f)break}if(!Number.isFinite(h))throw new Cr("not differentiable here");return uo(h,f)}function so(e,t,n){if(t===-1/0&&n===1/0){const t=so(e,-1/0,0),n=so(e,0,1/0);return{value:t.value+n.value,error:t.error+n.error}}return n===1/0?io(n=>e(t+n/(1-n))/((1-n)*(1-n)),0,1):t===-1/0?io(t=>e(n-t/(1-t))/((1-t)*(1-t)),0,1):io(e,t,n)}function io(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 f=e(0===i?(t+n)/2:h);if(!Number.isFinite(f)){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*f))),c*f};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=io(e,t,s,r+1),o=io(e,s,n,r+1);return{value:i.value+o.value,error:i.error+o.error}}function oo(e){const t=ao(e),n=ao(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 ao(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 lo(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 uo(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 us(0);if(Math.abs(e)<1e-10)return e;const r=[[us(1),1e3],[cs,100],[ls(Kr,2),100],[hs,100],...[2n,3n,5n,6n,7n].map(e=>[ls(Kr,0,0,{n:2,r:e}),100])];for(const[t,s]of r){const r=e/xs(t),i=co(r,s);if(i&&Math.abs(Number(i.n)/Number(i.d)-r)*xs(t)<=n)return Ns(ls(i),t)}return e}function co(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?Jr(BigInt(r),BigInt(i)):null}function ho(e,t){if("boolean"==typeof e)return String(e);if(Hs(e))return fo(e,t);if(e&&"s"===e.kind)return JSON.stringify(e.text);if(Array.isArray(e)){if("pm"===e.group&&2===e.length&&gi(e[1],Zs(e[0])))return`±${mo(e[0],t)}`;if(Fi.has(e.group)&&fe(e))return`${e.group}(${e.map(e=>`[${e.map(e=>ho(e,t)).join(", ")}]`).join(", ")})`;const[n,r]={"()":"()","[]":"[]","{}":"{}"}[e.group]||"{}";return n+e.map(e=>ho(e,t)).join(", ")+r}return"number"==typeof e?go(e,t):t.decimal||null!==t.places?function(e,t){if(ps(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=Hr(n).toString().padStart(i+1,"0"),o=i?`${s.slice(0,-i)}.${s.slice(-i)}`:s;if(s.length<=t.maxDigits)return(r?"-":"")+vo(o)}}return ps(e)&&null!==t.places?ho(Oi(e,us(t.places)),{...t,places:null,decimal:!0}):go(xs(e),t)}(e,t):function(e,t){const{c:n}=e,r=Hr(n.n);if(r.toString().length>t.maxDigits||n.d.toString().length>t.maxDigits)return function(e,t){if(!ps(e))return go(xs(e),t);if(1n!==e.c.d){const n=xs(e);if(0!==n&&Number.isFinite(n))return go(n,t);const r=Hr(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=vo(`${a[0]}.${a.slice(1,t.digits)}`);return`${e.c.n<0n?"-":""}${u}*10^(${l})`}const n=Hr(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=vo(`${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)}function fo(e,t){const n=e=>e.vars.reduce((e,[,t])=>e+t,0),r=[...new Set([...e.terms.values()].flatMap(e=>e.vars.map(([e])=>e)))].sort(),s=(e,t)=>e.vars.find(([e])=>e===t)?.[1]??0,i=[...e.terms.values()].sort((e,t)=>n(t)-n(e)||r.reduce((n,r)=>n||s(t,r)-s(e,r),0)).map(e=>function(e,t){const n=Xs(e.vars);if(!n)return po(e.re,e.im,t);if(!ms(e.im))return`(${po(e.re,e.im,t)})*${n}`;const r=e.re,s=ho(r,t);if("1"===s)return n;if("-1"===s)return`-${n}`;if(ps(r)&&1n!==r.c.d&&!t.decimal&&null===t.places){const e=Hr(r.c.n);return`${r.c.n<0n?"-":""}${1n===e?n:`${e}*${n}`}/${r.c.d}`}return/^-?[\w.^]+(?:\([\w ,.]*\))?$/.test(s)?`${s}*${n}`:`(${s})*${n}`}(e,t));return i.reduce((e,t,n)=>0===n?t:t.startsWith("-")?`${e} - ${t.slice(1)}`:`${e} + ${t}`,"")}function po(e,t,n){if(ms(t))return ho(e,n);const r=!ms(t)&&di(t,us(0))<0,s=ho(r?Ts(t):t,n),i="1"===s?"i":/^[\d.]+$/.test(s)?`${s}*i`:`(${s})*i`;return ms(e)?r?`-${i}`:i:`${ho(e,n)} ${r?"-":"+"} ${i}`}const mo=(e,t)=>{const n=ho(e,t);return/^[\d.]+$|^[a-zπ]+$/i.test(n)?n:`(${n})`};function go(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 Ei(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`${vo(n)}*10^(${Number(r)})`}return String(Number(e.toPrecision(t.digits)))}const vo=e=>e.includes(".")?e.replace(/\.?0+$/,""):e;function bo(e,t={},n={}){0===Vr&&(Dr=0);const r="string"==typeof e?dr(e):z(e),s={};for(const[e,n]of Object.entries(t))s[e]=qs(n);Vr++;const i=Us;let o,a=!1;_(r,e=>{"symbol"!==e.type||"i"!==e.value||Object.prototype.hasOwnProperty.call(t,"i")||(a=!0)}),Us=n.complex??(a||Vr>1&&i);try{o=Xi(r,s)}finally{Vr--,Us=i}const l={decimal:!1,places:null,digits:12,maxDigits:50,...n};if(void 0===l.places&&(l.places=null),null!==l.places&&!(Number.isInteger(l.places)&&l.places>=0&&l.places<=Pr.places))throw new Rr(`places is a whole number from 0 to ${Pr.places}`);const u=e=>Array.isArray(e)?e.every(u):Hs(e)?[...e.terms.values()].every(e=>"number"!=typeof e.re&&"number"!=typeof e.im):"number"!=typeof e;return{value:Ms(o),text:ho(o,l),exact:u(o)}}function yo(e,t={}){let n=e.trim();const r={},s=/^(~|≈)(\d+)?\s*/.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}=bo(n,t,r);return e.startsWith('"')||/^\d+(\.\d+)?$/.test(e)?e:`(${e})`}catch(e){if(e instanceof Cr)return'"undefined"';if(e instanceof Rr)return`(${n})`;throw e}}hr=yo;for(const e of[Pr,vi,ji,Ti,Hi,Gi])Object.setPrototypeOf(e,null);Object.setPrototypeOf(Wi,null);const wo=e=>"op"===e.type&&o(e.op)&&["vec","hat"].includes(ee(e.op)),xo={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",implies:"implies",iff:"if and only if",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",evaluatedFrom:"evaluated from",setOf:"the set of",suchThat:"such that",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",andSoOn:"dot dot dot",emptySet:"the empty set",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"]},$o={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",arcsec:"inverse secant",arccsc:"inverse cosecant",arccot:"inverse cotangent",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"},ko=Object.fromEntries(Object.entries(T).map(([e,t])=>[t,e]));function qo(e,t={}){return Ao(function(e,t={}){return Mo(e,t,!0)}(e,t))}function Mo(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 Oo({...xo,...t.words},{...$o,...t.names},t.say||{},n).speak(e))}function Ao(e){return e.map(e=>e.text).join(" ").replace(/\s+/g," ").replace(/ ,/g,",").replace(/,(\s*,)+/g,",").replace(/^,\s*/,"").replace(/,\s*$/,"").trim()}const So={"=":"equals","===":"equals","≠":"notEqual","≠=":"notEqual","<":"lessThan",">":"greaterThan","≤":"lessOrEqual","≥":"greaterOrEqual","≈":"approx","≡":"congruent","→":"tendsTo","∈":"isIn","∉":"isNotIn","∪":"union","∩":"intersect","±":"plusOrMinus","&":"and","|":"or","\\xor":"xor","\\nand":"nand","\\nor":"nor","\\implies":"implies","\\iff":"iff"},No={"ℝ":"reals","ℤ":"integers","ℕ":"naturals","ℚ":"rationals","ℂ":"complexes"};class Oo{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=>Ao(this.speak(e))):[e.value],e,e=>Ao(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("⋯"===e)return t.andSoOn;if(No[e])return t[No[e]];if(ko[e])return ko[e].toLowerCase();if(/^Δ.+$/.test(e))return`${t.delta} ${this.symbol(e.slice(1))}`;if(/^d[A-Za-z\u03B1-\u03C9]$/.test(e))return`d ${this.symbol(e[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(So[t])return[...this.speak(r),a(i[So[t]]),...this.speak(s)];if(o(t)){if(1===n.length&&"symbol"===r.type&&"vec"===ee(t))return[a(i.vector),...this.speak(r)];if(1===n.length&&"symbol"===r.type&&"hat"===ee(t))return[...this.speak(r),a(i.hat)];const e=this.symbol(ee(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 B(s)?[...this.leftSide(r),a(i.minus),...this.quantityIfSum(s.args[1])]:[...this.leftSide(r),a(i.plus),...this.speak(s)];case"-":return B(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):Ao(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:`${Ao(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 he(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 n.length?[a(i.theSet),...l()]:[a(i.emptySet)];case"setbuilder":return[a(i.setOf),..."op"===n[0].type&&"∈"===n[0].op?[...this.speak(n[0].args[0]),a("in"),...this.speak(n[0].args[1])]:this.speak(n[0]),a(i.suchThat),...this.speak(n[1])];case"evaluated":return[...this.speak(n[0]),a(`${i.comma} ${i.evaluatedFrom}`),...this.speak(n[2]),a(i.to),...this.speak(n[3])];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=he(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(B(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(wo))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)&&!B(e),o=this.grouped(t,null,i(t,"/")),a=this.isCall(t)?[s(r.comma)]:[],l=this.speak(n),u=i(n,"/")||this.audio&&i(n,"*")&&l.some(e=>e.id===n.id&&e.text===r.times),c=this.isCompound(n)||this.audio&&u;return[...o,...a,s(r.over),...c?[this.seg(n,r.quantity),...l,...this.closer(n,"endFraction")]:l]}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||B(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}=se(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(j(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=j(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[xo,$o,So,No,ko])Object.setPrototypeOf(e,null);function Eo(e,t={}){return vr(e)?[]:function(e,t={}){return Mo(e,t,!1)}(gr(e),t)}function Io(e,t={}){return vr(e)?"":qo(gr(e),t)}const zo={"(":{fill:"M0.92,0 C0.1,0.2 0.1,0.8 0.92,1 L1,0.975 C0.48,0.75 0.48,0.25 1,0.025 Z"},")":{fill:"M0.08,0 C0.9,0.2 0.9,0.8 0.08,1 L0,0.975 C0.52,0.75 0.52,0.25 0,0.025 Z"},"{":{fill:"M1,0 C0.45,0 0.5,0.05 0.5,0.2 L0.5,0.38 C0.5,0.46 0.35,0.49 0.05,0.5 C0.35,0.51 0.5,0.54 0.5,0.62 L0.5,0.8 C0.5,0.95 0.45,1 1,1 L1,0.985 C0.68,0.985 0.64,0.95 0.64,0.8 L0.64,0.62 C0.64,0.53 0.55,0.505 0.3,0.5 C0.55,0.495 0.64,0.47 0.64,0.38 L0.64,0.2 C0.64,0.05 0.68,0.015 1,0.015 Z"},"}":{fill:"M0,0 C0.55,0 0.5,0.05 0.5,0.2 L0.5,0.38 C0.5,0.46 0.65,0.49 0.95,0.5 C0.65,0.51 0.5,0.54 0.5,0.62 L0.5,0.8 C0.5,0.95 0.55,1 0,1 L0,0.985 C0.32,0.985 0.36,0.95 0.36,0.8 L0.36,0.62 C0.36,0.53 0.45,0.505 0.7,0.5 C0.45,0.495 0.36,0.47 0.36,0.38 L0.36,0.2 C0.36,0.05 0.32,0.015 0,0.015 Z"},sqrt:{stroke:"M0,0.62 L0.18,0.55 L0.45,0.97 L0.98,0"},cancel:{stroke:"M0,1 L1,0"},int:{stroke:"M0.95,0.09 C0.9,0.01 0.72,0 0.66,0.12 C0.6,0.25 0.42,0.75 0.34,0.88 C0.28,0.99 0.1,0.99 0.05,0.91"},sum:{fill:"M0.04,0 L0.94,0 L0.98,0.24 L0.94,0.24 C0.9,0.1 0.8,0.07 0.62,0.07 L0.24,0.07 L0.58,0.5 L0.2,0.93 L0.64,0.93 C0.82,0.93 0.92,0.9 0.95,0.76 L0.99,0.76 L0.94,1 L0.02,1 L0.47,0.47 Z"},prod:{fill:"M0,0 L1,0 L1,0.04 L0.88,0.05 L0.88,0.95 L1,0.96 L1,1 L0.62,1 L0.62,0.96 L0.74,0.95 L0.74,0.06 L0.26,0.06 L0.26,0.95 L0.38,0.96 L0.38,1 L0,1 L0,0.96 L0.12,0.95 L0.12,0.05 L0,0.04 Z"}};function _o(e,t,n=""){const r=zo[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 jo=.8,To=.2,Lo=.25,Fo=.7,Zo="−",Co={"+":"add","-":"sub","*":"mul","/":"frac","^":"pow",_:"subscript",neg:"neg",pm:"pm","!":"factorial","=":"eq","===":"eq","≠":"neq","≠=":"neq","<":"lt",">":"gt","≤":"le","≥":"ge","≈":"approx","≡":"equiv","∈":"in","∉":"notin","∪":"union","∩":"intersect","→":"to","±":"pm","&":"and","|":"or","\\not":"not","\\xor":"xor","\\nand":"nand","\\nor":"nor","\\implies":"implies","\\iff":"iff","?:":"cases","()":"tuple","[]":"list","{}":"set","(]":"interval","[)":"interval","\\sumidx":"sum","\\prodidx":"prod",mod:"mod",pmod:"pmod",pmatrix:"matrix",bmatrix:"matrix",vmatrix:"matrix"},Ro={"=":"=","===":"=","≠":"≠","≠=":"≠","<":"<",">":">","≤":"≤","≥":"≥","∈":"∈","∉":"∉","→":"→","≈":"≈","≡":"≡","&":"∧","|":"∨","\\xor":"⊕","\\nand":"↑","\\nor":"↓","\\implies":"⇒","\\iff":"⇔"},Bo={"±":"±","∪":"∪","∩":"∩",mod:"mod"},Po=["sin","cos","tan","csc","sec","cot","sinh","cosh","tanh"],Do={arcsin:"sin",arccos:"cos",arctan:"tan",arcsec:"sec",arccsc:"csc",arccot:"cot",arcsinh:"sinh",arccosh:"cosh",arctanh:"tanh"},Wo=[...Po,...Object.keys(Do),"ln","det"],Uo={atan2:"atan2",max:"max",min:"min",gcd:"gcd",mean:"mean",round:"round",fixed:"fixed",expm1:"expm1",random:"random"},Vo={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]},Ho=["int","lim","\\sumidx","\\prodidx"],Go={"\\partial":"∂","\\nabla":"∇","\\ell":"ℓ","\\infty":"∞","\\emptyset":"∅"},Qo={vec:"→",hat:"ˆ",widehat:"ˆ",tilde:"˜",dot:"˙",ddot:"¨"},Xo=/^[acegmnopqrsuvwxyzαγεημνοπρστυχω]$/,Jo=e=>"symbol"===e?.type&&Xo.test(T[e.value]??e.value),Yo=["boxed","overline","bar","underline","cancel",...Object.keys(Qo)],Ko={prefix:"mv",display:!0,fnParens:"auto",trigPowers:!0,inverseTrig:"arc",derivativeBrackets:"[",scriptFractions:"slash",cases:!0,label:!0,mathml:null,attributes:null,style:null},ea=e=>String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),ta=e=>+e.toFixed(3)+"em",na=(e,t=jo,n=To)=>({html:e,h:t,d:n});function ra(...e){const t=e.flat().filter(Boolean);return{html:t.map(e=>e.html).join(""),h:Math.max(jo,...t.map(e=>e.h)),d:Math.max(To,...t.map(e=>e.d))}}function sa(e,t={}){const n=new ia({...Ko,...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):Io(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="${ea(o)}"`}>${a}${i}</span>`,h:r.h,d:r.d}}class ia{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=na(this.el(e,ea(t)));return n.leaf={kind:e,content:ea(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="${ea(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}="${ea(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?[ea(s.class)]:[]).join(" "),a=n.leaf?n.leaf.content:n.html;return{html:`<span class="${o}"${i?` style="${ea(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){const t=/^(-?\d*\.)(\d*)\.\.$/.exec(e.value);if(t){const[,n,r]=t;let s=1;for(let e=1;2*e<=r.length;e++)if(r.slice(-e)===r.slice(-2*e,-e)){s=e;break}let i=r;for(;i.endsWith(r.slice(-s))&&i.length>=s;)i=i.slice(0,-s);const o=this.text("num",(n+i).replace(/^-/,Zo)),a=this.text("num",r.slice(-s));return this.wrap(e,["number"],ra(o,na(this.el("over",a.html),a.h+.14,a.d)))}return this.wrap(e,["number"],this.text("num",e.value.replace(/^-/,Zo)))}symbol(e){return T[e]&&(e=T[e]),Go[e]?this.text("ord",Go[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)?na(this.el("var",ea(e[0]))+this.el("prime",ea(e.slice(1)))):/^Δ[A-Za-z]$/.test(e)?na(this.el("ord","Δ")+this.el("var",e[1])):/^d[A-Za-zα-ω]$/.test(e)?na(this.el("ord","d")+this.el("var",e[1])):e.endsWith("⁻¹")?this.script(this.symbol(e.slice(0,-2)),this.text("num","−1"),{level:0}):/^\\[A-Za-z]+$/.test(e)?this.text("name",e.slice(1)):/^[A-Za-z]{2,}$/.test(e)?this.text("name",e):this.text("ord",e)}operation(e,t){const{op: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=Co[n]??(/^[a-z0-9]+$/i.test(n)?n:"other"),c=t=>this.wrap(e,["op",`op-${l}`],t),h=(t,n)=>W(e,t,n)&&"/"!==t.op?this.fence(a(t)):a(t);if(Wo.includes(n)||"log"===n)return c(this.named(e,t));if(Uo[n])return c(ra(this.word(Uo[n]),this.fence(this.list(r,t))));if(o(n))return c(this.custom(e,t));const f=he(e);if(f)return c(this.matrix(e,f,t));if("{}"===n&&!r.length)return c(this.text("op","∅"));if(Vo[n])return c(this.fence(this.list(r,t),...Vo[n]));if(("|"===n||"&"===n)&&r.length>=2&&r.every(la)){const e=e=>"|"!==e.op&&"&"!==e.op||e.op===n?a(e):this.fence(a(e));return c(ra(r.map((t,r)=>r?[this.text("conj","|"===n?"or":"and"),e(t)]:[e(t)]).flat()))}if(Ro[n]&&2===r.length)return c(ra(h(s,"left"),this.rel(Ro[n]),h(i,"right")));if(Bo[n]&&2===r.length)return c(ra(h(s,"left"),this.bin(Bo[n]),h(i,"right")));switch(n){case"+":if(B(i)){const e=i.args[1],t=W({op:"-"},e,"right")?this.fence(a(e)):a(e);return c(ra(h(s,"left"),this.bin(Zo),this.wrap(i,["op","op-mul"],t)))}return"number"===i.type&&i.value.startsWith("-")?c(ra(h(s,"left"),this.bin(Zo),this.wrap(i,["number"],this.text("num",i.value.slice(1))))):c(ra(h(s,"left"),this.bin("+"),this.signed(i,h(i,"right"))));case"-":return c(ra(h(s,"left"),this.bin(Zo),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=P(s)&&u(P(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(ra(this.text("sign",Zo),U(n,s)?this.fence(a(s)):a(s,{before:t.before})));case"pm":return c(ra(this.text("sign","±"),U(n,s)?this.fence(a(s)):a(s)));case"!":return c(ra(U(n,s)?this.fence(a(s)):a(s,{forceParens:!0}),this.text("ord","!")));case"\\not":return c(ra(this.text("sign","¬"),U(n,s)?this.fence(a(s)):a(s)));case"pmod":return c(ra(a(s),this.fence(ra(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(ra(this.word("ln"),this.fence(ra(this.word("ln"),this.fence(a(s))))));case"logloglog":return c(ra(this.word("ln"),this.fence(ra(this.word("ln"),this.fence(ra(this.word("ln"),this.fence(a(s))))))));case"perm":return c(this.script(this.script(na(""),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):ra(a(s),this.bin("?"),a(i),this.bin(":"),a(r[2])));case"sum":case"prod":{const e={op:"sum"===n?"+":"*"},t=(t,n)=>W(e,t,n?"right":"left")?this.fence(a(t)):a(t);return c(ra(r.map((e,r)=>r?[this.bin("sum"===n?"+":"·"),t(e,r)]:[t(e,r)]).flat()))}case"setbuilder":return c(this.fence(ra(a(s),this.bin("|"),a(i)),"{","}"));case"evaluated":{const e=e=>this.render(e,{...t,level:t.level+1});return c(this.script(this.fence(a(s),"[","]"),e(r[3]),t,e(r[2])))}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 ra(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(B(e))return ra(this.text("sign",Zo),U("neg",r)?this.fence(this.render(r,t)):this.render(r,t));const s=function(e){const[t,n]=e.args;return{left:W(e,t,"left")&&"/"!==t.op,right:W(e,n,"right")&&"/"!==n.op}}(e);Ho.includes(n.op)&&(s.left=!0);const i=!e.written&&V(n,r,s),a=function(e){for(;"op"===e.type;){if(Wo.includes(e.op)||"log"===e.op||Uo[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 ra(l,i?na(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=Do[r]&&"power"===this.o.inverseTrig?this.script(this.word(Do[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&&oa(i),l=this.render(i,{...t,forceParens:!1,before:!1});return ra(o,a?ra(na(this.el("fnspace","")),l):this.fence(l))}custom(e,t){const n=ee(e.op),r=e.args;if(Yo.includes(n)&&1===r.length)return this.decorate(n,this.render(r[0],t),r[0]);return ra(/^[A-Za-z]′*(⁻¹)?$/.test(n)?this.symbol(n):this.word(n),na(this.el("callgap","")),this.fence(this.list(r,t)))}decorate(e,t,n){switch(e){case"boxed":return na(this.el("boxed",t.html),t.h+.22,t.d+.22);case"cancel":return na(this.el("cancel",t.html+_o("cancel",`${this.p}-cancel-line`)),t.h,t.d);case"underline":return na(this.el("underline",t.html),t.h,t.d+.12);case"overline":case"bar":return na(this.el("over"+(Jo(n)?" over-low":""),t.html),t.h+.14,t.d);default:{const r=Jo(n);return na(this.el("accent"+(r?" accent-low":""),this.el(`accent-mark accent-${e}`,Qo[e])+t.html),t.h+.3,t.d)}}}fraction(e,t){const[n,r]=e.args;if(t.level>0&&"slash"===this.o.scriptFractions&&oa(n,!0)&&oa(r,!0)){const e={...t,leftFactor:!1},s=(t,n)=>"op"!==t.type||oa(t)&&(!n||"*"!==t.op||B(t))?this.render(t,e):this.fence(this.render(t,e)),i=ra("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:${ta(r)}`),i=n?.06:0,o=Lo+i/2+.1+Math.max(To,r*e.d),a=this.el("frac"+(n?"":" frac-nobar"),this.el("numer",s(e))+this.el("denom",s(t)),`vertical-align:${ta(o)}`);return na(a,o+Math.max(jo,r*e.h),Math.max(jo,r*t.h)+Math.max(To,r*t.d)+.1+i/2-Lo)}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&&Po.includes(n.op)&&ca(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=W(e,n,"left")||"number"===n.type&&n.value.startsWith("-")||"/"===n.op||Wo.includes(n.op)||Ho.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:Fo,o=s?ra(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:${ta(i)}`);if(t&&!r)return na(e.html+this.el("sup",t.html,`font-size:${ta(i)};vertical-align:${ta(a/i)}`),Math.max(o.h,a+i*t.h),Math.max(o.d,i*t.d-a));if(r&&!t)return na(o.html+this.el("sub",r.html,`font-size:${ta(i)};vertical-align:${ta(-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,f=this.el("subsup",u(t)+u(r),`vertical-align:${ta(a)};height:${ta(c+h)}`);return na(o.html+f,Math.max(o.h,c),Math.max(o.d,h))}radical(e,t=null){const n=Math.max(e.h,jo)+.1+.06,r=Math.max(e.d,To),s=n+r,i=.5+.06*(s-1),o=_o("sqrt",`${this.p}-hook`,`width:${ta(i)};left:${ta(-i)}`);let a="";if(t){const e=.8*Fo;a=this.el("rootindex",t.html,`font-size:${ta(e)};vertical-align:${ta((.55*s-r)/e)}`)}return na(this.el("sqrt",a+this.el("radicand",o+e.html,`margin-left:${ta(i+.05)}`)),n,r)}fence(e,t="(",n=")"){const r=Math.max(e.h,jo)+Math.max(e.d,To),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:_o(e,`${this.p}-delim ${this.p}-delim-${t}`,`width:${ta(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");if(!s){const t=na(this.el("fence fence-line",a.html+e.html+l.html),Math.max(e.h,jo),Math.max(e.d,To));return t.fenced=!0,t}const u=`padding:${ta(i)} ${ta(l.w)} ${ta(i)} ${ta(a.w)}`,c=na(this.el("fence",a.html+e.html+l.html,u),Math.max(e.h,jo)+i,Math.max(e.d,To)+i);return c.fenced=!0,c}derivative(e,t){const n=this.leibniz(e,t),{by:r,at:s}=se(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}=se(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=ra(a(),l()?this.script(this.render(s,c),l(),c):this.render(s,c)),f=e=>ra(l()?this.script(a(),l(),c):a(),e||[]),p=t.level>0||t.inFraction||!this.o.display?.8:1;if(i)return this.stack(f(this.render(r,c)),h,!0,p);const m=P(r)&&u(P(r))<100,[d,g]="("===this.o.derivativeBrackets?["(",")"]:["[","]"],v=m?this.fence(this.render(r,t),d,g):this.render(r,t);return ra(this.stack(f(),h,!0,p),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",j(n)||"x");let u,c=null,h=null;switch(e.length){case 1:u=l();break;case 2:K(r)?u=o(r):(u=l(),c=a(r));break;case 3:K(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 f=o(n),p=na(this.el("dx",this.el("d","d")+u.html),u.h,u.d);return ra(this.bigSign("int",f,c,h,t),f,p)}bigSign(e,t,n,r,s){const i=!this.o.display||s.level>0,o=Math.max(i?.6:.95,Math.max(t.h-Lo,t.d+Lo)+.12),a=_o(e,`${this.p}-bigsign ${this.p}-${e}sign`,`height:${ta(2*o)};width:${ta(i?.38:.5)};vertical-align:${ta(Lo-o)}`);if(!n&&!r)return na(a,Lo+o,o-Lo);const l=Fo,u=r||na(""),c=n||na(""),h=Lo+o-l*u.h;c.d;const f=this.el("limits",this.el("script",u.html,`font-size:${ta(l)}`)+this.el("script lower",c.html,`font-size:${ta(l)}`),`vertical-align:${ta(h)};height:${ta(2*o)}`);return na(a+f,Lo+o,o-Lo)}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 ra(this.word("lim"),na(this.el("fnspace","")),this.body(n,t));case 2:{const e=j(n),t="number"===r.type||"symbol"===r.type&&r.value.includes("∞");u=e&&t?ra(this.text("var",e),l(),a(r)):a(r);break}case 3:u=ra(a(r),l(),a(s));break;default:{const e=L(i).toLowerCase().startsWith("r")?"+":Zo;u=ra(a(r),l(),this.script(a(s),this.wrap(i,["symbol"],this.text("ord",e)),o))}}return ra(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):na(this.el("under",e.html+this.el("script",t.html,`font-size:${ta(.7)}`)),e.h,Math.max(e.d,To)+.05+.7*(t.h+t.d))}body(e,t){const n=P(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=_o(e,`${this.p}-bigsign`,`height:${ta(2*t)};width:${ta(.8)};vertical-align:${ta(Lo-t)}`);return ra(this.script(na(r,Lo+t,t-Lo),l,n,a),u)}const c=.68,h=Fo,f=_o(e,`${this.p}-bigsign`,`height:${ta(1.36)};width:${ta("sum"===e?1:1.05)}`),p=l?1.01+h*l.d:Lo-c,m=e=>this.el("script",e.html,`font-size:${ta(h)}`),d=this.el("bigop",(l?m(l):"")+f+(a?m(a):""),`vertical-align:${ta(p)}`);return ra(na(d,.93+(l?.08+h*(l.h+l.d):0),c-Lo+(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(jo,...e.map(e=>e.h)),d:Math.max(To,...e.map(e=>e.d))})),i=s.reduce((e,t)=>e+t.h+t.d,0)+.3*(t.length-1),o=Lo+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"],na(r)).html:r}).join(""),l=t[0].length,u=na(this.el("matrix",a,`grid-template-columns:repeat(${l},auto);vertical-align:${ta(o)}`),Lo+i/2,i/2-Lo),[c,h]=ce[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),ra(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=Lo+i/2-s[0].h,a=n.map(([e,t])=>this.el("case-value",e.html)+this.el("case-cond",t.html)).join(""),l=na(this.el("cases",a,`vertical-align:${ta(o)}`),Lo+i/2,i/2-Lo);return this.fence(l,"{","")}}function oa(e,t=!1){return"number"===e.type?!e.value.startsWith("-")||t:"symbol"===e.type||"op"===e.type&&("abs"===e.op||he(e)?!t:!t||"neg"!==e.op&&"^"!==e.op?"*"===e.op&&!B(e)&&e.args.every(e=>"number"===e.type&&!e.value.startsWith("-")||ua(e)||"*"===e.op&&oa(e,t)):oa(e.args[0],!0)&&("neg"===e.op||oa(e.args[1],!0)))}const aa=["=","===","≠","≠=","<",">","≤","≥","≈","≡","∈","∉"],la=e=>"op"===e.type&&e.args.length>=2&&(2===e.args.length&&aa.includes(e.op)||("|"===e.op||"&"===e.op)&&e.args.every(la)),ua=e=>"symbol"===e.type&&(1===e.value.length||/^[α-ωΑ-Ω]$/.test(e.value)||Boolean(T[e.value])),ca=e=>"number"===e.type&&/^[1-9]\d*$/.test(e.value)&&Number(e.value)<10;for(const e of[Co,Ro,Bo,Do,Uo,Vo,Go,Qo])Object.setPrototypeOf(e,null);function ha(e){const{id:t,from:n,...r}=e;return r.args&&(r.args=r.args.map(ha)),r}const fa=e=>I(e).join(" ");function pa(e,t){const n=new Set;ma(e,t,n);const r=[];return _(e,e=>{n.has(e)&&r.push(e)}),r}function ma(e,t,n){if(null!=t)if(Array.isArray(t))t.forEach(t=>ma(e,t,n));else if("number"!=typeof t)if("function"!=typeof t){if("string"==typeof t){const r=fa(dr(t));return void _(e,e=>{fa(e)===r&&n.add(e)})}if(t.path){const r=da(e,t.path);return void(r&&n.add(r))}if(t.type){const r=fa(t);_(e,e=>{e!==t&&fa(e)!==r||n.add(e)})}}else _(e,(e,r)=>{t(e,r)&&n.add(e)});else _(e,e=>{e.id===t&&n.add(e)})}function da(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 ga(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 va(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 ba(e,t={}){const{blocks:n}=t;if("string"==typeof e)return dr(e,n?{blocks:e=>n(e,t.scope)}:{});if(Array.isArray(e))return E(e);if(e&&"object"==typeof e&&e.type){if(void 0!==e.id)return e;const t=structuredClone(e);return _(t,e=>{"op"!==e.type&&void 0!==e.value&&(e.value=String(e.value))}),va(t)}throw new Error("Inline Math needs an expression, standard postfix or a tree")}function ya(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(wa(r))for(const n of pa(e,t))a.set(n,`color:${r}`);const l=new Set(void 0===r?[]:pa(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 wa(e){return"string"==typeof e&&/^[#\w\s.,%()/+-]+$/.test(e)&&!/url\s*\(|expression/i.test(e)}function xa(e,t={}){return ba(e,{...t,blocks:t.blocks??yo})}function $a(e,t={}){return function(e,t={}){const n=ba(e,t);return sa(n,ya(n,t)).html}(e,{...t,blocks:t.blocks??yo})}function ka(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 ha(r(e,0))}function qa(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`},f=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:f.fontSize}),h(),a.body.appendChild(c),l.getSelection?.()?.removeAllRanges(),c.focus(),c.select();let p=!1;const m=()=>{p=!0,c.remove()};c.cancelEdit=()=>{p||(m(),s&&s())};const d=e=>{if(p)return!0;if(!e||c.value===t)return m(),s&&s(),!0;let i;try{i=n(c.value)}catch(e){return c.setAttribute("aria-invalid","true"),c.title=e.message,!1}return m(),r(i,c.value),!0};return c.addEventListener("keydown",e=>{e.stopPropagation(),"Enter"===e.key&&(e.preventDefault(),d(!0)),"Escape"===e.key&&(e.preventDefault(),d(!1))}),c.addEventListener("input",()=>{h(),c.removeAttribute("aria-invalid"),c.removeAttribute("title")}),c.addEventListener("blur",()=>{d(!0)||d(!1)}),c}class Ma{constructor(e,t,n={}){this.element=e,this.options=n,this.p=n.prefix||"mv",this.handlers=[],this.clicks=[],this.active=null,this.live=Aa(e,n.announce,this.p),this.set(t)}set(e,{animate:t=!1,duration:n=600,easing:r="ease-in-out"}={}){const s=xa(e,this.options),{html:i}=sa(s,ya(s,this.options));if(this.editor){const e=this.editor;this.editor=null,e.cancelEdit?.()}const o=Sa(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 Io(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 pa(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=pa(this.tree,r)[0];t({node:s,id:r,path:ga(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(pa(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=ga(this.tree,n.id)||[],s=this.elementOf(n)||this.root;let i="Edit";try{i=`Edit ${Io(n)}`}catch{}const o=()=>{t&&this.root.focus&&this.root.focus()};return this.editor=qa(s,this.editing.toText(n),{label:i,prefix:this.p,parse:e=>xa(e,this.options),commit:(e,n)=>{this.set(ka(this.tree,r,e),{animate:!0});const s=da(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||Aa(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:ga(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?Io(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=ga(this.tree,e.id);for(let e=t?t.length-1:-1;e>0;e--){const n=da(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 Eo(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=fa(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(fa(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(fa(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 Aa(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 Sa(e){return!!e&&("always"===e||!("function"==typeof matchMedia&&matchMedia("(prefers-reduced-motion: reduce)").matches))}const Na=Symbol.for("inlinemath.expressions"),Oa=new Set(["symbol","number"]);function Ea(e){return e?"symbol"===e.type?e.value:"op"===e.type&&"_"===e.op&&2===e.args.length&&"symbol"===e.args[0].type&&Oa.has(e.args[1].type)?`${e.args[0].value}_${e.args[1].value}`:null:null}function Ia(e){const{id:t,...n}=e;return n.args&&(n.args=n.args.map(Ia)),n}function za(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 _a=new Set;function ja(e,t){let n=!1;const r=new Set,s=(e,i=_a)=>{const o=Ea(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(ha(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?j(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?Ia(i):e,changed:n}}const Ta="[-+]?(?:\\d+\\.?\\d*|\\.\\d+)",La=new RegExp(`^(${Ta})\\s*\\.\\.\\s*(${Ta})(?:\\s+step\\s+(${Ta}))?(?:\\s*=\\s*(${Ta}))?$`);function Fa(e){const t=/^\s*\[\[([\s\S]*)\]\]\s*$/.exec(e);if(!t||/\]\s*,\s*\[/.test(t[1]))return null;const n=t[1].trim(),r=La.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 Za=Symbol("set on the page");class Ca{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(Za));n.set(e,{name:e,text:t,key:`page:${t}`,input:null}),this.owners.delete(Za),this.owners.set(Za,n)}return this.notify(null,e),this}clear(e){return void 0===e?(this.owners.clear(),this.chosen.clear()):(this.owners.get(Za)?.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 Ra(){return new Ca}const Ba=Ra(),Pa=new RegExp("(\\d+)","g");function Da(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=Ka.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}=Wa(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 Wa(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 Ua=e=>String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),Va=/^\s*([A-Za-z\u0370-\u03ff](?:_\{?\w+\}?)?)\s*=\s*([^=<>≤≥]+)$/;function Ha(e,t,n,r){const{text:s,math:i}=Da(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,f=[],p=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=xa(a(r),e)}catch{}t.set(n,s)}return t.get(n)}};let m=!0;const d=i.map((e,n)=>{const{source:r,display:s}=e;m&&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=bo(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=p({});for(const e of o.keys()){const r=n(e);if(r)try{t[e]=I(ja(r,t=>t===e?null:n(t)).tree)}catch{}}u[Na]=t})(),m=!1);const i=s?"mv-md-display":"mv-md-math",d=(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:Ea(xa(o))}catch{}return null!==l&&a?{hidden:n,lhs:o,name:l,rhs:a,input:Fa(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="${Ua(r)}" aria-label="${Ua(r)}"`;if("dropdown"===n.kind)return`<select ${s}>${n.options.map(e=>`<option value="${Ua(e)}"${e===t?" selected":""}>${Ua(e)}</option>`).join("")}</select>`;return"slider"===n.kind?`<input type="range" ${s} min="${n.min}" max="${n.max}" step="${n.step}" value="${Ua(t)}"><output class="mv-md-output" data-mv-out="${Ua(r)}">${Ua(t)}</output>`:`<input type="text" ${s} value="${Ua(t)}" size="${Math.max(4,t.length+1)}" spellcheck="false" autocomplete="off">`}(l,a(l));u=s?e:`${$a(g.lhs,i)}<span class="mv-md-assign" aria-hidden="true">≔</span>${e}`,h.add(n)}else{const e=ja(xa(g.rhs,i),p(i)).tree;if(!s){const t=va({type:"op",op:"=",args:[ha(xa(g.lhs)),void 0===e.id?e:ha(e)]});f[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>")}($a(t,i),i.prefix)}}return o.delete(t),o.set(t,l),c.set(t,l),m=!0,s&&!r?"":d(u,r?" mv-md-input-def":"")}const{tree:v,changed:b}=ja(xa(r,i),p(i));b&&va(v),f[n]=v;const y=$a(v,i);return!b&&!1!==t.define&&function(e,t,n){const r=Va.exec(e);if(!r||/\{\{/.test(r[2]))return!1;const s=r[1].replace(/[{}]/g,"");if(n.has(s))return!1;try{const e=bo(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)&&(m=!0),d(y)}catch(t){return`<span class="mv-md-error" data-mv-md="${n}" title="${Ua(t.message)}"><code>${Ua(e.raw)}</code></span>`}});return{text:s,math:i,drawn:d,defs:c,inputs:h,trees:f}}const Ga=/^(https?:|mailto:|#|\/|\.{0,2}\/|[^:]*$)/i,Qa=e=>Ga.test(e.trim())?Ua(e.trim()):"#",Xa=/\uE002(\d+)\uE003/g;function Ja(e,t,n,r=[]){const s=e=>(r.push(e),`${r.length-1}`),i=e=>(e=>e.replace(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&"))(n(e).replace(Xa,(e,t)=>(r[Number(t)]??"").replace(/<[^>]*>/g,"")));let o=e;o=o.replace(/(`+)([\s\S]*?[^`])\1(?!`)/g,(e,t,r)=>s(`<code>${Ua(n(r.trim()))}</code>`)),o=o.replace(/\\([\\`*_{}[\]()#+\-.!|~$<>"'])/g,(e,t)=>s(Ua(t))),o=o.replace(/<((?:https?:\/\/|mailto:)[^\s>]+)>/g,(e,t)=>s(`<a href="${Qa(t)}">${Ua(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="${Qa(i(n))}" alt="${Ua(i(t))}"${r?` title="${Ua(i(r))}"`:""}>`)),o=o.replace(/\[([^\[\]]+)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,o,a,l)=>s(`<a href="${Qa(i(a))}"${l?` title="${Ua(i(l))}"`:""}>${Ja(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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),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(Xa,(e,t)=>r[Number(t)]??"");return o}const Ya=/^( {0,3})(#{1,6}\s|>|```|~~~|([-*+]|\d{1,9}[.)])\s|(\*[ \t]*){3,}$|(-[ \t]*){3,}$|(_[ \t]*){3,}$)/,Ka=/^( {0,3})([-*+]|\d{1,9}[.)])(\s+|$)/,el=/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/,tl=e=>Ya.test(e)&&!/^ {0,3}[-=]+\s*$/.test(e)&&!/^ {0,3}(?!1[.)])\d{1,9}[.)]\s/.test(e);function nl(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 rl(e,t,n,r=0){const s=[];let i=0;const o=e=>Ja(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-${Ua(l[2])}"`:"";s.push(`<pre><code${r}>${Ua(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(nl(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${rl(o,t,n,r+1)}\n</blockquote>`);continue}const c=Ka.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=Ka.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&&Ka.test(t)&&(u=!0);break}if(t.startsWith(" ".repeat(Math.min(n,4))))r.push(t.slice(Math.min(n,4)));else{if(Ka.test(t)||Ya.test(t))break;r.push(t)}i++}for(l.push(r);i<e.length&&!e[i].trim()&&void 0!==e[i+1]&&Ka.test(e[i+1]);)i++}const h=o?"ol":"ul",f=l.map(e=>{let s=rl(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${f.join("\n")}\n</${h}>`);continue}if(a.includes("|")&&void 0!==e[i+1]&&el.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>${Ua(n(t.join("\n")))}</code></pre>`);continue}const h=[];for(;i<e.length&&e[i].trim()&&(!h.length||!tl(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 sl(e,t={},n=e=>e){return rl(String(e).replace(/\r\n?/g,"\n").replace(/[\uE002\uE003]/g,"�").split("\n"),t,n)}function il({text:e,math:t,drawn:n},r){return(r.render?r.render(e):sl(e,r,e=>e.replace(Pa,(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(Pa,(e,t)=>n[Number(t)]??"").replace(/<p>\s*<\/p>\n?/g,"")}const ol=new WeakMap,al=new Set;function ll(){for(const e of al)e.connected()&&!e.element.isConnected&&e.stop(!0)}function ul(e){const t=e=>function(e){if(e.length>1e6)throw new Error("The output would be too long");return e}("op"===e.type?fl(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 cl={"+":"+","-":"-","*":"*","/":"/","^":"^",mod:"mod","±":"±","=":"=","===":"===","≠":"≠","≠=":"≠","<":"<",">":">","≤":"≤","≥":"≥","∈":"∈","∉":"∉","→":"→","≈":"≈","∪":"∪","∩":"∩","≡":"≡","&":"∧","|":"∨","\\xor":"⊕","\\nand":"↑","\\nor":"↓","\\implies":"⇒","\\iff":"⇔"},hl={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]};function fl(e,t){const{op:n,args:r}=e,[s,i]=r,a=(e,r)=>c(n,P(e),r)?`(${t(e)})`:t(e),l=()=>r.map(t).join(", "),u=e=>U(n,e)?`(${t(e)})`:t(e);if("*"===n&&B(e))return fl({...e,op:"neg",args:[i]},t);if("+"===n&&B(i))return fl({...e,op:"-",args:[s,i.args[1]]},t);if("-"===n&&B(i))return fl({...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(cl[n])return`${a(s,"left")} ${cl[n]} ${a(i,"right")}`;if(ce[n])return`${n}(${he(e).map(e=>`[${e.map(t).join(", ")}]`).join(", ")})`;if(hl[n])return hl[n][0]+l()+hl[n][1];if(o(n))return`${ee(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`${ae(s)?`(${t(s)})`:t(s)} ? ${t(i)} : ${t(r[2])}`;case"sum":return r.map((e,n)=>c("+",P(e),n?"right":"left")?`(${t(e)})`:t(e)).join(" + ");case"prod":return r.map((e,n)=>c("*",P(e),n?"right":"left")?`(${t(e)})`:t(e)).join(" * ");case"setbuilder":return`{${r.map(t).join(" : ")}}`;case"evaluated":return`evaluated(${r.map(t).join(", ")})`;case"der":{const{n:n,body:r,by:s,at:i,variable:o}=se(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&&K(r)?t(r):j(n)||"x",a=`${t(n)} d${o}`;return 1===e.length||2===e.length&&K(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)}, ${L(i).toLowerCase().startsWith("r")?"r":"l"})`:`lim(${e.map(t).join(", ")})`}(r,t);case"\\sumidx":return pl("∑",r,t);case"\\prodidx":return pl("∏",r,t)}return`${n}(${l()})`}function pl(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=j(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[cl,hl])Object.setPrototypeOf(e,null);function ml(e){return vr(e)?"":ul(gr(e))}const dl=new Map,gl=-1,vl="\\:",bl=e=>"string"==typeof e&&e.startsWith(vl)&&e.length>2;function yl(e){if(!e||!e.symbol)throw new Error("operator needs a symbol");if(!Number.isInteger(e.arity)||e.arity<0&&e.arity!==gl)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 dl.set(t.symbol,t),t}const wl=Object.freeze({symbol:vl,arity:gl,commutative:!1,fold:null,label:"function"});function xl(e){const t=dl.get(e);return t||(bl(e)?{...wl,symbol:e,label:e.slice(2)}:null)}function $l(e){return dl.has(e)||bl(e)}const kl=e=>Number.isFinite(e)&&Number.isInteger(e)?e:null,ql=e=>Number.isFinite(e)?e:null;!function(){yl({symbol:"+",arity:2,commutative:!0,label:"add",fold:(e,t)=>ql(e+t)}),yl({symbol:"-",arity:2,label:"subtract",fold:(e,t)=>ql(e-t)}),yl({symbol:"*",arity:2,commutative:!0,label:"multiply",fold:(e,t)=>ql(e*t)}),yl({symbol:"/",arity:2,label:"divide",fold:(e,t)=>0===t?null:kl(e/t)}),yl({symbol:"^",arity:2,label:"power",fold:(e,t)=>Number.isInteger(t)&&Math.abs(t)<=64?ql(e**t):null}),yl({symbol:"neg",arity:1,label:"negate",fold:e=>ql(-e)}),yl({symbol:"pm",arity:1,label:"plus or minus"}),yl({symbol:"±",arity:2,label:"plus or minus"}),yl({symbol:"mod",arity:2,label:"modulo",fold:(e,t)=>0===t?null:kl((e%t+t)%t)}),yl({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}),yl({symbol:"_",arity:2,label:"subscript"}),yl({symbol:"der",arity:2,label:"derivative"}),yl({symbol:"evaluated",arity:4,label:"evaluated from a to b"}),yl({symbol:"setbuilder",arity:2,label:"the set of … such that"}),yl({symbol:"int",arity:gl,label:"integral"}),yl({symbol:"lim",arity:gl,label:"limit"}),yl({symbol:"\\sumidx",arity:gl,label:"sum over an index"}),yl({symbol:"\\prodidx",arity:gl,label:"product over an index"}),yl({symbol:"abs",arity:1,label:"absolute value",fold:e=>ql(Math.abs(e))}),yl({symbol:"floor",arity:1,label:"floor",fold:e=>ql(Math.floor(e))}),yl({symbol:"ceil",arity:1,label:"ceiling",fold:e=>ql(Math.ceil(e))}),yl({symbol:"round",arity:2,label:"round",fold:(e,t)=>Number.isInteger(t)?ql(Math.round(e*10**t)/10**t):null}),yl({symbol:"fixed",arity:2,label:"fixed",fold:()=>null}),yl({symbol:"sqrt",arity:1,label:"square root",fold:e=>kl(Math.sqrt(e))}),yl({symbol:"root",arity:2,label:"nth root",fold:(e,t)=>kl(Math.round(t**(1/e))**e===t?Math.round(t**(1/e)):NaN)});for(const e of["sin","cos","tan","csc","sec","cot","sinh","cosh","tanh","arcsin","arccos","arctan","arcsec","arccsc","arccot","arcsinh","arccosh","arctanh","ln","loglog","logloglog","expm1"])yl({symbol:e,arity:1,label:e});yl({symbol:"log",arity:2,label:"log to a base"}),yl({symbol:"atan2",arity:2,label:"atan2"}),yl({symbol:"perm",arity:2,label:"permutations"}),yl({symbol:"comb",arity:2,label:"combinations"}),yl({symbol:"random",arity:0,label:"random"});for(const e of["max","min","gcd","mean","sum","prod"])yl({symbol:e,arity:gl,label:e});for(const e of["()","[]","{}","(]","[)"])yl({symbol:e,arity:gl,label:"group"});for(const e of["pmatrix","bmatrix","vmatrix"])yl({symbol:e,arity:gl,label:"matrix"});yl({symbol:"det",arity:1,label:"determinant"});for(const e of["=","===","≠","≠=","<",">","≤","≥","∈","∉","∪","∩","≈","≡","→","pmod","&","|","\\xor","\\nand","\\nor","\\implies","\\iff"])yl({symbol:e,arity:2,label:e});yl({symbol:"\\not",arity:1,label:"not"}),yl({symbol:"?:",arity:3,label:"if then else"})}();const Ml="num",Al="sym",Sl="op",Nl=Object.freeze([]);class Ol extends Error{constructor(e){super(e),this.name="ExprError"}}function El(e){if("number"!=typeof e||!Number.isFinite(e))throw new Ol(`not a finite number: ${e}`);const t=(n=e,Object.is(n,-0)?"0":String(n));var n;return Object.freeze({type:Ml,token:t,value:e,args:Nl,s:t})}function Il(e){if("string"!=typeof e||""===e)throw new Ol("symbol needs a non-empty token");return Object.freeze({type:Al,token:e,value:null,args:Nl,s:e})}function zl(e){const t=/^(-?)0*(\d+?)(?:\.(\d*?)0*)?$/.exec(String(e));if(!t)throw new Ol(`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:Ml,token:o,value:Number(o),args:Nl,s:o})}const _l=/^-?\d+(\.\d+)?$/;function jl(e){const t=String(e);if(_l.test(t))return zl(t);if(""!==t&&!/\s/.test(t)){const e=Number(t);if(Number.isFinite(e))return El(e)}return Il(t)}function Tl(e,t){const n=xl(e);if(!n)throw new Ol(`unknown operator "${e}"`);if(n.arity!==gl&&t.length!==n.arity)throw new Ol(`"${e}" takes ${n.arity} operand(s), got ${t.length}`);const r=Object.freeze(t.slice()),s=n.arity===gl?` ${r.length}`:"",i=`${r.length?r.map(e=>e.s).join(" "):""}${r.length,""}${s} ${e}`.trimStart();return Object.freeze({type:Sl,op:e,token:e,value:null,args:r,s:i})}const Ll=e=>e.type===Ml,Fl=e=>e.type===Sl;function Zl(e){return Cl(function(e){const t=String(e).trim();return""===t?[]:t.split(/\s+/)}(e))}function Cl(e){if(!Array.isArray(e))throw new Ol("fromPostfix needs an array of tokens");if(0===e.length)throw new Ol("empty expression");const t=[];for(let n=0;n<e.length;n++){const r=String(e[n]);if($l(r)){let e=xl(r).arity;if(e===gl){const s=t.pop();if(e=s&&s.type===Ml&&Number.isInteger(s.value)&&s.value>=0?s.value:-1,e<0)throw new Ol(`"${r}" at position ${n+1} takes any number of operands, so a count must come before it`)}if(t.length<e)throw new Ol(`"${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(Tl(r,s))}else t.push(jl(r))}if(1!==t.length){const n=[...new Set(e.filter(e=>!$l(e)))];throw new Ol(`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 Rl(e){if(e.type!==Sl)return 0;let t=0;for(const n of e.args)t=Math.max(t,Rl(n));return t+1}function Bl(e){if(e.type!==Sl)return 1;let t=1;for(const n of e.args)t+=Bl(n);return t}function Pl(e,t=[]){if(e.type!==Sl)t.push(e.token);else for(const n of e.args)Pl(n,t);return t}function Dl(e){return e.type===Ml||e.type!==Al&&e.args.every(Dl)}function Wl(e,t="pre",n=[],r=[]){"pre"===t&&r.push({node:e,path:n});for(let s=0;s<e.args.length;s++)Wl(e.args[s],t,n.concat(s),r);return"post"===t&&r.push({node:e,path:n}),r}function Ul(e,t,n){if(0===t.length)return n;const[r,...s]=t,i=e.args.slice();return i[r]=Ul(i[r],s,n),Tl(e.op,i)}class Vl extends Error{constructor(e){super(e),this.name="CasError"}}const Hl=1e5,Gl=e=>e<0n?-e:e,Ql=e=>0n===e?0:Gl(e).toString(2).length;function Xl(e,t){for(e=Gl(e),t=Gl(t);t;)[e,t]=[t,e%t];return e}class Jl{constructor(e,t=1n){if(0n===t)throw new Vl("division by zero");t<0n&&(e=-e,t=-t);const n=Xl(e,t)||1n;if(this.n=e/n,this.d=t/n,Ql(this.n)>Hl||Ql(this.d)>Hl)throw new Vl("a number too large to keep exactly")}static of(e){return new Jl(BigInt(e))}add(e){return new Jl(this.n*e.d+e.n*this.d,this.d*e.d)}sub(e){return new Jl(this.n*e.d-e.n*this.d,this.d*e.d)}mul(e){return new Jl(this.n*e.n,this.d*e.d)}div(e){if(0n===e.n)throw new Vl("division by zero");return new Jl(this.n*e.d,this.d*e.n)}neg(){return new Jl(-this.n,this.d)}abs(){return this.n<0n?this.neg():this}inv(){return Jl.ONE.div(this)}pow(e){if((e=BigInt(e))<0n)return this.inv().pow(-e);if((0n===this.n||1n===Gl(this.n))&&1n===this.d)return 0n===e||-1n===this.n&&e%2n==0n?Jl.ONE:this;if(BigInt(Math.max(Ql(this.n),Ql(this.d)))*e>BigInt(Hl))throw new Vl("a power too large to work out exactly");return new Jl(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 Jl(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(Ql(this.n),Ql(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 Yl(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 Jl(BigInt((r||"0")+s),10n**BigInt(s.length));const a=Number(i);return a&&(o=o.mul(Jl.of(10).pow(a))),n?o.neg():o}function Kl(e,t){if(e<2n)return e;if(t>=Ql(e))return 1n;const n=BigInt(t);let r=1n<<BigInt(Math.ceil(Ql(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}Jl.ZERO=new Jl(0n),Jl.ONE=new Jl(1n),Jl.MINUS_ONE=new Jl(-1n),Jl.HALF=new Jl(1n,2n);const eu=(()=>{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 tu(e,t){const n=BigInt(t);let r=1n,s=1n,i=e;for(const e of eu){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=Kl(e,t);return n**BigInt(t)===e?n:null}(i,t);null!==e?r*=e:s*=i}return{outside:r,inside:s}}const nu=new Set(["pi","e","π"]),ru={complex:!1};function su(e,t){const n=ru.complex;ru.complex=Boolean(e);try{return t()}finally{ru.complex=n}}const iu=e=>nu.has(e)||ru.complex&&"i"===e,ou=e=>ru.complex&&"atom"===e.k&&"sym"===e.node.type&&"i"===e.node.token,au=e=>({k:"num",q:e}),lu=au(Jl.ONE),uu=au(Jl.ZERO),cu=au(Jl.HALF),hu=e=>"num"===e.k,fu=e=>({k:"atom",node:e}),pu=new WeakMap;function mu(e){let t=pu.get(e);return void 0===t&&pu.set(e,t=Vu(e).s),t}function du(e){if("num"===e.k)return 0;if("atom"===e.k)return"sym"===e.node.type&&iu(e.node.token)?0:1;if("add"===e.k)return Math.max(...e.terms.map(e=>du(e.x)));let t=0;for(const n of e.fs){const e=du(n.b);e&&(t+=e*(hu(n.e)?n.e.q.toNumber():1))}return t}function gu(e,t){return"num"===e.k?t&&!hu(t)?3:0:ou(e)?1.5:"atom"===e.k&&"sym"===e.node.type?iu(e.node.token)?t&&!hu(t)?3:1:2:"atom"===e.k?3:4}const vu=(e,t)=>e<t?-1:e>t?1:0;function bu(e){const t=new Map,n=(e,n)=>{"atom"!==e.k||"sym"!==e.node.type||iu(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,hu(t.e)?t.e.q.toNumber():1);else n(e,1);return t}function yu(e,t){const n=du(t.x)-du(e.x);if(n)return n;const r=bu(e.x),s=bu(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 vu(mu(e.x),mu(t.x))}function wu(e,t){return e.isOne?t:e.isZero?uu:qu([au(e),t])}function xu(e){if("num"===e.k)return{coef:e.q,rest:null};if("mul"!==e.k||e.c.isOne)return{coef:Jl.ONE,rest:e};const t=1===e.fs.length&&hu(e.fs[0].e)&&e.fs[0].e.q.isOne?e.fs[0].b:{k:"mul",c:Jl.ONE,fs:e.fs};return{coef:e.c,rest:t}}function $u(e){let t=Jl.ZERO;const n=new Map,r=(e,t)=>{const r=mu(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}=xu(n);r(e,t)}const s=[...n.values()].filter(e=>!e.coef.isZero);return s.length?t.isZero&&1===s.length?wu(s[0].coef,s[0].x):(s.sort(yu),{k:"add",c:t,terms:s}):au(t)}function ku(e,t){if(!hu(t))return e.isOne?{coef:Jl.ONE,fs:[]}:{coef:Jl.ONE,fs:[{b:au(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 Vl("division by zero");return{coef:Jl.ZERO,fs:[]}}if(e.isOne)return{coef:Jl.ONE,fs:[]};if(e.sign<0){if(n.d%2n==1n){const{coef:r,fs:s}=ku(e.neg(),t);return{coef:n.n%2n==0n?r:r.neg(),fs:s}}if(ru.complex&&2n===n.d){const{coef:r,fs:s}=ku(e.neg(),t);return{coef:r,fs:[...s,{b:Su,e:au(new Jl(n.n))}]}}return{coef:Jl.ONE,fs:[{b:au(e),e:t}]}}if(!e.isInteger){const r=ku(new Jl(e.n),t),s=ku(new Jl(e.d),au(n.neg()));return{coef:r.coef.mul(s.coef),fs:[...r.fs,...s.fs]}}const r=n.floor(),s=n.sub(r);if(BigInt(Ql(e.n))*s.n>BigInt(Hl)||s.d>1000n)return{coef:Jl.ONE,fs:[{b:au(e),e:t}]};let i=r.isZero?Jl.ONE:e.pow(r.n);const{outside:o,inside:a}=tu(e.n**s.n,Number(s.d));i=i.mul(new Jl(o));return{coef:i,fs:a>1n?[{b:au(new Jl(a)),e:au(new Jl(1n,s.d))}]:[]}}function qu(e){let t=Jl.ONE;const n=new Map,r=(e,t)=>{const r=mu(e),s=n.get(r);s?s.e=$u([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,lu);if(t.isZero)return uu;const s=[],i=new Map;for(const e of n.values())if(!hu(e.e)||!e.e.q.isZero){if("num"===e.b.k){if(hu(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=ku(e.b.q,e.e);t=t.mul(n.coef),s.push(...n.fs);continue}if("mul"===e.b.k&&hu(e.e)&&e.e.q.isInteger){const n=Mu(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:lu});continue}s.push(e)}for(const{n:e,e:n}of i.values()){const r=ku(new Jl(e),n);t=t.mul(r.coef),s.push(...r.fs)}if(t.isZero)return uu;const o=new Map;for(const e of s){const t=mu(e.b),n=o.get(t);n?n.e=$u([n.e,e.e]):o.set(t,{...e})}let a=[...o.values()].filter(e=>!(hu(e.e)&&e.e.q.isZero));if(ru.complex){a=a.flatMap(e=>{if(!ou(e.b)||!hu(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:lu}]:[]});const e=a.filter(e=>"add"===e.b.k&&hu(e.e)&&e.e.q.isInteger&&Ou(e.b)),n=a.some(e=>ou(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)&&!ou(t.b));let s=n?[Su]:[lu];for(const t of e){const e=t.e.q.sign<0?zu(t.b):t.b;for(let n=0n;n<(t.e.q.sign<0?-t.e.q.n:t.e.q.n);n++)s=Eu(s,Xu(e))}return qu([au(t),$u(s),...r.map(e=>Au(e.b,e.e))])}}if(a.some(e=>"num"===e.b.k&&hu(e.e)&&e.e.q.compare(Jl.ONE)>=0))return qu([au(t),...a.map(e=>"num"===e.b.k?Mu(e.b,e.e):{k:"mul",c:Jl.ONE,fs:[e]})]);if(!a.length)return au(t);if(1===a.length&&!t.isOne&&"add"===a[0].b.k&&hu(a[0].e)&&a[0].e.q.isOne){const e=a[0].b;return $u([au(t.mul(e.c)),...e.terms.map(e=>wu(t.mul(e.coef),e.x))])}return t.isOne&&1===a.length&&hu(a[0].e)&&a[0].e.q.isOne?a[0].b:(a=a.sort((e,t)=>gu(e.b,e.e)-gu(t.b,t.e)||vu(mu(e.b),mu(t.b))),{k:"mul",c:t,fs:a})}function Mu(e,t){if(ru.complex&&hu(t)&&t.q.isInteger){if(ou(e))return qu([{k:"mul",c:Jl.ONE,fs:[{b:e,e:t}]}]);if("add"===e.k&&Ou(e)&&!t.q.isOne)return qu([{k:"mul",c:Jl.ONE,fs:[{b:e,e:t}]}])}if(hu(t)){if(t.q.isZero){if(hu(e)&&e.q.isZero)throw new Vl("0^0 is undefined");return lu}if(t.q.isOne)return e}if(hu(e)){const n=ku(e.q,t);if(!n.fs.length)return au(n.coef);if(n.fs.some(e=>ou(e.b)))return qu([au(n.coef),...n.fs.map(e=>({k:"mul",c:Jl.ONE,fs:[e]}))]);const r={k:"mul",c:n.coef,fs:n.fs};return n.coef.isOne&&1===n.fs.length&&hu(n.fs[0].e)&&n.fs[0].e.q.isOne?n.fs[0].b:r}if(ru.complex&&hu(t)&&2n===t.q.d&&Ou(e)){const n=Iu(e);if(n&&hu(n.im)&&!n.im.q.isZero){const e=e=>Mu(e,au(Jl.of(2))),r=Mu($u([e(n.re),e(n.im)]),cu),s=Mu(qu([$u([r,n.re]),au(Jl.HALF)]),cu),i=Mu(qu([$u([r,Tu(n.re)]),au(Jl.HALF)]),cu);return Mu($u([s,qu([au(Jl.of(n.im.q.sign)),i,Su])]),au(new Jl(t.q.n)))}}if("mul"===e.k){if(hu(t)&&t.q.isInteger)return qu([au(e.c.pow(t.q.n)),...e.fs.map(e=>Au(e.b,qu([e.e,t])))]);if(!e.c.isOne&&e.c.sign>0)return qu([Mu(au(e.c),t),Mu({k:"mul",c:Jl.ONE,fs:e.fs},t)]);if(e.c.isOne&&1===e.fs.length){const[n]=e.fs;if(hu(n.e)&&hu(t)&&1n===n.e.q.n&&n.e.q.d%2n==1n)return Au(n.b,qu([n.e,t]))}}return{k:"mul",c:Jl.ONE,fs:[{b:e,e:t}]}}function Au(e,t){return hu(t)&&t.q.isZero?lu:hu(e)?Mu(e,t):hu(t)&&t.q.isOne?e:{k:"mul",c:Jl.ONE,fs:[{b:e,e:t}]}}const Su=fu(Il("i")),Nu=e=>ru.complex&&Vu(e).s.split(" ").includes("i");function Ou(e){return ru.complex&&Nu(e)&&0===Qu(Vu(e)).size}function Eu(e,t){const n=[];for(const r of e)for(const e of t)n.push(qu([r,e]));return Xu($u(n))}function Iu(e){const t=[],n=[];for(const r of Xu(e)){const{coef:e,rest:s}=xu(r),i=s?Ju(s):[],o=i.filter(e=>ou(e)),a=i.filter(e=>!ou(e));if(a.some(e=>Nu(e)))return null;(o.length?n:t).push(qu([au(e),...a]))}return{re:$u(t),im:$u(n)}}function zu(e){const t=Iu(e);if(!t)return Mu(e,au(Jl.MINUS_ONE));const n=$u([Mu(t.re,au(Jl.of(2))),Mu(t.im,au(Jl.of(2)))]);return qu([$u([t.re,qu([au(Jl.MINUS_ONE),t.im,Su])]),Mu(n,au(Jl.MINUS_ONE))])}const _u={re:([e])=>Iu(e)?.re??null,im:([e])=>Iu(e)?.im??null,conj:([e])=>{const t=Iu(e);return t?$u([t.re,qu([au(Jl.MINUS_ONE),t.im,Su])]):null},arg:([e])=>{const t=Iu(e);return t?Cu("atan2",[t.im,t.re]):null},abs:([e])=>{const t=Iu(e);return!t||hu(t.im)&&t.im.q.isZero?null:Mu($u([Mu(t.re,au(Jl.of(2))),Mu(t.im,au(Jl.of(2)))]),cu)}},ju={Re:"re",re:"re",Im:"im",im:"im",conj:"conj",overline:"conj",bar:"conj",arg:"arg"},Tu=e=>qu([au(Jl.MINUS_ONE),e]),Lu=(e,t)=>qu([e,Mu(t,au(Jl.MINUS_ONE))]),Fu=3000n,Zu={abs:([e])=>hu(e)?au(e.q.abs()):"mul"!==e.k||e.c.isOne?null:qu([au(e.c.abs()),Cu("abs",[xu(e).rest])]),floor:([e])=>hu(e)?au(e.q.floor()):null,ceil:([e])=>hu(e)?au(e.q.ceil()):null,"!":([e])=>{if(!hu(e)||!e.q.isInteger||e.q.sign<0||e.q.n>Fu)return null;let t=1n;for(let n=2n;n<=e.q.n;n++)t*=n;return au(new Jl(t))},mod:([e,t])=>hu(e)&&hu(t)&&!t.q.isZero?au(e.q.sub(t.q.mul(e.q.div(t.q).floor()))):null,max:e=>e.every(hu)&&e.length?e.reduce((e,t)=>t.q.compare(e.q)>0?t:e):null,min:e=>e.every(hu)&&e.length?e.reduce((e,t)=>t.q.compare(e.q)<0?t:e):null,gcd:e=>e.length&&e.every(e=>hu(e)&&e.q.isInteger)?au(new Jl(e.reduce((e,t)=>Xl(e,t.q.n),0n))):null,log:([e,t])=>{if(!hu(e)||!hu(t)||e.q.sign<=0||t.q.sign<=0||e.q.isOne)return null;if(t.q.isOne)return uu;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 au(new Jl(BigInt(s),BigInt(r)))}return null},comb:([e,t])=>hu(e)&&hu(t)&&e.q.isInteger&&t.q.isInteger&&e.q.sign>=0&&t.q.sign>=0&&e.q.n<=Fu?au(function(e,t){if(t>e)return Jl.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 Jl(n)}(e.q.n,t.q.n)):null,perm:([e,t])=>{if(!(hu(e)&&hu(t)&&e.q.isInteger&&t.q.isInteger&&e.q.sign>=0&&t.q.sign>=0&&e.q.n<=Fu))return null;if(t.q.n>e.q.n)return uu;let n=1n;for(let r=0n;r<t.q.n;r++)n*=e.q.n-r;return au(new Jl(n))}};function Cu(e,t){if(ru.complex&&_u[e]){const n=_u[e](t);if(n)return n}const n=Zu[e];if(n){const e=n(t);if(e)return e}return fu(Tl(e,t.map(Vu)))}const Ru=new Map;function Bu(e){const t=ru.complex?`ℂ ${e.s}`:e.s,n=Ru.get(t);if(n)return n;const r=function(e){if("num"===e.type){const t=Yl(e.token);if(!t)throw new Vl(`not an exact number: ${e.token}`);return au(t)}if("sym"===e.type)return"π"===e.token?fu(Il("pi")):fu(e);const t=e.args.map(Bu);switch(e.op){case"+":return $u(t);case"-":return((e,t)=>$u([e,Tu(t)]))(t[0],t[1]);case"neg":return Tu(t[0]);case"*":return qu(t);case"/":return Lu(t[0],t[1]);case"^":return Mu(t[0],t[1]);case"sqrt":return Mu(t[0],cu);case"root":return Mu(t[1],Mu(t[0],au(Jl.MINUS_ONE)));default:{const n=e.op.startsWith("\\:")?e.op.slice(2):null;return n&&ru.complex&&ju[n]&&1===t.length?Cu(ju[n],t):n&&$l(n)&&xl(n).arity===t.length?Cu(n,t):Cu(e.op,t)}}}(e);return Ru.size>2e4&&Ru.clear(),Ru.set(t,r),r}const Pu=e=>Vu(Bu(e)),Du=e=>zl(String(e));function Wu(e){return e.isInteger?Du(e.n):Tl("/",[Du(e.n),Du(e.d)])}const Uu=new WeakMap;function Vu(e){let t=Uu.get(e);return t||Uu.set(e,t=function(e){switch(e.k){case"num":return Wu(e.q);case"atom":return e.node;case"mul":return function(e,t){const n=[],r=[];for(const e of t)hu(e.e)&&e.e.q.sign<0?r.push(Hu(e.b,au(e.e.q.neg()))):n.push(Hu(e.b,e.e));let s=1n!==e.n&&-1n!==e.n||!n.length?Gu([Du(e.n),...n]):Gu(n);-1n===e.n&&n.length&&(s=Tl("neg",[s]));1n!==e.d&&r.unshift(Du(e.d));return r.length?Tl("/",[s,Gu(r)]):s}(e.c,e.fs);case"add":return function(e){let t=null;const n=e=>ru.complex&&Nu(e.x)&&0===Qu(Vu(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?Tl("-",[t,Wu(s.neg())]):Tl("+",[t,Wu(s)]):Wu(s))};let o=!1;for(const e of r)!o&&n(e)&&(i(),o=!0),t=t?e.coef.sign<0?Tl("-",[t,Vu(wu(e.coef.neg(),e.x))]):Tl("+",[t,Vu(wu(e.coef,e.x))]):Vu(wu(e.coef,e.x));o||i();return t}(e);default:throw new Error(`bad form ${e.k}`)}}(e)),t}function Hu(e,t){const n=Vu(e);if(hu(t)){const e=t.q;if(e.isOne)return n;if(1n===e.n&&2n===e.d)return Tl("sqrt",[n]);if(1n===e.n)return Tl("root",[Du(e.d),n])}return Tl("^",[n,Vu(t)])}const Gu=e=>e.reduce((e,t)=>e?Tl("*",[e,t]):t,null);function Qu(e,t=new Set){if("sym"===e.type)iu(e.token)||t.add(e.token);else if(Fl(e))for(const n of e.args)Qu(n,t);return t}function Xu(e){if("add"!==e.k)return[e];const t=e.terms.map(e=>wu(e.coef,e.x));return e.c.isZero||t.push(au(e.c)),t}function Ju(e){if("num"===e.k)return[e];if("mul"!==e.k)return[e];const t=e.c.isOne?[]:[au(e.c)];for(const n of e.fs)t.push(Au(n.b,n.e));return t}const Yu="_",Ku=new WeakMap;function ec(e,t){return[...t,...xl(e.op)?.arity===gl?[String(e.args.length)]:[],e.op].join(" ")}function tc(e,t){let n=Ku.get(e);n||Ku.set(e,n=new Map);const r=n.get(t);if(r)return r;const s=function(e,t){const n={key:Yu,slots:[e]};if(e.type!==Sl||t<=0)return[n];const r=e.args.map(e=>tc(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:ec(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 nc(e){return e.type!==Sl?Yu:ec(e,e.args.map(nc))}function rc(e,t=[]){if(e.type!==Sl)t.push(e);else for(const n of e.args)rc(n,t);return t}const sc=new Map,ic=new Map;class oc extends Error{constructor(e){super(e),this.name="RequirementError"}}function ac(e,t,n=""){sc.set(e,{name:e,fn:t,doc:n,arity:Math.max(0,t.length-1)})}function lc(e,t,n=""){ic.set(e,{name:e,fn:t,doc:n})}function uc(e){return sc.get(e)||null}function cc(e){return ic.get(e)||null}const hc=e=>e.type===Ml;function fc(e,t){return e.type===Sl&&(e.op===t||e.args.some(e=>fc(e,t)))}ac("always",()=>!0,"matches anything"),ac("never",()=>!1,"matches nothing"),ac("isLeaf",e=>e.type!==Sl,"a bare operand, not an operation"),ac("isCompound",e=>e.type===Sl,"an operation, not a bare operand"),ac("isSymbol",e=>e.type===Al,"a non-numeric operand such as x"),ac("isOperation",(e,t)=>e.type===Sl&&e.op===t,"is this specific operation"),ac("notOperation",(e,t)=>!(e.type===Sl&&e.op===t),"is anything except this operation"),ac("isNumber",hc,"a numeric literal"),ac("isInteger",e=>hc(e)&&Number.isInteger(e.value),"a whole number"),ac("isPositive",e=>hc(e)&&e.value>0,"greater than zero"),ac("isNegative",e=>hc(e)&&e.value<0,"less than zero"),ac("isNonNegative",e=>hc(e)&&e.value>=0,"zero or greater"),ac("isZero",e=>hc(e)&&0===e.value,"exactly 0"),ac("isOne",e=>hc(e)&&1===e.value,"exactly 1"),ac("isNonZero",e=>hc(e)&&0!==e.value,"a number that is provably not 0"),ac("isNotZeroLiteral",e=>!(hc(e)&&0===e.value),"anything except a literal 0"),ac("isPositiveInteger",e=>hc(e)&&Number.isInteger(e.value)&&e.value>0,"a whole number above 0"),ac("isNegativeInteger",e=>hc(e)&&Number.isInteger(e.value)&&e.value<0,"a whole number below 0"),ac("isEven",e=>hc(e)&&Number.isInteger(e.value)&&e.value%2==0,"a whole even number"),ac("isOdd",e=>hc(e)&&Number.isInteger(e.value)&&1===Math.abs(e.value%2),"a whole odd number"),ac("greaterThan",(e,t)=>hc(e)&&e.value>Number(t),"above a given value"),ac("lessThan",(e,t)=>hc(e)&&e.value<Number(t),"below a given value"),ac("isValue",(e,t)=>hc(e)&&e.value===Number(t),"equals a given number"),ac("isNumeric",Dl,"contains no symbols: a constant (it need not fold to a number: 1 sin)"),ac("hasSymbol",e=>!Dl(e),"mentions a symbol somewhere, so it is not just a number"),ac("isVar",(e,t)=>e.type===Al&&e.token===String(t),"is exactly this symbol"),ac("contains",(e,t)=>Pl(e).includes(String(t)),"mentions this operand somewhere"),ac("isFree",(e,t)=>!Pl(e).includes(String(t)),"never mentions this operand"),ac("hasOperation",(e,t)=>fc(e,String(t)),"uses this operation somewhere inside"),ac("equals",(e,t)=>e.s===String(t),"is exactly this postfix expression");const pc=e=>e.type===Sl?null:e.token;function mc(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 oc(`bad requirement: ${JSON.stringify(e)}`)}lc("freeOf",(e,t)=>{const n=pc(t);return null!==n&&!Pl(e).includes(n)},"the first operand never mentions the second"),lc("dependsOn",(e,t)=>{const n=pc(t);return null!==n&&Pl(e).includes(n)},"the first operand does mention the second"),lc("sameAs",(...e)=>e.every(t=>t.s===e[0].s),"these operands are structurally identical"),lc("differs",(...e)=>new Set(e.map(e=>e.s)).size===e.length,"these operands are all different"),lc("sameValue",(...e)=>e.every(e=>hc(e))&&e.every(t=>t.value===e[0].value),"these operands are the same number");const dc="simplify";class gc extends Error{constructor(e,t){super(t?`rule "${t}": ${e}`:e),this.name="RuleError",this.ruleId=t}}const vc=/^[A-Za-z_][A-Za-z0-9_]*$/;function bc(e,t){if(Ll(e))return{literal:e.value};const n=e.token;if(n.startsWith("=")){const e=n.slice(1);if(""===e)throw new gc('"=" needs an operand after it',t);return{token:e}}if(!vc.test(n))throw new gc(`"${n}" is not a usable slot name; use letters, digits and _`,t);if($l(n))throw new gc(`slot name "${n}" collides with an operator`,t);return{name:n}}function yc(e){if(!Fl(e))return[e];const t=e.args.map(yc),n=xl(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(Tl(e.op,s)),n.commutative&&2===s.length&&s[0].s!==s[1].s&&r.push(Tl(e.op,[s[1],s[0]])),r.length>=64)break;return r}function wc(e,t=[]){return"op"===e.kind?e.args.forEach(e=>wc(e,t)):"const"===e.kind&&e.free&&t.push(e.node.token),t}function xc(e){if(!e||"object"!=typeof e)throw new gc("rule must be a mapping");const t=e.id||e.name;if(!t)throw new gc("rule needs an id");if(!e.pattern)throw new gc("rule needs a pattern",t);if(void 0===e.output||null===e.output)throw new gc("rule needs an output",t);let n;try{n=Zl(String(e.pattern))}catch(e){if(e instanceof Ol)throw new gc(`bad pattern: ${e.message}`,t);throw e}const r=rc(n).map(e=>bc(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 gc('"when" must map slot names to lists of requirements',n);for(const[e,i]of Object.entries(s)){if(!t.has(e))throw new gc(`"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}=mc(t),o=uc(s);if(!o)throw new gc(`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 gc('"require" must be a list of relations',n);for(const e of s){const{name:s,args:i}=mc(e),o=cc(s);if(!o)throw new gc(`unknown relation "${s}"`,n);if(i.length<2)throw new gc(`relation "${s}" needs at least two operands`,n);for(const e of i)if("string"==typeof e&&!t.has(e)&&vc.test(e))throw new gc(`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=Zl(e)}catch(t){throw new gc(`bad output "${e}": ${t.message}`,n)}const s=e=>Fl(e)?{kind:"op",op:e.op,args:e.args.map(s)}:Ll(e)?{kind:"const",node:e}:t.has(e.token)?{kind:"slot",name:e.token}:e.token.startsWith("=")?{kind:"const",node:Il(e.token.slice(1))}:{kind:"const",node:e,free:!0};return s(r)}(String(e.output),s,t),l=e.commutative?yc(n):[n],u=[],c=new Set;for(const e of l){const n=nc(e),r=rc(e).map(e=>bc(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):dc,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:Rl(n),bindings:u,freeSymbols:wc(a),source:e};for(const e of u)e.rule=h;return h}function $c(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!==dc&&(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 kc extends Error{constructor(e,t){super(null==t?e:`${e} (line ${t+1})`),this.name="YamlError",this.line=t}}class qc{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 Mc=e=>"-"===e||e.startsWith("- ");function Ac(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:Sc(t),rest:e.slice(r+1).trim()}}}return null}function Sc(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 Nc(e){const t=new qc(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=Ec(t,n.indent),s=t.peek();if(s&&"..."!==s.text&&"---"!==s.text)throw new kc(`unexpected content "${s.text}"`,s.n);return r}const Oc=/^[|>][-+]?\d*$/;function Ec(e,t){const n=e.peek();return!n||n.indent<t?null:Mc(n.text)?Ic(e,n.indent):Ac(n.text)?function(e,t){const n={};for(;;){const r=e.peek();if(!r||r.indent!==t)break;const s=Ac(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]=Ec(e,r.indent):r&&r.indent===t&&Mc(r.text)?n[i]=Ic(e,t):n[i]=null}else Oc.test(o)?n[i]=zc(e,o,t):n[i]=_c(o,r.n)}return n}(e,n.indent):(e.next(),Oc.test(n.text)?zc(e,n.text,n.indent-1):_c(n.text,n.n))}function Ic(e,t){const n=[];for(;;){const r=e.peek();if(!r||r.indent!==t||!Mc(r.text))break;if(e.next(),"-"===r.text){const r=e.peek();n.push(r&&r.indent>t?Ec(e,r.indent):null);continue}if(Oc.test(r.text.slice(2).trim())){n.push(zc(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(Ec(e,i))}return n}function zc(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 _c(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=Tc(n);if(jc(n),n.i<n.text.length)throw new kc(`unexpected "${n.text.slice(n.i)}" in flow value`,t);return r}(n,t):'"'===n[0]||"'"===n[0]?Sc(n):/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(n)?Number(n):n)}const jc=e=>{for(;e.i<e.text.length&&/\s/.test(e.text[e.i]);)e.i++};function Tc(e){jc(e);const t=e.text[e.i];return"["===t?function(e){e.i++;const t=[];for(;;){if(jc(e),e.i>=e.text.length)throw new kc("unterminated [",e.line);if("]"===e.text[e.i])return e.i++,t;if(t.push(Tc(e)),jc(e),","===e.text[e.i])e.i++;else if("]"!==e.text[e.i])throw new kc(`expected , or ] near "${e.text.slice(e.i)}"`,e.line)}}(e):"{"===t?function(e){e.i++;const t={};for(;;){if(jc(e),e.i>=e.text.length)throw new kc("unterminated {",e.line);if("}"===e.text[e.i])return e.i++,t;const n=String(Tc(e));if(jc(e),":"!==e.text[e.i])throw new kc(`expected : after "${n}"`,e.line);if(e.i++,t[n]=Tc(e),jc(e),","===e.text[e.i])e.i++;else if("}"!==e.text[e.i])throw new kc(`expected , or } near "${e.text.slice(e.i)}"`,e.line)}}(e):_c(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 kc("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 Lc=/^(true|false|null|yes|no|on|off|~)$/i;function Fc(e){if(null==e)return"null";if("boolean"==typeof e)return e?"true":"false";if("number"==typeof e){if(!Number.isFinite(e))throw new kc(`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)||Lc.test(e)||/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(e))}(t)?JSON.stringify(t):t}const Zc=e=>null==e||"object"!=typeof e;function Cc(e){return Array.isArray(e)?`[${e.map(Cc).join(", ")}]`:e&&"object"==typeof e?`{${Object.entries(e).map(([e,t])=>`${Fc(e)}: ${Cc(t)}`).join(", ")}}`:Fc(e)}function Rc(e){return Array.isArray(e)?!!e.every(e=>Zc(e)||Array.isArray(e)&&e.every(Zc))&&Cc(e).length<=72:!(!e||"object"!=typeof e)&&(Object.values(e).every(e=>Zc(e)||Array.isArray(e)&&e.every(Zc))&&Cc(e).length<=72)}function Bc(e){const t=[];return Pc(e,0,t),t.length?t.join("\n")+"\n":""}function Pc(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)Dc(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)Wc(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+Fc(e))}(e,r,n)}}function Dc(e,t,n){const r=" ".repeat(t);if(null!==e&&"object"==typeof e&&!Rc(e)){const s=[];if(Pc(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+"- "+Fc(e));else n.push(r+"- "+Cc(e))}function Wc(e,t,n,r){const s=" ".repeat(n),i=Fc(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 Rc(t)?void r.push(`${s}${i}: ${Cc(t)}`):(r.push(`${s}${i}:`),void Pc(t,Array.isArray(t)?n:n+2,r));r.push(`${s}${i}: ${Fc(t)}`)}}class Uc{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:xc(e);if(this.rules.some(e=>e.id===t.id))throw new gc(`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 Uc(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===dc?-1:t===dc?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=Nc(e);return Uc.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 gc('expected a list of rules, or a mapping with a "rules" list');const s=new Uc;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 gc(`${i.length} rule(s) failed to compile:\n ${i.join("\n ")}`);return s.errors=i,s}toSpecs(){return this.rules.map($c)}toYaml(){const e=this.toSpecs();return this.name?Bc({name:this.name,rules:e}):Bc(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 Vc(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(!Ll(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 Hc(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 Gc(e,t){return t.rule.priority-e.rule.priority||t.rule.depth-e.rule.depth}function Qc(e,t){const n=[];if(0===t.maxDepth)return n;for(const{key:r,slots:s}of function(e,t){const n=tc(e,t),r=[];for(const e of n)e.key!==Yu&&r.push(e);return r}(e,t.maxDepth)){const e=t.candidates(r);if(e)for(const t of e){const e=Vc(t,s);e&&(Hc(t.rule,e)&&n.push({rule:t.rule,binding:t,key:r,bound:e}))}}return n.sort(Gc)}function Xc(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 Tl(e.op,e.args.map(e=>Xc(e,t)));default:throw new Error(`bad output template: ${JSON.stringify(e)}`)}}const Jc=4e5,Yc=()=>new Vl("a number too large to approximate"),Kc=e=>e<0n?-e:e;class eh{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 Vl("division by zero");return e*this.S/t}sqrt(e){if(e<0n)throw new Vl("the square root of a negative number is not real");return Kl(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 Vl("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(Jc))throw Yc();if(t<-BigInt(Jc))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 Vl("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(Kc(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(Kc(e)>this.S)throw new Vl("arcsin of a number beyond ±1 is not real");return Kc(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 th(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 Vl("the argument of 0 is undefined");return t>0n?e.pi/2n:-e.pi/2n}const nh={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 Vl("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=nh.abs(e,t);if(0n===n)throw new Vl("the log of 0 is undefined");return[e.ln(n),th(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=nh.mul(e,s,i)),i=nh.mul(e,i,i),n>>=1n;return r.n<0n?nh.div(e,[e.S,0n],s):s}return nh.exp(e,nh.mul(e,n,nh.ln(e,t)))},sinh:(e,t)=>(e.exp(t)-e.exp(-t))/2n,cosh:(e,t)=>(e.exp(t)+e.exp(-t))/2n},rh={sin:(e,[t,n])=>[e.mul(e.sin(t),nh.cosh(e,n)),e.mul(e.cos(t),nh.sinh(e,n))],cos:(e,[t,n])=>[e.mul(e.cos(t),nh.cosh(e,n)),-e.mul(e.sin(t),nh.sinh(e,n))],tan:(e,t)=>nh.div(e,rh.sin(e,t),rh.cos(e,t)),ln:(e,t)=>nh.ln(e,t),sqrt:(e,t)=>nh.exp(e,nh.mul(e,[e.S/2n,0n],nh.ln(e,t))),sinh:(e,[t,n])=>[e.mul(nh.sinh(e,t),e.cos(n)),e.mul(nh.cosh(e,t),e.sin(n))],cosh:(e,[t,n])=>[e.mul(nh.cosh(e,t),e.cos(n)),e.mul(nh.sinh(e,t),e.sin(n))]},sh=e=>({q:e}),ih=([e,t])=>0n===t?{f:e}:{z:[e,t]};function oh(e,t,n){const r=e=>((e,t)=>t.z??[ah(e,t),0n])(n,t[e]);switch(e.op){case"+":return ih(nh.add(r(0),r(1)));case"-":return ih(nh.sub(r(0),r(1)));case"neg":return ih([-r(0)[0],-r(0)[1]]);case"*":return ih(nh.mul(n,r(0),r(1)));case"/":return ih(nh.div(n,r(0),r(1)));case"^":return ih(nh.pow(n,r(0),r(1),t[1].q));case"sqrt":return ih(rh.sqrt(n,r(0)));case"root":return ih(nh.pow(n,r(1),nh.div(n,[n.S,0n],r(0)),t[0].q?.inv()));case"abs":return{f:nh.abs(n,r(0))};case"arg":return{f:th(n,r(0)[1],r(0)[0])};case"re":return{f:r(0)[0]};case"im":return{f:r(0)[1]};case"conj":return ih([r(0)[0],-r(0)[1]]);case"log":return ih(nh.div(n,nh.ln(n,r(1)),nh.ln(n,r(0))));default:{const s=rh[e.op];if(!s||1!==t.length)throw new Vl(`no complex value for ${e.op}`);return ih(s(n,r(0)))}}}function ah(e,t){return t.q?e.fromQ(t.q):t.f}const lh={sin:(e,t)=>e.sin(t),cos:(e,t)=>e.cos(t),tan:(e,t)=>e.div(e.sin(t),e.cos(t)),sec:(e,t)=>e.div(e.S,e.cos(t)),csc:(e,t)=>e.div(e.S,e.sin(t)),cot:(e,t)=>e.div(e.cos(t),e.sin(t)),arcsin:(e,t)=>e.asin(t),arccos:(e,t)=>e.pi/2n-e.asin(t),arctan:(e,t)=>e.atan(t),arcsec:(e,t)=>{if(Kc(t)<e.S)throw new Vl("arcsec of a number between -1 and 1 is not real");return e.pi/2n-e.asin(e.div(e.S,t))},arccsc:(e,t)=>{if(Kc(t)<e.S)throw new Vl("arccsc of a number between -1 and 1 is not real");return e.asin(e.div(e.S,t))},arccot:(e,t)=>e.pi/2n-e.atan(t),sinh:(e,t)=>(e.exp(t)-e.exp(-t))/2n,cosh:(e,t)=>(e.exp(t)+e.exp(-t))/2n,tanh:(e,t)=>{const n=e.exp(t),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 Vl("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(Kc(t)>=e.S)throw new Vl("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 uh(e,t,n){if("num"===e.type)return sh(Yl(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&&ru.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?Yl(String(t)):null;if(!r)throw new Vl(`the value of ${e.token} is not a number`);return sh(r)}throw new Vl(`${e.token} has no value`)}ru.complex&&e.op.startsWith("\\:")&&ju[e.op.slice(2)]&&(e=Tl(ju[e.op.slice(2)],e.args));const r=e.args.map(e=>uh(e,t,n));if(r.some(e=>e.z)||["re","im","conj","arg"].includes(e.op)||function(e,t){if(!ru.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 oh(e,r,t);const s=r.every(e=>e.q),i=e=>ah(t,r[e]);switch(e.op){case"+":return s?sh(r[0].q.add(r[1].q)):{f:i(0)+i(1)};case"-":return s?sh(r[0].q.sub(r[1].q)):{f:i(0)-i(1)};case"neg":return r[0].q?sh(r[0].q.neg()):{f:-r[0].f};case"*":return s?sh(r[0].q.mul(r[1].q)):{f:t.mul(i(0),i(1))};case"/":return s?sh(r[0].q.div(r[1].q)):{f:t.div(i(0),i(1))};case"^":return hh(t,r[0],r[1]);case"sqrt":return hh(t,r[0],sh(Jl.HALF));case"root":return hh(t,r[1],r[0].q?sh(r[0].q.inv()):{f:t.div(t.S,r[0].f)});case"abs":return r[0].q?sh(r[0].q.abs()):{f:Kc(r[0].f)};case"floor":return sh(r[0].q?r[0].q.floor():new Jl(ch(r[0].f,t.S)));case"ceil":return sh(r[0].q?r[0].q.ceil():new Jl(-ch(-r[0].f,t.S)));case"log":return{f:t.div(t.ln(i(1)),t.ln(i(0)))};case"atan2":return{f:th(t,i(0),i(1))};case"max":case"min":if(!r.length)throw new Vl(`${e.op} of nothing`);return s?sh(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?sh(r.reduce((e,t)=>e.add(t.q),Jl.ZERO)):{f:r.reduce((e,t,n)=>e+i(n),0n)};case"prod":return s?sh(r.reduce((e,t)=>e.mul(t.q),Jl.ONE)):{f:r.reduce((e,n,r)=>t.mul(e,i(r)),t.S)};case"mean":if(!r.length)throw new Vl("mean of nothing");return s?sh(r.reduce((e,t)=>e.add(t.q),Jl.ZERO).div(new Jl(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 Vl("mod 0 is undefined");return sh(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 Vl("mod 0 is undefined");return{f:i(0)-t.mul(e,ch(t.div(i(0),e),t.S)*t.S)}}case"round":{if(!r[1].q?.isInteger)throw new Vl("round needs a whole number of places");const e=10n**Kc(r[1].q.n),n=r[0].q??new Jl(i(0),t.S),s=r[1].q.sign>=0,o=(s?n.mul(new Jl(e)):n.div(new Jl(e))).add(Jl.HALF).floor();return sh(s?o.div(new Jl(e)):o.mul(new Jl(e)))}case"!":{if(!r[0].q?.isInteger||r[0].q.sign<0)throw new Vl("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)&&Ql(e)>Jc)throw Yc();return sh(new Jl(e))}default:{const n=lh[e.op];if(!n||1!==r.length)throw new Vl(`no numeric value for ${e.op}`);return{f:n(t,i(0))}}}}const ch=(e,t)=>{const n=e/t;return e<0n&&n*t!==e?n-1n:n};function hh(e,t,n){if(n.q&&n.q.isInteger){if(t.q)return sh(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),Ql(i)>Jc+4*e.P||Ql(o)>8e5){if(s)return{f:0n};throw Yc()}r>>=1n}return{f:s?e.div(e.S,i):i}}const r=ah(e,t);if(0n===r){if(n.q?n.q.sign>0:n.f>0n)return sh(Jl.ZERO);throw new Vl("0 to a power that is not positive is undefined")}if(r<0n){if(n.q&&n.q.d%2n==1n){const t=hh(e,{f:-r},n).f;return{f:n.q.n%2n==0n?t:-t}}throw new Vl("a negative number to a fractional power is not real")}if(n.q&&1n===Kc(n.q.n)&&n.q.d<=64n){const t=Kl(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(ah(e,n),e.ln(r)))}}function fh(e,t,n){const r=e<0n?"-":"",s=Kc(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 ph({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 mh(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=Kc(e.n)*10n**s/e.d;if(0n===i)return 1;for(;i%10n==0n;)i/=10n;return i.toString().length}function dh(e){let t=e.d;for(;t%2n==0n;)t/=2n;for(;t%5n==0n;)t/=5n;return 1n===t}function gh(e){const t=/^(-?[\d.]+)e(-?\d+)$/.exec(e);return t?Tl("*",[zl(t[1]),Tl("^",[zl("10"),zl(t[2])])]):zl(e)}function vh(e,{digits:t=15,scope:n}={}){if(!Number.isInteger(t)||t<1||t>1e5)throw new Vl("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 eh(r),a=uh(e,o,n);if(a.z){const e=yh(a.z,o,t);if(e.retry&&i<3){r+=e.retry;continue}return void 0===e.real?e:bh(e.real,o,t,null)}if(a.q&&a.q.isInteger&&Kc(a.q.n).toString().length<=t)return{text:a.q.n.toString(),node:zl(a.q.n.toString()),number:Number(a.q.n),re:Number(a.q.n),im:0,exact:!0};const l=ah(o,a);if(0n===l&&(!a.q||!a.q.isZero)&&i<3){s=null,r*=4;continue}const u=fh(l,o,t);if(s&&u.point<-10&&s.point-u.point>=(r-s.P)/2)return{text:"0",node:zl("0"),number:0,re:0,im:0,exact:!1};if(!(u.point<-10&&i<3)||s&&s.point===u.point)return bh(l,o,t,a.q);s={point:u.point,P:r},r+=10-u.point}throw new Vl("could not approximate")}function bh(e,t,n,r){const s=ph(fh(e,t,n));return{text:s,node:gh(s),number:Number(s),re:Number(s),im:0,exact:Boolean(r)&&dh(r)&&mh(r)<=n}}function yh([e,t],n,r){const s=10n**BigInt(Math.max(0,n.P-r-12)),i=e=>Kc(e)>s;if(!i(t))return{real:e};const o=fh(t,n,r);if(o.point<-10&&i(t))return{retry:10-o.point};const a=ph(o),l="1"===a?"i":"-1"===a?"-i":`${a}i`,u="1"===a?Il("i"):Tl("*",[gh(a.replace(/^-/,"")),Il("i")]);if(!i(e))return{text:l,node:a.startsWith("-")?Tl("neg",[u]):u,number:NaN,re:0,im:Number(a),exact:!1};const c=ph(fh(e,n,r)),h=a.startsWith("-"),f="1"===a.replace(/^-/,"")?Il("i"):Tl("*",[gh(a.replace(/^-/,"")),Il("i")]);return{text:`${c} ${h?"-":"+"} ${l.replace(/^-/,"")}`,node:Tl(h?"-":"+",[gh(c),f]),number:NaN,re:Number(c),im:Number(a),exact:!1}}function wh(e,t={}){const n=e=>(e=>0===Qu(e).size)(e)?"num"===e.type&&/^-?\d+$/.test(e.token)?e:vh(e,t).node:Fl(e)?Tl(e.op,e.args.map(n)):e;return n(e)}const xh={variable:null},$h=(e,t)=>null!==t&&Qu(e).has(t);function kh(e){if("num"===e.type)return Yl(e.token);if(Fl(e)&&"/"===e.op&&e.args.every(e=>"num"===e.type)){const t=Yl(e.args[0].token),n=Yl(e.args[1].token);return t&&n&&!n.isZero?t.div(n):null}return null}const qh=e=>0===Qu(e).size;function Mh(e,t,n){const r=function(e){const t=Bu(e);return"num"===t.k?t.q.isZero?t.q:null:"atom"===t.k&&"sym"===t.node.type&&"pi"===t.node.token?Yl("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(Yl(s).div(Yl(i))))}function Ah(e){if(!qh(e))return NaN;try{const{number:t}=vh(e,{digits:30});return Math.sign(t)}catch{return NaN}}function Sh(){uc("hasVariable")||(ac("hasVariable",e=>$h(e,xh.variable),"mentions the variable being solved for"),ac("freeOfVariable",e=>null!==xh.variable&&!$h(e,xh.variable),"does not mention the variable being solved for"),ac("isRational",e=>null!==kh(e),"an exact number: 3, -2, 1/2"),ac("isWhole",e=>kh(e)?.isInteger??!1,"a whole number (any size)"),ac("isEvenWhole",e=>{const t=kh(e);return Boolean(t?.isInteger&&t.n%2n==0n)},"an even whole number"),ac("isOddWhole",e=>{const t=kh(e);return Boolean(t?.isInteger&&t.n%2n!=0n)},"an odd whole number"),ac("isPositiveRational",e=>(kh(e)?.sign??0)>0,"an exact number above 0"),ac("isNegativeRational",e=>(kh(e)?.sign??0)<0,"an exact number below 0"),ac("isConstant",qh,"has no unknowns (numbers, π and e only)"),ac("notOne",e=>{const t=kh(e);return!t||!t.isOne},"anything except the number 1"),ac("notMinusOne",e=>{const t=kh(e);return!t||!t.equals(Yl("-1"))},"anything except the number -1"),ac("hasMinusSign",e=>function(e){const t=Bu(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"),ac("piMultipleAtLeast",(e,t)=>Mh(e,t,e=>e>=0),"a multiple of π, at least k·π"),ac("piMultipleAbove",(e,t)=>Mh(e,t,e=>e>0),"a multiple of π, above k·π"),ac("piMultipleBelow",(e,t)=>Mh(e,t,e=>e<0),"a multiple of π, below k·π"),ac("piMultipleAtMost",(e,t)=>Mh(e,t,e=>e<=0),"a multiple of π, at most k·π"),ac("isPositiveConstant",e=>Ah(e)>0,"no unknowns, and above 0 (e, π, √2, 3)"),ac("isNegativeConstant",e=>Ah(e)<0,"no unknowns, and below 0"),ac("hasImaginaryPart",e=>{if(!ru.complex)return!1;const t=Iu(Bu(e));return Boolean(t)&&!("num"===t.im.k&&t.im.q.isZero)},"complex mode: has a nonzero imaginary part (unknowns count as real)"),ac("isSymbolNode",e=>"sym"===e.type&&!nu.has(e.token),"a single unknown such as x"))}function Nh(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=Zl(e),n=e=>"num"===e.type||("sym"===e.type?e.token.startsWith("="):e.args.every(n)),r=e=>"sym"===e.type?Il(e.token.slice(1)):"num"===e.type?e:Tl(e.op,e.args.map(r)),s=e=>"sym"===e.type?Il(`=${e.token}`):"num"===e.type?e:Tl(e.op,e.args.map(s)),i=e=>"op"!==e.type?e:n(e)?s(Pu(r(e))):Tl(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 Uc.fromSpecs(n,{strict:!0})}function Oh(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 Eh=e=>Fl(e)&&("+"===e.op||"-"===e.op),Ih=e=>Fl(e)&&("*"===e.op||"/"===e.op);function*zh(e,t,{order:n="pre"}={}){for(const r of function(e,t,{order:n="post"}={}){const r=[];for(const{node:s,path:i}of Wl(e,n))for(const e of Qc(s,t))r.push({...e,node:s,path:i});return r}(e,t,{order:n})){const t=Xc(r.rule.outputTemplate,r.bound);yield{rule:r.rule,bound:r.bound,path:r.path,before:r.node,after:t,next:()=>Pu(Ul(e,r.path,t))}}for(const{node:r,path:s}of Wl(e,n)){const n=Eh(r);if(!n&&!Ih(r))continue;const i=n?Xu(Bu(r)):Ju(Bu(r));if(i.length<3)continue;const o=n?$u:qu;for(let n=0;n<i.length;n++)for(let r=n+1;r<i.length;r++){const a=Vu(o([i[n],i[r]]));for(const l of Qc(a,t)){const t=Xc(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:()=>Pu(Ul(e,s,Vu(o([Bu(t),...u]))))}}}}}function _h(e,t,{format:n,order:r="pre",maxSteps:s=200,variable:i=null}={}){const o=xh.variable;xh.variable=i;try{let i=Pu(e);const o=new Set([i.s]),a=[];for(let e=0;e<s;e++){let e=null;for(const n of zh(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:Oh(s.rule,s.bound,Pu(s.after),n)}),i=l,o.add(i.s)}return{node:i,steps:a}}finally{xh.variable=o}}const jh={full:[],normal:["hidden"],brief:["hidden","tidy","identity","value","split","base","arithmetic"]},Th=(e,t)=>"all"===t||"*"===t||Array.isArray(t)&&t.some(t=>t===e.id||e.tags?.includes(t));function Lh(e){if(!1===e)return null;if(void 0===e||!0===e)return{show:"all",hide:jh.normal,explain:!0};if("string"==typeof e){if(!jh[e])throw new Error(`steps: "${e}" is not one of ${Object.keys(jh).join(", ")}`);return{show:"all",hide:jh[e],explain:!0}}const t=e.detail??"normal";if(!jh[t])throw new Error(`steps.detail: "${t}" is not one of ${Object.keys(jh).join(", ")}`);return{show:e.show??"all",hide:[...jh[t],...e.hide??[]],explain:e.explain??!0}}function Fh(e,t){if(!t)return[];e=function(e){const t=[];for(const n of e){const e=t[t.length-1];if(!("d-variable"===n.id&&e&&/^(\S+) \1 der$/.test(n.before??"")&&` ${e.after??""} `.includes(` ${n.before} `))){t.push(n);continue}const r={...e,to:n.to};if(e.after&&(r.after=` ${e.after} `.replace(` ${n.before} `," 1 ").replace(/ 1 \*(?= )/g,"").trim()),e.explanation){const t=n.before.split(" ")[0];r.explanation=e.explanation.endsWith(`the derivative of ${t}.`)?`${e.explanation.slice(0,-1)}, which is 1.`:`${e.explanation} The derivative of ${t} is 1.`}t[t.length-1]=r}return t}(e);const n=[];let r=null;for(const s of e){if(!(Th(s,t.show)&&!Th(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&&Th(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 Zh=au(Jl.ONE),Ch=(e,t)=>"atom"===e.k&&"sym"===e.node.type&&e.node.token===t;function Rh(e){switch(e.k){case"num":default:return e;case"atom":return"op"===e.node.type?Cu(e.node.op,e.node.args.map(e=>Rh(Bu(e)))):e;case"add":return $u(Xu(e).map(Rh));case"mul":{let t=[au(e.c)];for(const n of e.fs){const e=Rh(n.b);if("add"===e.k&&hu(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=Bh(t,Xu(e));else t=Bh(t,[Au(e,n.e)])}return $u(t)}}}function Bh(e,t){const n=[];for(const r of e)for(const e of t)n.push(qu([r,e]));return Xu($u(n))}function Ph(e,t){const n=new Map;for(const r of Xu(Rh(e))){const{coef:e,rest:s}=xu(r);let i=0;const o=[au(e)];for(const e of s?Ju(s):[]){const{b:n,e:r}="mul"===e.k&&1===e.fs.length&&e.c.isOne?e.fs[0]:{b:e,e:Zh};if(Ch(n,t)){if(!hu(r)||!r.q.isInteger||r.q.sign<0)return null;i+=Number(r.q.n)}else{if(Dh(n,t)||Dh(r,t))return null;o.push(e)}}n.set(i,$u([n.get(i)??au(Jl.ZERO),qu(o)]))}for(const[e,t]of n)hu(t)&&t.q.isZero&&n.delete(e);return n}const Dh=(e,t)=>Qu(Vu(e)).has(t);function Wh(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)??au(Jl.ZERO);if(!hu(t))return null;n.push(t.q)}return n}function Uh(e,t){const n=Bu(Il(t));return $u(e.map((e,t)=>qu([au(e),Mu(n,au(Jl.of(t)))])))}const Vh=e=>{const t=e.slice();for(;t.length>1&&t[t.length-1].isZero;)t.pop();return t},Hh=(e,t)=>e.reduceRight((e,n)=>e.mul(t).add(n),Jl.ZERO);function Gh(e,t){const n=e.length-1,r=new Array(n);let s=Jl.ZERO;for(let i=n;i>=1;i--)s=e[i].add(s.mul(t)),r[i-1]=s;return r}function Qh(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 Xh(e){let t=Vh(e);const n=[];for(;t.length>1&&t[0].isZero;)n.push(Jl.ZERO),t=t.slice(1);if(t.length<=1)return{roots:n,rest:t};const r=t.reduce((e,t)=>e*t.d/Xl(e,t.d),1n),s=t.map(e=>e.n*r/e.d),i=Qh(s[0]),o=Qh(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 Jl(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&&Hh(t,e).isZero;)n.push(e),t=Gh(t,e);return{roots:n.sort((e,t)=>e.compare(t)),rest:t}}function Jh(e,t){const n=Vh(t);let r=Vh(e);const s=n[n.length-1];if(s.isZero)throw new Vl("division by the zero polynomial");const i=new Array(Math.max(1,r.length-n.length+1)).fill(Jl.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=Vh(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:Vh(i),r:r}}function Yh(e){if("num"===e.k)return{coef:e.q,factors:[],notes:[]};if("atom"===e.k)return{coef:Jl.ONE,factors:[{base:e,exp:Zh}],notes:[]};if("mul"===e.k){let t=e.c;const n=[],r=[];for(const s of e.fs)if("add"===s.b.k&&hu(s.e)&&s.e.q.isInteger){const e=Yh(s.b);t=t.mul(e.coef.pow(s.e.q.n));for(const t of e.factors)n.push({base:t.base,exp:qu([t.exp,s.e])});r.push(...e.notes)}else n.push({base:s.b,exp:s.e});return Kh(t,n,r)}return function(e){const t=Xu(e),n=[],r=t.map(e=>{const{coef:t,rest:n}=xu(e);return{coef:t,fs:n?Ju(n).map(tf):[]}}),s=r.reduce((e,t)=>({n:Xl(e.n,t.coef.n),d:e.d*t.coef.d/Xl(e.d,t.coef.d)}),{n:0n,d:1n});let i=new Jl(s.n||1n,s.d);ef(e)<0&&(i=i.neg());const o=[];for(const e of r[0].fs){if(!hu(e.e)||e.e.q.sign<=0)continue;let t=e.e.q;const n=mu(e.b);let s=!0;for(const e of r.slice(1)){const r=e.fs.find(e=>mu(e.b)===n&&hu(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:au(t)})}let a=e;if(!i.isOne||o.length){const e=qu([au(i),...o.map(e=>Au(e.base,e.exp))]);a=$u(t.map(t=>qu([t,Mu(e,au(Jl.MINUS_ONE))]))),n.push({id:"factor.common",values:{common:e}})}const l="add"===a.k?function(e,t){const n=[...nf(e)];for(const r of n){const s=Wh(Ph(e,r));if(!s||s.length<3)continue;if(1!==n.length)break;const{roots:i,rest:o}=Xh(s);if(!i.length)break;const a=[];let l=o[o.length-1]??Jl.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=Uh([new Jl(-e.n),new Jl(e.d)],r);a.push({base:n,exp:Zh}),l=l.div(new Jl(e.d)),t.push({id:"factor.root",values:{root:au(e),factor:n}})}if(u.length>1){const e=u.reduce((e,t)=>e*t.d/Xl(e,t.d),1n),t=u.map(t=>t.mul(new Jl(e))),n=t.reduce((e,t)=>Xl(e,t.n),0n)||1n;l=l.mul(new Jl(n,e)),a.push({base:Uh(t.map(e=>e.div(new Jl(n))),r),exp:Zh})}return Kh(l,a,[])}const r=Xu(e);if(2===r.length){const[e,n]=r;for(const r of[2,3]){const s=rf(e,r),i=rf(Tu(n),r),o=3===r?rf(n,r):null;if(s&&i&&2===r){t.push({id:"factor.squares",values:{a:s,b:i}});const e=Yh($u([s,Tu(i)])),n=Yh($u([s,i]));return Kh(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=$u(n<0?[s,Tu(e)]:[s,e]),a=$u([Mu(s,au(Jl.of(2))),n<0?qu([s,e]):Tu(qu([s,e])),Mu(e,au(Jl.of(2)))]),l=Yh(r);return Kh(l.coef,[...l.factors,{base:a,exp:Zh}],l.notes)}}}return{coef:Jl.ONE,factors:[{base:e,exp:Zh}],notes:[]}}(a,n):Yh(a);return Kh(i.mul(l.coef),[...o,...l.factors],[...n,...l.notes.filter(e=>!n.includes(e))])}(e)}function Kh(e,t,n){const r=new Map;for(const e of t){const t=mu(e.base),n=r.get(t);n?n.exp=$u([n.exp,e.exp]):r.set(t,{...e})}return{coef:e,factors:[...r.values()].filter(e=>!(hu(e.exp)&&e.exp.q.isZero)),notes:n}}const ef=e=>xu(Xu(e)[0]).coef.sign;const tf=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length?{b:e.fs[0].b,e:e.fs[0].e}:{b:e,e:Zh},nf=e=>Qu(Vu(e));function rf(e,t){const{coef:n,rest:r}=xu(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 Jl(r,s):null}(n,t);if(!s)return null;const i=[au(s)];for(const e of r?Ju(r).map(tf):[]){if(!hu(e.e))return null;const n=e.e.q.div(Jl.of(t));if(!n.isInteger)return null;i.push(Au(e.b,au(n)))}return qu(i)}function sf({coef:e,factors:t}){const n=[],r=[];for(const e of t){const t=hu(e.exp)&&e.exp.q.sign<0,s=t?au(e.exp.q.neg()):e.exp,i=Vu(Au(e.base,s));(t?r:n).push(i)}const s=e=>e.reduce((e,t)=>e?Tl("*",[e,t]):t,null),i=e.n<0n?-e.n:e.n;let o=n.length?s(1n===i?n:[Vu(au(new Jl(i))),...n]):Vu(au(new Jl(i)));return e.n<0n&&(o=Tl("neg",[o])),1n!==e.d&&r.unshift(Vu(au(new Jl(e.d)))),r.length?Tl("/",[o,s(r)]):o}function of(e){if("mul"!==e.k)return{num:e,den:Zh};const t=[au(new Jl(e.c.n))],n=[au(new Jl(e.c.d))];for(const r of e.fs)hu(r.e)&&r.e.q.sign<0?n.push(Au(r.b,au(r.e.q.neg()))):t.push(Au(r.b,r.e));return{num:qu(t),den:qu(n)}}function af(e){if("add"!==e.k)return of(e);const t=Xu(e).map(of),n=new Map;let r=1n;for(const e of t){const{coef:t,rest:s}=xu(e.den);r=r*t.n/Xl(r,t.n);for(const e of s?Ju(s).map(tf):[]){const t=mu(e.b),r=n.get(t);(!r||hu(e.e)&&hu(r.e)&&e.e.q.compare(r.e.q)>0)&&n.set(t,e)}}const s=qu([au(new Jl(r)),...[...n.values()].map(e=>Au(e.b,e.e))]);if(hu(s)&&s.q.isOne)return{num:e,den:Zh};const i=Rh($u(t.map(e=>qu([e.num,s,Mu(e.den,au(Jl.MINUS_ONE))]))));return{num:i,den:s}}function lf(e){const{num:t,den:n}=af(e);if(hu(n)&&n.q.isOne)return null;const r=Yh(t),s=Yh(n),i=new Set(r.factors.map(e=>mu(e.base))),o=s.factors.filter(e=>i.has(mu(e.base))),a=[...r.factors,...s.factors.map(e=>({base:e.base,exp:Tu(e.exp)}))];return{...Kh(r.coef.div(s.coef),a,[...r.notes,...s.notes]),canceled:o.map(e=>e.base)}}const uf=(e,t)=>Tl("=",[e,t]),cf=Pu(Tl("+",[Il("x"),Tl("neg",[Il("x")])])),hf=e=>Fl(e)&&"="===e.op;function ff(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=hf(t)?t:uf(t,cf),a=uf(Pu(o.args[0]),Pu(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,bf(e,a,n,r,i,l,u,0);const h=[],f=new Set;for(const t of l.map(t=>c.has(t)?t:(t=>_h(t,e.set.view("simplify"),{format:e.format}).node)(t))){const e=t.s;if(f.has(e))continue;f.add(e);const r=c.has(t)?null:df(o,n,t);r?i("solve.reject","Check the answer",["check"],uf(Il(n),t),uf(Il(n),t),{value:t,reason:r}):h.push(t)}return h.sort(pf),{solutions:h,unsolved:u,steps:s,always:u.some(e=>e.always)}}function pf(e,t){const n=mf(e),r=mf(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 mf(e){if(Qu(e).size)return null;try{const{re:t,im:n}=vh(e,{digits:20});return{re:t,im:n}}catch{return null}}function df(e,t,n){const[r,s]=e.args,i=new Set([...Qu(r),...Qu(s),...Qu(n)]);if(i.delete(t),i.size)return null;const o=e=>gf(e,t,n);try{const e=vh(o(r),{digits:40}),t=vh(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 gf(e,t,n){return"sym"===e.type?e.token===t?n:e:Fl(e)?Tl(e.op,e.args.map(e=>gf(e,t,n))):e}const vf=24;function bf(e,t,n,r,s,i,o,a){if(a>vf)return Mf(e,t,n,r,s,i,o);const l=function(e){const t=[],n=e=>{if(Fl(e)&&"|"===e.op)return void e.args.forEach(n);if(!hf(e))return void t.push(e);const r=e.args[1],s=Wl(r,"pre").find(({node:e})=>Fl(e)&&"pm"===e.op);if(!s)return void t.push(e);const i=s.node.args[0],o=Pu(Ul(r,s.path,i)),a=Pu(Ul(r,s.path,Tl("neg",[i])));n(uf(e.args[0],o)),a.s!==o.s&&n(uf(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?Tl("|",[e,t]):t,null));for(const t of l)bf(e,t,n,r,s,i,o,a+1);return}if(1===l.length&&l[0].s!==t.s)return bf(e,l[0],n,r,s,i,o,a+1);const[u,c]=t.args;if("sym"===u.type&&u.token===n&&!Dh(Bu(c),n))return void i.push(c);const h=$u([Bu(u),Tu(Bu(c))]);if(!Dh(h,n))return hu(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 f=Xu(h).filter(e=>Dh(e,n)),p=Xu(h).filter(e=>!Dh(e,n)),m=$u(f),d=Tu($u(p));if(ru.complex){const l=Ph(h,n);if(l&&[...l.values()].every(e=>!Dh(e,n))&&Math.max(...l.keys())>=2){const u=uf(Vu(h),cf);return u.s!==t.s&&s("solve.one-side","Everything on one side",["move"],t,u,{v:n}),kf(e,h,l,n,r,s,i,o,a,u)}}if(1===f.length)return yf(e,t,m,d,n,r,s,i,o,a);const g=uf(Vu(h),cf),v=Ph(h,n);if(v&&[...v.values()].every(e=>!Dh(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}),kf(e,h,v,n,r,s,i,o,a,g);const b=Yh(h),y=b.factors.filter(e=>Dh(e.base,n)&&!(hu(e.exp)&&e.exp.q.sign<0));if(y.length>=2||1===y.length&&b.factors.length>1){const l=uf(sf(b),cf);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=>uf(Vu(e.base),cf));u.length>1&&s("solve.zero-product","A product is zero when a factor is",["split"],l,u.reduce((e,t)=>e?Tl("|",[e,t]):t,null),{});for(const t of u)bf(e,t,n,r,s,i,o,a+1);return}const w=af(h);if(Dh(w.den,n)){const l=uf(Vu(w.num),cf);return s("solve.clear-denominator","Clear the denominator",["move"],t,l,{den:Vu(w.den)}),bf(e,l,n,r,s,i,o,a+1)}const x=f.filter(e=>!$f(e,n));if(1===x.length&&/\b(sqrt|root|abs)\b/.test(Vu(x[0]).s))return yf(e,t,x[0],Tu($u(Xu(h).filter(e=>e!==x[0]))),n,r,s,i,o,a);const $=function(e,t){const n=Vu(e),r=new Map;for(const{node:e}of Wl(n,"pre"))if(Fl(e)&&Qu(e).has(t))if("^"!==e.op||Qu(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=Bu(e.args[1]),{coef:s,rest:i}=xu(n);if(i&&s.isInteger&&Vu(i).s===t){const n=Vu(Mu(Bu(e.args[0]),Bu(Il(t))));r.set(n.s,n)}}const s="u"===t?"w":"u";for(const e of r.values()){const r=qf(n,e,t,s);if(!r||Qu(r).has(t))continue;const i=Bu(r),o=Ph(i,s);if(o&&Math.max(...o.keys())>=1)return{kernel:Bu(e),poly:i,symbol:s}}return null}(h,n);if($){const t=$.symbol;s("solve.substitute","Substitute",["substitute"],g,uf(Vu($.poly),cf),{u:Il(t),kernel:Vu($.kernel)});const l=[];bf(e,uf(Vu($.poly),cf),t,r,s,l,o,a+1);for(const t of l)bf(e,uf(Vu($.kernel),t),n,r,s,i,o,a+1);return}return Mf(e,g,n,r,s,i,o)}function yf(e,t,n,r,s,i,o,a,l,u){let c=uf(Vu(n),Vu(r));c.s!==t.s&&o("solve.move","Move the terms",["move"],t,c,{v:s});const{coef:h,rest:f}=xu(n),p=f?Ju(f):[],m=qu([au(h),...p.filter(e=>!Dh(e,s))]);if(!hu(m)||!m.q.isOne){const e=qu(p.filter(e=>Dh(e,s))),t=uf(Vu(e),Vu(Lu(r,m))),n=hu(m)&&!m.q.isInteger&&(1n===m.q.n||-1n===m.q.n);o(n?"solve.multiply":"solve.divide",n?"Multiply both sides":"Divide both sides",["move"],c,t,{by:Vu(n?au(m.q.inv()):m),v:s}),c=t}if("sym"===c.args[0].type&&c.args[0].token===s)return void a.push(c.args[1]);const d=Bu(c.args[1]);if(hu(d)&&d.q.isZero){const t=Bu(c.args[0]),n=Ju(t).filter(e=>Dh(e,s)&&!wf(e));if(!n.length&&Ju(t).some(e=>Dh(e,s)))return void o("solve.never","No solution",["check"],c,c,{});if(n.length>1||n.length<Ju(t).filter(e=>Dh(e,s)).length){const t=n.map(e=>uf(Vu(xf(e)),cf));o("solve.zero-product","A product is zero when a factor is",["split"],c,t.reduce((e,t)=>e?Tl("|",[e,t]):t,null),{});for(const n of t)bf(e,n,s,i,o,a,l,u+1);return}}const g=_h(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),bf(e,g.node,s,i,o,a,l,u+1)):Mf(e,c,s,i,o,a,l)}const wf=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&hu(e.fs[0].e)&&e.fs[0].e.q.sign<0,xf=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&hu(e.fs[0].e)&&e.fs[0].e.q.sign>0?e.fs[0].b:e,$f=(e,t)=>{const n=Ph(e,t);return Boolean(n)&&[...n.values()].every(e=>!Dh(e,t))};function kf(e,t,n,r,s,i,o,a,l,u){const c=Math.max(...n.keys()),h=Wh(n);if(ru.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=Mu(au(t.abs()),au(new Jl(1n,BigInt(c)))),s=[];for(let r=0;r<c;r++){const i=qu([au(new Jl(BigInt((t.sign<0?1:0)+2*r),BigInt(c))),Bu(Il("pi"))]),o=Tl("*",[Vu(n),Tl("+",[Tl("cos",[Vu(i)]),Tl("*",[Il("i"),Tl("sin",[Vu(i)])])])]);s.push(_h(o,e.set.view("simplify"),{format:e.format}).node)}return i("solve.roots","All n roots",["complex"],u,s.map(e=>uf(Il(r),e)).reduce((e,t)=>e?Tl("|",[e,t]):t),{v:r,n:String(c),last:String(c-1),r:Vu(au(t))}),void o.push(...s)}if(h){const{roots:n}=Xh(h);if(n.length){const n=Yh(t),c=uf(sf(n),cf);if(n.factors.length>1||n.factors.some(e=>!(hu(e.exp)&&e.exp.q.isOne))){i("solve.factor","Factor",["factor"],u,c,{});const t=n.factors.filter(e=>Dh(e.base,r)).map(e=>uf(Vu(e.base),cf));t.length>1&&i("solve.zero-product","A product is zero when a factor is",["split"],c,t.reduce((e,t)=>e?Tl("|",[e,t]):t,null),{});for(const n of t)bf(e,n,r,s,i,o,a,l+1);return}}}if(2===c){const e=n.get(2),t=n.get(1)??au(Jl.ZERO),s=n.get(0)??au(Jl.ZERO),a=$u([Mu(t,au(Jl.of(2))),qu([au(Jl.of(-4)),e,s])]);if(hu(a)&&a.q.sign<0&&!ru.complex)return void i("solve.no-real","No real solutions",["quadratic"],u,u,{D:Vu(a)});const l=qu([au(Jl.of(2)),e]),c=Mu(a,au(Jl.HALF)),h=Vu(Lu($u([Tu(t),c]),l)),f=Vu(Lu($u([Tu(t),Tu(c)]),l)),p=h.s===f.s?uf(Il(r),h):Tl("|",[uf(Il(r),h),uf(Il(r),f)]);return i(ru.complex&&hu(a)&&a.q.sign<0?"solve.quadratic-complex":"solve.quadratic","The quadratic formula",["quadratic"],u,p,{a:Vu(e),b:Vu(t),c:Vu(s),D:Vu(a),root:Vu(c),v:r}),o.push(h),void(f.s!==h.s&&o.push(f))}return Mf(e,u,r,s,i,o,a)}function qf(e,t,n,r){if(e.s===t.s)return Il(r);if(!Fl(e))return e;if("^"===e.op&&"^"===t.op&&e.args[0].s===t.args[0].s){const t=Bu(e.args[1]),{coef:s,rest:i}=xu(t);if(i&&Vu(i).s===n&&s.isInteger)return Tl("^",[Il(r),Vu(au(s))])}return Tl(e.op,e.args.map(e=>qf(e,t,n,r)))}function Mf(e,t,n,r,s,i,o){if(r.approximate){const e="number"==typeof r.approximate?r.approximate:15,o=Bu(Tl("-",[t.args[0],t.args[1]])),a=ru.complex?Wh(Ph(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=Af(e);if(0===t)return n;const r=Tl("*",[Af(Math.abs(t)),Il("i")]);return 0===e?t<0?Tl("neg",[r]):r:Tl(t<0?"-":"+",[n,r])})}(a.map(e=>e.toNumber()),Math.min(e,14)):function(e,t,n){const r=Bu(Tl("-",[e.args[0],e.args[1]])),s=Vu(r),i=e=>{try{return vh(gf(s,t,Sf(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(Sf(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(Sf(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=>uf(Il(n),e)).reduce((e,t)=>e?Tl("|",[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 Af=e=>zl(String(e).includes("e")?e.toFixed(20):String(e)),Sf=e=>zl(Number.isInteger(e)?String(e):e.toFixed(17));const Nf=()=>zl("1"),Of={"<":e=>e<0,">":e=>e>0,"≤":e=>e<=0,"≥":e=>e>=0},Ef=new Set(["sin","cos","tan","csc","sec","cot"]);function If(e,t,n){const r=[],s=[],i=[];let o=t;for(;Fl(o.args[0])&&Of[o.args[0].op];)i.unshift({op:o.op,right:o.args[1]}),o=o.args[0];const a=[o.args[0],o.args[1],...i.map(e=>e.right)];[o.op,...i.map(e=>e.op)].forEach((e,t)=>s.push({h:Pu(Tl("-",[a[t],a[t+1]])),op:e}));const l=new Set(s.flatMap(e=>[...Qu(e.h)]));if(l.delete(n),l.size)throw new Vl(`an inequality in ${n} with other unknowns (${[...l].join(", ")}) can't be charted`);if(s.some(e=>Wl(e.h,"pre").some(({node:e})=>Fl(e)&&Ef.has(e.op)&&Qu(e).has(n))))return{pieces:null,steps:r,unsolved:!0};const u=[];for(const{h:e}of s){u.push(e);for(const{node:t}of Wl(e,"pre"))Fl(t)&&Qu(t).has(n)&&("/"===t.op&&u.push(t.args[1]),"sqrt"!==t.op&&"ln"!==t.op||u.push(t.args[0]),"root"===t.op&&u.push(t.args[1]),"log"===t.op&&u.push(t.args[1],t.args[0],Tl("-",[t.args[0],Nf()])),["arcsin","arccos","arctanh","arcsec","arccsc"].includes(t.op)&&u.push(Tl("-",[t.args[0],Nf()]),Tl("+",[t.args[0],Nf()])),"arccosh"===t.op&&u.push(Tl("-",[t.args[0],Nf()])),"^"===t.op&&hu(Bu(t.args[1]))&&Bu(t.args[1]).q.sign<0&&u.push(t.args[0]),"^"===t.op&&hu(Bu(t.args[1]))&&!Bu(t.args[1]).q.isInteger&&u.push(t.args[0]))}const c=new Map;for(const t of u){const s=ff(e,uf(t,cf),n,{});if(s.unsolved.length&&!s.always)return{pieces:null,steps:r,unsolved:!0};if(!s.always)for(const e of s.solutions){const t=mf(e);!t||Math.abs(t.im)>1e-12||c.set(e.s,{node:e,x:t.re})}}const h=[...c.values()].sort((e,t)=>e.x-t.x).filter((e,t,n)=>0===t||Math.abs(e.x-n[t-1].x)>1e-12),f=h.map(e=>e.x),p=[];if(f.length){p.push(f[0]-Math.max(1,Math.abs(f[0])));for(let e=0;e+1<f.length;e++)p.push((f[e]+f[e+1])/2);p.push(f[f.length-1]+Math.max(1,Math.abs(f[f.length-1])))}else p.push(0);const m=p.map(e=>s.every(({h:t,op:r})=>{try{const s=vh(gf(t,n,zl(function(e){return Math.abs(e)>=1e21?BigInt(Math.round(e)).toString():e.toFixed(Math.min(100,Math.max(0,17-Math.floor(Math.log10(Math.abs(e)||1)))))}(e))),{digits:20});return!(!Number.isFinite(s.re)||Math.abs(s.im)>1e-12)&&Of[r](Math.abs(s.re)<1e-30?0:s.re)}catch{return!1}})),d=h.map(e=>s.every(({h:t,op:r})=>{try{const s=vh(Pu(gf(t,n,e.node)),{digits:30});return!(!Number.isFinite(s.re)||Math.abs(s.im)>1e-12)&&Of[r](Math.abs(s.re)<1e-15?0:s.re)}catch{return!1}})),g=[];let v=null;const b=(e,t)=>{g.push({...v,hi:e,hiClosed:t}),v=null};for(let e=0;e<=h.length;e++){const t=0===e?null:h[e-1].node;if(m[e]?v??={lo:t,loClosed:!1}:v&&b(t,e>0&&d[e-1]),e===h.length)break;const n=h[e];if(d[e]){if(v)continue;m[e+1]?v={lo:n.node,loClosed:!0}:g.push({lo:n.node,hi:n.node,loClosed:!0,hiClosed:!0})}else v&&b(n.node,!1)}v&&b(null,!1);const y=h.length?h.map(t=>e.format(t.node)).join(", "):"none";return r.push(e.step("solve.sign-chart","A sign chart",["inequality"],t,t,{points:Il(y),v:n})),{pieces:g,steps:r}}const zf={tan:"cos",sec:"cos",csc:"sin",cot:"sin"};class _f extends Error{}const jf=e=>({fin:e}),Tf={bnd:!0},Lf=e=>({inf:e}),Ff=Il("∞");function Zf(e){try{const t=vh(e,{digits:15});return Math.abs(t.im??0)>1e-12?NaN:t.re??t.number}catch{return NaN}}function Cf(e){if(!ru.complex)return Number.isFinite(Zf(e));try{const t=vh(e,{digits:15});return Number.isFinite(t.re??t.number)&&Number.isFinite(t.im??0)}catch{return!1}}function Rf(e,t,n){if(!Number.isFinite(n))return!1;try{const r=vh(gf(e,t,zl(Pf(n))),{digits:15});return Math.abs(r.im??0)>1e-12}catch(e){return/not real/.test(e.message)}}function Bf(e,t,n){return Number.isFinite(n)?Zf(gf(e,t,zl(Pf(n)))):NaN}function Pf(e){const t=Math.min(40,Math.max(0,16-Math.floor(Math.log10(Math.abs(e)||1))));return e.toFixed(t)}function Df(e,t,n,r){const s=Wf(n,r).map(n=>Bf(e,t,n)).filter(Number.isFinite);if(s.length<3)return NaN;const[i,o,a]=s.slice(-3),l=Math.max(1,Math.abs(a));return Math.abs(a-o)<1e-4*l&&Math.abs(o-i)<.01*l?a:NaN}function Wf(e,t){if(e.inf)return[100,1e3,1e4,1e5,1e6].map(t=>t*e.inf);const n=Zf(e.fin);return[.001,1e-4,1e-5,1e-6,1e-7].map(e=>n+t*e*Math.max(1,Math.abs(n)))}function Uf(e,t,n,r,s=0){const i=[];if(!s&&!r.inf){const[e,s]=[Df(t,n,r,-1),Df(t,n,r,1)];if(Number.isFinite(e)&&Number.isFinite(s)&&Math.abs(e-s)>.001*Math.max(1,Math.abs(e),Math.abs(s)))throw new _f(`from the left it goes to ${+e.toPrecision(6)}, from the right to ${+s.toPrecision(6)}`)}if(!r.inf&&!ru.complex)for(const e of s?[s]:[-1,1])if(Wf(r,e).every(e=>Rf(t,n,e)))throw new _f(`it has no real values ${e<0?"to the left":"to the right"} of ${+Zf(r.fin).toPrecision(6)}`);const o=new Vf(e,n,r,s,i);let a;try{if(a=o.of(Pu(t),0),a.bnd)throw new _f("it keeps swinging between bounds")}catch(e){if(e instanceof _f){const e=(r.inf?[r.inf]:s?[s]:[-1,1]).map(e=>Df(t,n,r,e));if(e.every(Number.isFinite)&&e.every(t=>Math.abs(t-e[0])<1e-6*Math.max(1,Math.abs(t))))throw new Vl(`numbers near the point settle on ${+e[0].toPrecision(6)}: not answered`)}throw e}return function(e,t,n,r,s){const i=r?[r]:n.inf?[-1]:[-1,1];for(const r of i){const i=Wf(n,r).map(n=>Bf(e,t,n)).filter(Number.isFinite);if(i.length<3)continue;const o=i[i.length-1];if(s.inf){if(Math.sign(o)!==s.inf||Math.abs(o)<Math.abs(i[0]))throw new Vl(`numbers near the point don't go to ${s.inf>0?"∞":"-∞"}: not answered`)}else{const e=Zf(s.fin);if(!Number.isFinite(e))continue;const t=i.map(t=>Math.abs(t-e)),n=Math.abs(i[i.length-1]-i[i.length-2]),r=t.every((e,n)=>0===n||e<t[n-1])&&t[t.length-1]<.5*t[0]&&t[t.length-1]<10*n;if(t[t.length-1]>.01*Math.max(1,Math.abs(e))&&!r)throw new Vl(`numbers near the point go to ${o.toPrecision(6)}, not ${e.toPrecision(6)}: not answered`)}}}(t,n,r,s,a),{value:a,steps:i}}class Vf{constructor(e,t,n,r,s){Object.assign(this,{cas:e,v:t,a:n,side:r,steps:s}),this.point=n.inf?n.inf>0?Ff:Il("-∞"):n.fin}step(e,t,n,r,s={}){this.steps.push(this.cas.step(e,t,["limit"],n,r,{v:Il(this.v),a:this.point,...s}))}of(e,t){if(t>8)throw new Vl("this limit went too deep");const{v:n,a:r}=this;if(!Qu(e).has(n))return jf(e);if("sym"===e.type)return r.inf?Lf(r.inf):jf(r.fin);if(r.inf){const s=Wh(Ph(Bu(e),n));if(s&&s.length>1){const i=s.length-1,o=s[i].sign*(i%2&&r.inf<0?-1:1);return 0===t&&this.step("limit.leading","The leading term",e,Pu(Tl("*",[Vu(au(s[i])),Tl("^",[Il(n),zl(String(i))])])),{f:e,lead:Pu(Tl("*",[Vu(au(s[i])),Tl("^",[Il(n),zl(String(i))])]))}),Lf(o)}}if(!r.inf&&0===t){const t=gf(e,n,r.fin);let s=null;if(Cf(t)&&!this.pole(t)&&!Hf(t))try{s=Pu(t)}catch{}if(s&&Cf(s)){const t=this.cas.simplify(s,{steps:!1}).result;return this.step("limit.substitute","Put the point in",e,t,{f:e}),jf(t)}}if(!Fl(e))return jf(e);switch(e.op){case"+":case"-":return this.sum(e,t);case"neg":return Qf(this.of(e.args[0],t+1));case"*":return this.product(e,t);case"/":return this.quotient(e,e.args[0],e.args[1],t);case"^":return this.power(e,t);default:return this.func(e,t)}}signOf(e){const t=Math.sign(Zf(e));if(!t)throw new Vl(`the sign of ${this.cas.format(e)} is not known`);return t}pole(e){return Gf(e).some(e=>Fl(e)&&zf[e.op]&&this.isExactZero(Tl(zf[e.op],[e.args[0]])))}isExactZero(e){try{const t=this.cas.simplify(Pu(e),{steps:!1}).result;return Ll(t)&&0===Number(t.value)}catch{return!1}}sum(e,t){const[n,r]=e.args;let s,i;try{s=this.of(n,t+1),i=this.of(r,t+1)}catch(n){if(!(n instanceof _f))throw n;const r=af(Bu(e)),s=Pu(Tl("/",[Vu(r.num),Vu(r.den)]));if(s.s===e.s)throw n;return this.step("limit.combine","One fraction",e,s,{f:e}),this.of(s,t+1)}const o="-"===e.op?Qf(i):i;if(s.bnd||o.bnd)return s.inf||o.inf?s.inf?s:o:Tf;if(s.fin&&o.fin)return jf(Pu(Tl("+",[s.fin,o.fin])));if(s.inf&&o.inf&&s.inf!==o.inf){const s="-"===e.op?r:Tl("neg",[r]);if([n,r].some(e=>Fl(e)&&"sqrt"===e.op)||Fl(r)&&"neg"===r.op&&Fl(r.args[0])&&"sqrt"===r.args[0].op){const r=Pu(Tl("/",[Tl("-",[Tl("^",[n,zl("2")]),Tl("^",[s,zl("2")])]),Tl("+",[n,s])]));return this.step("limit.conjugate","∞ − ∞: the conjugate",e,r,{f:e}),this.of(r,t+1)}const i=af(Bu(e)),o=Pu(Tl("/",[Vu(i.num),Vu(i.den)]));if(o.s===e.s)throw new Vl("∞ − ∞ that does not become one fraction");return this.step("limit.combine","∞ − ∞: one fraction",e,o,{f:e}),this.of(o,t+1)}return s.inf?s:o}product(e,t){const[n,r]=e.args,s=this.of(n,t+1),i=this.of(r,t+1),o=e=>e.fin&&Math.abs(Zf(e.fin))<1e-300;if(s.bnd||i.bnd){const t=s.bnd?i:s;if(o(t))return this.step("limit.squeeze","The squeeze theorem",e,zl("0"),{f:e,bounded:s.bnd?n:r}),jf(zl("0"));if(t.inf)throw new _f("a growing factor times one that keeps swinging");return Tf}if(s.fin&&i.fin)return jf(Pu(Tl("*",[s.fin,i.fin])));if(o(s)&&i.inf||s.inf&&o(i)){const[i,a]=o(s)?[n,r]:[r,n],l=e=>e.s.split(" ").length,[u,c]=[Pu(Tl("/",[zl("1"),i])),Pu(Tl("/",[zl("1"),a]))],h=l(u)<=l(c)?Tl("/",[a,u]):Tl("/",[i,c]);return this.step("limit.zero-times-infinity","0·∞: a quotient",e,h,{f:e}),this.quotient(h,h.args[0],h.args[1],t+1)}const a=e=>e.inf?e.inf:this.signOf(e.fin);return Lf(a(s)*a(i))}quotient(e,t,n,r){const{v:s,a:i}=this;if(i.inf){const t=this.rational(e,r);if(t)return t}const o=this.of(t,r+1),a=this.of(n,r+1),l=e=>e.fin&&Math.abs(Zf(e.fin))<1e-300;if(o.bnd&&a.inf)return this.step("limit.squeeze","The squeeze theorem",e,zl("0"),{f:e,bounded:t}),jf(zl("0"));if(o.bnd&&a.fin&&!l(a))return Tf;if(a.bnd)throw new Vl("a quotient over something that keeps swinging is not worked out here");if(o.inf&&a.inf&&i.inf){const s=this.dividePower(e,t,n,r);if(s)return s}if(a.fin&&!l(a))return o.fin?jf(this.cas.simplify(Pu(Tl("/",[o.fin,a.fin])),{steps:!1}).result):Lf(o.inf*this.signOf(a.fin));if(a.inf&&o.fin)return jf(zl("0"));if(l(a)&&!l(o))return this.blowUp(e);const u=l(o)?"0/0":"∞/∞",c=this.rational(e,r);if(c)return c;const h=Pu(this.cas.differentiate(t,s)),f=Pu(this.cas.differentiate(n,s)),p=Pu(Tl("/",[h,f]));return this.step("limit.lhopital","L'Hôpital's rule",e,p,{f:e,form:Il(u)}),this.of(p,r+1)}dividePower(e,t,n,r){const{v:s,a:i}=this;if(!Gf(e).some(e=>Fl(e)&&(["sqrt","root","sin","cos"].includes(e.op)||"^"===e.op&&!Qu(e.args[1]).size&&!Number.isInteger(Zf(e.args[1]))))||this.divided?.has(e.s))return null;const[o,a]=[1e4*i.inf,1e6*i.inf],l=Math.log(Math.abs(Bf(n,s,a)/Bf(n,s,o)))/Math.log(100),u=Math.round(2*l)/2;if(!Number.isFinite(l)||Math.abs(l-u)>.05||u<=0||i.inf<0&&!Number.isInteger(u))return null;const c=Tl("^",[Il(s),zl(String(u))]),h=e=>{if(Fl(e)&&("+"===e.op||"-"===e.op))return Tl(e.op,e.args.map(h));if(Fl(e)&&"neg"===e.op)return Tl("neg",[h(e.args[0])]);if(Fl(e)&&"sqrt"===e.op){const t=Tl("sqrt",[Pu(Tl("/",[e.args[0],Tl("^",[Il(s),zl(String(2*u))])]))]);return i.inf<0&&u%2?Tl("neg",[t]):t}return Pu(Tl("/",[e,c]))},f=Tl("/",[Pu(h(t)),Pu(h(n))]);return(this.divided??=new Set).add(e.s),this.step("limit.divide-power","Divide by the highest power",e,f,{f:e,power:c}),this.quotient(f,f.args[0],f.args[1],r+1)}rational(e,t){const{v:n,a:r}=this,{num:s,den:i}=af(Bu(e)),o=Wh(Ph(s,n)),a=Wh(Ph(i,n));if(!o||!a||a.length<2)return null;if(r.inf){const[t,s]=[o.length-1,a.length-1],i=Pu(Tl("/",[Tl("*",[Vu(au(o[t])),Tl("^",[Il(n),zl(String(t))])]),Tl("*",[Vu(au(a[s])),Tl("^",[Il(n),zl(String(s))])])]));if(i.s!==e.s&&this.step("limit.leading","The leading terms",e,i,{f:e,lead:i}),t<s)return jf(zl("0"));if(t===s)return jf(Vu(au(o[t].div(a[s]))));const l=o[t].div(a[s]).sign*((t-s)%2&&r.inf<0?-1:1);return Lf(l)}const l=this.cas.cancel(e,{steps:!1}).result;if(l.s===e.s)return null;this.step("limit.cancel","Cancel the common factor",e,l,{f:e});const u=gf(l,n,r.fin);return Number.isFinite(Zf(u))?jf(this.cas.simplify(Pu(u),{steps:!1}).result):this.blowUp(l)}blowUp(e){const{v:t,a:n,side:r}=this,s=(r?[r]:[-1,1]).map(r=>function(e,t,n,r){const s=Wf(n,r).map(n=>Bf(e,t,n)).filter(Number.isFinite);if(!s.length)return 0;const i=Math.sign(s[s.length-1]);return s.slice(-3).every(e=>Math.sign(e)===i)?i:0}(e,t,n,r));if(s.includes(0))throw new Vl("the sign near the point could not be told");if(2===s.length&&s[0]!==s[1])throw this.step("limit.one-sided","The two sides differ",e,e,{f:e,left:s[0]>0?Ff:Il("-∞"),right:s[1]>0?Ff:Il("-∞")}),new _f(`from the left it goes to ${s[0]>0?"∞":"-∞"}, from the right to ${s[1]>0?"∞":"-∞"}`);return Lf(s[0])}power(e,t){const{v:n}=this,[r,s]=e.args,i=this.of(r,t+1);let o;const a=this.steps.length;try{o=this.of(s,t+1)}catch(n){if(!(n instanceof _f)||!i.fin||Math.abs(Zf(i.fin)-1)>1e-12)throw n;return this.steps.length=a,this.expLog(e,r,s,"1^∞",t)}if(i.bnd||o.bnd)throw new Vl("a power of something that keeps swinging is not worked out here");const l=e=>e.fin?Zf(e.fin):e.inf*(1/0),u=l(i),c=l(o);if(i.fin&&o.fin){if(Math.abs(u)<1e-300&&c<0)return this.blowUp(e);if(!(Math.abs(u)<1e-300&&Math.abs(c)<1e-300))return jf(this.cas.simplify(Pu(Tl("^",[i.fin,o.fin])),{steps:!1}).result)}const h=!Qu(r).has(n),f=!Qu(s).has(n),p=i.fin&&Math.abs(u)<1e-300,m=i.fin&&Math.abs(u-1)<1e-12;if(i.fin&&o.inf&&(!m||h)){if(m)return jf(zl("1"));if(p){if(o.inf<0){if(h)throw new _f("0 to a negative power has no value");return Lf(1)}return jf(zl("0"))}if(u>1)return o.inf>0?Lf(1):jf(zl("0"));if(u>0)return o.inf>0?jf(zl("0")):Lf(1);throw new _f("a negative number to a growing power swings between signs")}if(i.inf<0&&!f)throw new Vl("a power of something going to -∞ is not worked out here");if(i.inf&&(f||o.fin&&Math.abs(c)>1e-300||o.inf)){if(c>0)return Lf(i.inf>0?1:f&&Number.isInteger(c)&&c%2?-1:1);if(c<0)return jf(zl("0"))}if(f&&p&&c>0)return jf(zl("0"));const d=m?"1^∞":p?"0^0":i.inf&&o.fin?"∞^0":null;if(!d)throw new Vl("a power of this shape is not worked out here");return this.expLog(e,r,s,d,t)}expLog(e,t,n,r,s){const i=Pu(Tl("*",[n,Tl("ln",[t])]));this.step("limit.exp-log","Take logs",e,Tl("^",[Il("e"),i]),{f:e,form:Il(r)});const o=this.of(i,s+1);if(o.bnd)throw new Vl("a power of something that keeps swinging is not worked out here");return o.inf?o.inf>0?Lf(1):jf(zl("0")):jf(this.cas.simplify(Pu(Tl("^",[Il("e"),o.fin])),{steps:!1}).result)}func(e,t){const n=e.op,r=e.args;if(1!==r.length){if("log"===n&&!Qu(r[0]).has(this.v)){const e=this.of(r[1],t+1);if(e.fin){const t=Pu(Tl("log",[r[0],e.fin]));if(Number.isFinite(Zf(t)))return jf(this.cas.simplify(t,{steps:!1}).result)}return this.of(Pu(Tl("/",[Tl("ln",[r[1]]),Tl("ln",[r[0]])])),t+1)}throw new Vl(`a limit of ${n} is not worked out here`)}let s;try{s=this.of(r[0],t+1)}catch(e){if(e instanceof _f&&("sin"===n||"cos"===n))return Tf;throw e}if(s.bnd){if("sin"===n||"cos"===n||"arctan"===n||"abs"===n)return Tf;throw new Vl(`${n} of something that keeps swinging is not worked out here`)}if(s.fin){if(zf[n]&&this.isExactZero(Tl(zf[n],[s.fin])))return this.blowUp(e);const t=Pu(Tl(n,[s.fin]));if(Cf(t))return jf(this.cas.simplify(t,{steps:!1}).result);if("ln"===n&&Math.abs(Zf(s.fin))<1e-300)return Lf(-1);if(["tan","sec","csc","cot"].includes(n))return this.blowUp(e);throw new Vl(`${n} has no value at the limit of its argument`)}const i=s.inf;switch(n){case"sqrt":case"ln":case"cosh":if(i<0&&"cosh"!==n)throw new _f(`${n} has no value as its argument goes to -∞`);return Lf(1);case"abs":return Lf(1);case"sinh":return Lf(i);case"tanh":return jf(zl(String(i)));case"arctan":return jf(Pu(Tl("/",[i>0?Il("pi"):Tl("neg",[Il("pi")]),zl("2")])));case"arccot":return jf(i>0?zl("0"):Il("pi"));case"arcsec":case"arccsc":return jf("arcsec"===n?Pu(Tl("/",[Il("pi"),zl("2")])):zl("0"));case"sin":case"cos":return Tf;case"tan":case"sec":case"csc":case"cot":throw new _f(`${n} keeps swinging as its argument grows`);default:throw new Vl(`a limit of ${n} at ∞ is not worked out here`)}}}const Hf=e=>Gf(e).some(e=>Fl(e)&&("/"===e.op&&Math.abs(Zf(e.args[1]))<1e-300||"^"===e.op&&Zf(e.args[1])<0&&Math.abs(Zf(e.args[0]))<1e-300)),Gf=(e,t=[])=>(t.push(e),Fl(e)&&e.args.forEach(e=>Gf(e,t)),t),Qf=e=>e.bnd?e:e.inf?Lf(-e.inf):jf(Pu(Tl("neg",[e.fin])));function Xf(e){if(!Fl(e)||"lim"!==e.op)return null;const[t,n,r,s]=e.args;if(Fl(n)&&"→"===n.op)return{f:t,v:n.args[0].token,to:n.args[1],side:0};if("sym"===n?.type&&r){const e="r"===s?.token?1:"l"===s?.token?-1:0;return{f:t,v:n.token,to:r,side:e}}return null}function Jf(e){return"sym"!==e.type||"∞"!==e.token&&"oo"!==e.token&&"infinity"!==e.token?"sym"===e.type&&"-∞"===e.token||Fl(e)&&"neg"===e.op&&"sym"===e.args[0].type&&"∞"===e.args[0].token?Lf(-1):jf(Pu(e)):Lf(1)}const Yf=new Set(["sin","cos","tan","sec","csc","cot"]),Kf=()=>zl("2");function ep(e,t){if(!tp(t))return[];let n,r;try{const e=np(t);n=new Map;r=af(Bu(rp(e,n)))}catch{return[]}const s=[];for(const t of["sin","cos","none"])try{const i="none"===t?Rh(r.num):sp(r.num,n,t),o="none"===t?Rh(r.den):sp(r.den,n,t);if(!i||!o)continue;const a=[ap(i,o)],l=[ip(i,n),ip(o,n)];l[0]&&l[1]&&a.push(ap(l[0],l[1]));for(const t of a)s.push(up(e,lp(t,n)))}catch{}return s}const tp=e=>Fl(e)&&(Yf.has(e.op)||e.args.some(tp));function np(e){if(!Fl(e))return e;const t=e.args.map(np),[n]=t,r=e=>Tl("sin",[e]),s=e=>Tl("cos",[e]),i=e=>Fl(e)&&"*"===e.op&&Ll(e.args[0])&&2===Number(e.args[0].value)?2===e.args.length?e.args[1]:Tl("*",e.args.slice(1)):null;switch(e.op){case"tan":return Tl("/",[r(n),s(n)]);case"sec":return Tl("/",[zl("1"),s(n)]);case"csc":return Tl("/",[zl("1"),r(n)]);case"cot":return Tl("/",[s(n),r(n)]);case"sin":{const e=i(n);return e?Tl("*",[Tl("*",[Kf(),r(e)]),s(e)]):r(n)}case"cos":{const e=i(n);return e?Tl("-",[Tl("^",[s(e),Kf()]),Tl("^",[r(e),Kf()])]):s(n)}default:return Tl(e.op,t)}}function rp(e,t){if(!Fl(e))return e;if(("sin"===e.op||"cos"===e.op)&&!tp(e.args[0])){const n=e.args[0];t.has(n.s)||t.set(n.s,{u:n,s:`$s${t.size}`,c:`$c${t.size}`});const r=t.get(n.s);return Il("sin"===e.op?r.s:r.c)}return Tl(e.op,e.args.map(e=>rp(e,t)))}function sp(e,t,n){let r=Rh(e);for(const{s:e,c:s}of t.values()){const[t,i]="sin"===n?[e,s]:[s,e],o=Ph(r,t);if(!o)return null;const a=[];for(const[e,n]of o){const r=Math.floor(e/2),s=[n];e%2&&s.push(Bu(Il(t))),r&&s.push(Bu(Tl("^",[Tl("-",[zl("1"),Tl("^",[Il(i),Kf()])]),zl(String(r))]))),a.push(qu(s))}if(r=Rh($u(a)),Xu(r).length>200)return null}return r}function ip(e,t){let n=Rh(e);for(const{u:e,s:r,c:s}of t.values()){const t=Tl("sin",[Tl("*",[Kf(),e])]),i=Tl("cos",[Tl("*",[Kf(),e])]),o=[];for(const e of Xu(n)){const n=Vu(e),a=op(n,r),l=op(n,s);if(a+l===0){o.push(e);continue}if(a+l!==2)return null;const u=gf(gf(n,r,zl("1")),s,zl("1")),c=Tl("/",1===a?[t,Kf()]:2===a?[Tl("-",[zl("1"),i]),Kf()]:[Tl("+",[zl("1"),i]),Kf()]);o.push(Bu(Tl("*",[u,c])))}n=Rh($u(o))}return n}function op(e,t){const n=Ph(Bu(e),t);return n?Math.max(0,...n.keys()):0}function ap(e,t){const n=Bu(Tl("/",[Vu(e),Vu(t)])),r=lf(n);return r?sf(r):Vu(n)}function lp(e,t){let n=e;for(const{u:e,s:r,c:s}of t.values())n=gf(gf(n,r,Tl("sin",[e])),s,Tl("cos",[e]));return Pu(n)}function up(e,t){const n=e=>{if(!Fl(e))return e;const t=e.args.map(n);if("/"===e.op&&Ll(t[0])){const e=t[1],[n,r]=Fl(e)&&"^"===e.op&&Ll(e.args[1])?[e.args[0],e.args[1]]:[e,null],s=Fl(n)&&{cos:"sec",sin:"csc"}[n.op];if(s){const e=Tl(s,n.args),i=r?Tl("^",[e,r]):e;return 1===Number(t[0].value)?i:Tl("*",[t[0],i])}}return Tl(e.op,t)},r=_h(Pu(n(t)),e.set.view("simplify"),{format:e.format}).node;try{const{num:e,den:t}=af(Bu(r)),n=Pu(Tl("/",[Vu(e),Vu(t)]));return n.s.split(" ").length<r.s.split(" ").length?n:r}catch{return r}}const cp=(e,t)=>Tl("int",[e,"string"==typeof t?Il(t):t]);function hp(e,t,n,r=0){if(r>6)throw new Vl("integration went too deep");const s=[],i=e.set.view("integrate"),o=_h(t,e.set.view("simplify"),{format:e.format});s.push(...o.steps);let a=Pu(cp(o.node,n));for(let t=0;t<40;t++){const t=_h(a,i,{format:e.format});s.push(...t.steps),a=t.node;const n=Wl(a,"pre").find(({node:e})=>{return Fl(t=e)&&"int"===t.op&&2===t.args.length;var t});if(!n)return{node:a,steps:s};const o=fp(e,n.node,r);if(!o)throw new Vl(`no rule for ∫ ${e.format(n.node.args[0])} d${n.node.args[1].token}`);s.push(...o.steps),a=Pu(Ul(a,n.path,o.node))}throw new Vl("integration did not finish")}function fp(e,t,n){const[r,s]=t.args,i=s.token,o=Bu(r),a=function(e,t){const{num:n,den:r}=af(e),s=Yh(n),i=Yh(r),o=s.coef.div(i.coef);if(o.isOne||!Dh(e,t))return null;const a=qu([...s.factors.map(e=>Au(e.base,e.exp)),...i.factors.map(e=>Au(e.base,Tu(e.exp)))]);return{c:o,rest:a}}(o,i);if(a){const n=Tl("*",[Vu(au(a.c)),cp(Vu(a.rest),s)]);return{node:n,steps:[e.step("integrate.constant","Take the number out",["split"],t,n,{c:Vu(au(a.c))})]}}const l=Rh(o);if(Vu(l).s!==r.s&&"add"===l.k){const n=cp(Vu(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 Wl(e,"pre")){if(!Fl(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||!Qu(r).has(t))continue;const e=Ph(Bu(r),t);if(!e||1!==Math.max(...e.keys()))continue;const s=e.get(1);Dh(s,t)||hu(s)&&s.q.isZero||n.set(r.s,{node:r,a:s})}}for(const r of n.values()){if(!Qu(xp(e,r.node,Il("§"))).has(t))return r}return null}(r,i);if(u){const s="u"===i?"t":"u",o=xp(r,u.node,Il(s));if(!Qu(o).has(i)){const r=hp(e,Pu(o),s,n+1),a=Pu(gf(r.node,s,u.node)),l=Vu(Lu(Bu(a),u.a));return{node:l,steps:[e.step("integrate.substitute","Substitute",["substitute"],t,Pu(cp(o,s)),{u:Il(s),inside:u.node,a:Vu(u.a),v:i}),...r.steps,e.step("integrate.back","Substitute back",["substitute"],r.node,l,{u:Il(s),inside:u.node})]}}}const c=function(e,t,n,r){const{num:s,den:i}=af(n);if(!Dh(i,r))return null;const o=Wh(Ph(s,r)),a=Wh(Ph(i,r));if(!o||!a||a.length<2)return null;const l=Bu(Il(r)),u=e=>Uh(e,r);if(o.length>=a.length){const{q:n,r:s}=Jh(o,a),i=cp(Vu($u([u(n),Lu(u(s),u(a))])),Il(r));return{node:i,steps:[e.step("integrate.divide","Divide the polynomials",["divide"],t,i,{})]}}const{roots:c,rest:h}=Xh(a),f=new Set(c.map(String)).size===c.length,p=3===h.length&&h[1].mul(h[1]).sub(Jl.of(4).mul(h[0]).mul(h[2])).sign<0;if(!f||1!==h.length&&!p||!c.length&&!p)return null;const m=(e=>e.length<=1?[Jl.ZERO]:e.slice(1).map((e,t)=>e.mul(Jl.of(t+1))))(a),d=c.map(e=>Hh(o,e).div(Hh(m,e))),g=c.map((e,t)=>Lu(au(d[t]),$u([l,au(e.neg())])));if(!p){const n=cp(Vu($u(g)),Il(r));return{node:n,steps:[e.step("integrate.partial-fractions","Partial fractions",["partial-fractions"],t,n,{})]}}let v=o;c.forEach((e,t)=>{v=wp(v,yp(Jh(a,[e.neg(),Jl.of(1)]).q,d[t]))});const b=c.reduce((e,t)=>bp(e,[t.neg(),Jl.of(1)]),[Jl.of(1)]),{q:y}=Jh(v,b),[w,x]=[y[0]??Jl.ZERO,y[1]??Jl.ZERO],[$,k,q]=Jh(a,b).q,M=Jl.of(4).mul(q).mul($).sub(k.mul(k)),A=Uh([$,k,q],r),S=x.div(Jl.of(2).mul(q)),N=w.sub(x.mul(k).div(Jl.of(2).mul(q))),O=Tl("sqrt",[pp(M)]),E=Tl("*",[pp(S),Tl("ln",[Tl("abs",[Vu(A)])])]),I=Tl("*",[Tl("/",[Tl("*",[mp(2),pp(N)]),O]),Tl("arctan",[Tl("/",[Vu(Uh([k,q.mul(Jl.of(2))],r)),O])])]),z=g.length?cp(Vu($u(g)),Il(r)):mp(0),_=Pu(Tl("+",[Tl("+",[z,E]),I]));return{node:_,steps:[e.step("integrate.complete-square","Complete the square",["partial-fractions"],t,_,{Q:Vu(A)})]}}(e,t,o,i);if(c)return c;const h=vp(e,t,i);if(h)return h;const f=function(e,t,n,r){if(r>=3)return null;const[s,i]=t.args,o="u"===n?"t":"u",a=new Set;for(const{node:i}of Wl(s,"pre")){if(i===s||!Fl(i)||i.s===s.s||a.has(i.s)||!Qu(i).has(n)||["der","int"].includes(i.op))continue;let l,u,c;a.add(i.s);try{l=Pu(e.differentiate(i,n))}catch{continue}if(Ll(l)&&0===Number(l.value))continue;try{u=xp(Pu(Tl("/",[s,l])),i,Il(o))}catch{continue}if(Qu(u).has(n))continue;try{c=hp(e,Pu(u),o,r+1)}catch{continue}const h=Pu(gf(c.node,o,i));return{node:h,steps:[e.step("integrate.u-substitution","Substitute",["substitute"],t,Pu(cp(u,o)),{u:Il(o),inside:i,du:l,v:n}),...c.steps,e.step("integrate.back","Substitute back",["substitute"],c.node,h,{u:Il(o),inside:i})]}}return null}(e,t,i,n);return f||function(e,t,n,r,s){if(s>=6)return null;const i=Ju(n),o=i.filter(e=>$p(e,r)||!Dh(e,r)),a=i.filter(e=>!o.includes(e));if(1!==a.length)return null;const l=qu(o),u=a[0],c=Vu(u),h=Fl(c)?c.op:"",f=["ln","arctan","arcsin","arccos","arcsec","arccsc","arccot"];if(!Dh(l,r)&&!f.includes(h))return null;let p,m,d;f.includes(h)?(p=u,m=l):(p=l,m=u);try{d=hp(e,Vu(m),r,s+1)}catch{return null}const g=Bu(e.differentiate(Vu(p),r)),v=qu([p,Bu(d.node)]),b=cp(Vu(qu([g,Bu(d.node)])),Il(r)),y=Pu(Tl("-",[Vu(v),b]));return{node:y,steps:[e.step("integrate.parts","Integration by parts",["parts"],t,y,{u:Vu(p),dv:Vu(m),V:d.node,du:Vu(g),v:r})]}}(e,t,o,i,n)}const pp=e=>Vu(au(e)),mp=e=>zl(String(e));function dp(e,t){if(!e||!Qu(e).has(t))return null;const n=Ph(Bu(e),t);if(!n||1!==Math.max(...n.keys()))return null;const r=n.get(1);return!hu(r)||r.q.isZero?null:{a:r.q,node:e}}function gp(e){return Fl(e)&&"^"===e.op&&Ll(e.args[1])&&Number.isInteger(Number(e.args[1].value))?{base:e.args[0],n:Number(e.args[1].value)}:{base:e,n:1}}function vp(e,t,n){const[r,s]=t.args,i=Ju(Bu(r)).map(Vu).map(gp),o=(e,...t)=>Fl(e.base)&&t.includes(e.base.op),a=(r,s,i,o={})=>({node:i,steps:[e.step(r,s,["rewrite"],t,i,{v:n,...o})]});if(2===i.length&&i.every(e=>1===e.n)){const e=i.find(e=>Fl(e.base)&&"^"===e.base.op&&"sym"===e.base.args[0].type&&"e"===e.base.args[0].token),t=i.find(e=>o(e,"sin","cos")),r=e&&dp(e.base.args[1],n),s=t&&dp(t.base.args[0],n);if(r&&s){const[n,i]=[r.a,s.a],o=n.mul(n).add(i.mul(i)),[l,u]=[Tl("sin",[s.node]),Tl("cos",[s.node])],c="sin"===t.base.op?Tl("-",[Tl("*",[pp(n),l]),Tl("*",[pp(i),u])]):Tl("+",[Tl("*",[pp(n),u]),Tl("*",[pp(i),l])]);return a("integrate.parts-twice","By parts twice",Pu(Tl("/",[Tl("*",[e.base,c]),pp(o)])),{e:e.base,t:t.base})}}if(2===i.length&&i.every(e=>1===e.n&&o(e,"sin","cos")&&dp(e.base.args[0],n))&&i[0].base.args[0].s!==i[1].base.args[0].s){const[e,t]="sin"===i[0].base.op?i:[i[1],i[0]],[n,r]=[e.base.args[0],t.base.args[0]],o=(e,t)=>Tl(e,[Tl(t,[n,r])]);let l;l="sin"===e.base.op&&"cos"===t.base.op?Tl("+",[o("sin","+"),o("sin","-")]):"cos"===e.base.op?Tl("+",[o("cos","-"),o("cos","+")]):Tl("-",[o("cos","-"),o("cos","+")]);return a("integrate.product-to-sum","Product to sum",Pu(cp(Tl("/",[l,mp(2)]),s)))}const l=i.find(e=>o(e,"sin")),u=i.find(e=>o(e,"cos")),c=!l||!u||l.base.args[0].s===u.base.args[0].s;if((l||u)&&c&&i.every(e=>e===l||e===u)&&[l,u].every(e=>!e||e.n>=0))for(const[t,r]of[[u,"sin"],[l,"cos"]]){if(!t||t.n<3||t.n%2==0)continue;const o=t.base.args[0],l=(t.n-1)/2,u=i.filter(e=>e!==t).map(e=>Tl("^",[e.base,mp(e.n)])),c=[...u,Tl("^",[Tl("-",[mp(1),Tl("^",[Tl(r,[o]),mp(2)])]),mp(l)]),Tl(t.base.op,[o])].reduce((e,t)=>Tl("*",[e,t])),h=Pu(cp(c,s)),f=a("integrate.odd-power","An odd power",h,{f:t.base,other:Tl(r,[o])});if("sym"!==o.type||o.token!==n)return f;const p="u"===n?"t":"u",m=u.length?i.find(e=>e!==t).n:0;if(2*l+m>100)throw new Vl(`a power this high (${t.n+m}) is not integrated here`);const d="sin"===t.base.op?-1:1,g=Tl(r,[o]),v=Tl("*",[Tl("^",[Tl("-",[mp(1),Tl("^",[Il(p),mp(2)])]),mp(l)]),Tl("^",[Il(p),mp(m)])]),b=Pu(cp(d<0?Tl("neg",[v]):v,Il(p))),y=Ph(Rh(Bu(v)),p);if(!y)return f;const w=[...y].map(([e,t])=>Tl("*",[Vu(t),Tl("/",[Tl("^",[g,mp(e+1)]),mp(e+1)])])).reduce((e,t)=>Tl("+",[e,t])),x=Pu(d<0?Tl("neg",[w]):w);return{node:x,steps:[...f.steps,e.step("integrate.u-substitution","Substitute",["substitute"],h,b,{u:Il(p),inside:g,du:d<0?Tl("neg",[t.base]):t.base,v:n}),e.step("integrate.back","Back to "+n,["substitute"],b,x,{u:Il(p),inside:g})]}}if(1===i.length&&i[0].n>=3&&o(i[0],"sec","csc")&&"sym"===i[0].base.args[0].type&&i[0].base.args[0].token===n){const{base:e,n:t}=i[0],n=e.args[0],r="sec"===e.op?Tl("tan",[n]):Tl("cot",[n]),o=Tl("/",[Tl("*",[Tl("^",[e,mp(t-2)]),r]),mp(t-1)]),l=Tl("*",[Tl("/",[mp(t-2),mp(t-1)]),cp(Tl("^",[e,mp(t-2)]),s)]);return a("integrate.reduction","Reduction formula",Pu(Tl("+",["sec"===e.op?o:Tl("neg",[o]),l])),{f:e,n:mp(t)})}const h=e=>{if(!Fl(e)||"sqrt"!==e.op)return null;const t=Ph(Bu(e.args[0]),n);if(!t||2!==t.size||!t.has(2)||!t.has(0))return null;const[r,s]=[t.get(2),t.get(0)];return!hu(r)||!hu(s)||r.q.sign>=0||s.q.sign<=0?null:{k:r.q.neg(),c:s.q,root:e}},f=Il(n),p=e=>Tl("sqrt",[pp(e)]),m=h(r),d=Fl(r)&&"/"===r.op&&Ll(r.args[0])&&1===r.args[0].value?h(r.args[1]):null;if(m||d){const{k:e,c:t,root:n}=m??d,r=Tl("arcsin",[Tl("*",[f,p(e.div(t))])]);return a("integrate.trig-substitution","A trig substitution",Pu(m?Tl("+",[Tl("/",[Tl("*",[f,n]),mp(2)]),Tl("*",[Tl("/",[pp(t),Tl("*",[mp(2),p(e)])]),r])]):Tl("/",[r,p(e)])),{x:f,a:Pu(p(t.div(e)))})}return null}const bp=(e,t)=>{const n=Array.from({length:e.length+t.length-1},()=>Jl.ZERO);return e.forEach((e,r)=>t.forEach((t,s)=>{n[r+s]=n[r+s].add(e.mul(t))})),n},yp=(e,t)=>e.map(e=>e.mul(t)),wp=(e,t)=>Array.from({length:Math.max(e.length,t.length)},(n,r)=>(e[r]??Jl.ZERO).sub(t[r]??Jl.ZERO));function xp(e,t,n){return e.s===t.s?n:Fl(e)?Tl(e.op,e.args.map(e=>xp(e,t,n))):e}const $p=(e,t)=>{const n=Ph(e,t);return Boolean(n)&&[...n.values()].every(e=>!Dh(e,t))&&Math.max(...n.keys())>=1};function kp(e,t,n,r,s,i){if([r,s].some(e=>Jf(e).inf))return function(e,t,n,r,s,i){const o=[r,s].map(e=>Jf(e)),a=e=>e.inf?e.inf*(1/0):vh(e.fin,{digits:20}).number,[l,u]=o.map(a).sort((e,t)=>e-t);for(const t of i?qp(i,n):[]){let r=[];try{r=e.solve(Tl("=",[t,zl("0")]),n,{steps:!1}).solutions}catch{continue}for(const t of r){const r=vh(t,{digits:20});if(Number.isFinite(r.number)&&!r.im&&r.number>l&&r.number<u)throw new Vl(`the integrand has no value at ${n} = ${e.format(t)}, between the limits: split the integral there`)}}const c=(r,s,i)=>{if(!s.inf)try{const e=Pu(gf(t,n,r));if(Number.isFinite(vh(e,{digits:15}).number))return e}catch{}const o=e.limit(t,n,r,{steps:!1,side:s.inf?void 0:i});if(!o.exists)throw new Vl(`the integral diverges: as ${n} → ${e.format(r)}, ${e.format(t)} has no limit (${o.reason})`);if(o.infinite)throw new Vl(`the integral diverges: as ${n} → ${e.format(r)}, ${e.format(t)} goes to ${o.text}`);return o.result},h=a(o[0])<a(o[1]),[f,p]=[c(r,o[0],h?"right":"left"),c(s,o[1],h?"left":"right")],m=Pu(Tl("-",[p,f])),d=Tl("-",[p,f]);return{value:m,step:e.step("integrate.improper","Limits at the ends",["evaluate"],t,d,{a:r,b:s,F:t,v:n})}}(e,t,n,r,s,i);if(i&&!Qu(r).size&&!Qu(s).size){const o=vh(r,{digits:20}).number,a=vh(s,{digits:20}).number,l=[...Qu(i)].filter(e=>e!==n);if(!l.length){const[r,s]=o<=a?[o,a]:[a,o];for(const o of qp(i,n)){let i=[];try{i=e.solve(Tl("=",[o,zl("0")]),n,{steps:!1}).solutions}catch{continue}for(const o of i){const i=vh(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 Vl(`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=vh(Pu(gf(t,n,o)),{digits:15}).number}catch{}if(!Number.isFinite(a))throw new Vl(`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=vh(gf(i,n,zl(t.toFixed(15))),{digits:15}).number;if(!Number.isFinite(e))throw new Vl("not finite")}catch(e){throw new Vl(`the integrand has no value at ${n} = ${t.toPrecision(6)}, between the limits, so F(b) - F(a) would be wrong`)}}}const o=e=>Pu(gf(t,n,e)),a=Pu(Tl("-",[o(s),o(r)])),l=Tl("-",[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})}}function qp(e,t){const n=[],r={tan:"cos",sec:"cos",csc:"sin",cot:"sin"};return Wl(e,"pre").forEach(({node:e})=>{if(!Fl(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&&Fl(e.args[1])&&"neg"===e.args[1].op?s=e.args[0]:r[e.op]&&(s=Tl(r[e.op],[e.args[0]])),s&&Qu(s).has(t)&&!n.some(e=>e.s===s.s)&&n.push(s)}),n}const Mp={"=":1,"≠":1,"<":1,">":1,"≤":1,"≥":1,"+":2,"-":2,"±":2,"*":3,"/":3,neg:4,pm:4,"^":5},Ap={pi:"π","≤":"≤","≥":"≥"};function Sp(e){return zp(e).text}function Np(e,t,n=!1){return e.prec<t||n&&e.prec===t?`(${e.text})`:e.text}const Op=e=>"op"===e.type?e.op:null,Ep=e=>e.text.startsWith("-"),Ip={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]};function zp(e){if("num"===e.type)return{text:e.token,prec:e.token.startsWith("-")?4:9};if("sym"===e.type)return{text:Ap[e.token]??e.token,prec:9};const t=e.args.map(zp),n=Mp[e.op];switch(e.op){case"+":case"-":case"±":{const r="+"===e.op&&["+","-"].includes(Op(e.args[1])),s=Ep(t[1])?`(${t[1].text})`:r?t[1].text:Np(t[1],n,!0);return{text:`${Np(t[0],n)} ${"±"===e.op?"±":e.op} ${s}`,prec:n}}case"*":{const r=Np(t[0],n),s=Ep(t[1])?`(${t[1].text})`:"*"===Op(e.args[1])?t[1].text:Np(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:`${Np(t[0],n)}/${Np(t[1],n,!0)}`,prec:n};case"^":return{text:`${Np(t[0],n+1)}^${Np(t[1],n)}`,prec:n};case"neg":return{text:`-${Np(t[0],3)}`,prec:4};case"pm":return{text:`±${Np(t[0],4)}`,prec:4};case"!":return{text:`${Np(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:`${Np(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:`${Ip[e.op][0]}${t.map(e=>e.text).join(", ")}${Ip[e.op][1]}`,prec:9};case"&":return{text:`${t[0].text} and ${t[1].text}`,prec:0};default:return void 0!==n?{text:`${Np(t[0],n)} ${e.op} ${Np(t[1],n,!0)}`,prec:n}:{text:`${e.op.replace(/^\\:?/,"")}(${t.map(e=>e.text).join(", ")})`,prec:9}}}const _p=['name: Differentiation\n\n# `u v der` means d(u)/dv (MathZetta\'s postfix: mathzetta/docs/postfix.md). Every rule here rewrites one derivative into smaller\n# derivatives, so differentiating always terminates: the expressions sitting\n# under a `D` get strictly smaller at every step.\n#\n# The variable is a slot, not a fixed letter, so these rules work for d/dx,\n# d/dt or anything else. That is what freeOf and dependsOn are for: they ask\n# whether one operand mentions whatever the variable slot bound to.\n#\n# Where two rules share a structure key, requirements keep them apart and\n# priority picks the one that reads better. The constant-multiple rule outranks\n# the product rule for exactly that reason.\n\nrules:\n # ---- the two base cases ----------------------------------------------\n - id: d-constant\n name: Derivative of a constant\n mode: differentiate\n pattern: c v der\n require:\n - [freeOf, c, v]\n output: "0"\n priority: 10\n explain: "{c} does not change when {v} changes, so its rate of change is 0."\n tags: [base]\n\n - id: d-variable\n name: Derivative of the variable\n mode: differentiate\n pattern: u v der\n require:\n - [sameAs, u, v]\n output: "1"\n priority: 10\n explain: "{v} changes exactly as fast as itself, so the rate is 1."\n tags: [base]\n\n # ---- splitting a derivative into smaller ones ------------------------\n - id: d-sum\n name: Sum rule\n mode: differentiate\n pattern: u w + v der\n output: u v der w v der +\n explain: "Differentiate {u} and {w} separately, then add the two results."\n tags: [split]\n\n - id: d-difference\n name: Difference rule\n mode: differentiate\n pattern: u w - v der\n output: u v der w v der -\n explain: "Differentiate {u} and {w} separately, then subtract the second from the first."\n tags: [split]\n\n - id: d-negate\n name: Derivative of a negative\n mode: differentiate\n pattern: u neg v der\n output: u v der neg\n explain: "The minus sign just carries through to the derivative of {u}."\n tags: [split]\n\n - id: d-constant-multiple\n name: Constant multiple rule\n mode: differentiate\n pattern: c u * v der\n commutative: true\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n output: c u v der *\n priority: 5\n explain: "{c} is only a scale factor, so it comes along unchanged while {u} is differentiated."\n tags: [split]\n\n - id: d-constant-divisor\n name: Dividing by a constant\n mode: differentiate\n pattern: u c / v der\n require:\n - [freeOf, c, v]\n output: u v der c /\n priority: 5\n explain: "Dividing by {c} is only a scale factor, so differentiate {u} and keep the division."\n tags: [split]\n\n - id: d-product\n name: Product rule\n mode: differentiate\n pattern: u w * v der\n require:\n - [dependsOn, u, v]\n - [dependsOn, w, v]\n output: u v der w * u w v der * +\n explain: "Differentiate {u} and keep {w}, then keep {u} and differentiate {w}, and add the two."\n tags: [split]\n\n - id: d-quotient\n name: Quotient rule\n mode: differentiate\n pattern: u w / v der\n output: u v der w * u w v der * - w 2 ^ /\n explain: "Bottom times the derivative of the top, minus top times the derivative of the bottom, all over {w} squared."\n tags: [split]\n\n # ---- powers -----------------------------------------------------------\n - id: d-power-of-variable\n name: Power rule\n mode: differentiate\n pattern: u n ^ v der\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n output: n u n 1 - ^ *\n fold: true\n priority: 6\n explain: "Bring the {n} down in front and drop the power by one."\n tags: [power]\n\n - id: d-power-chain\n name: Power rule with the chain rule\n mode: differentiate\n pattern: u n ^ v der\n require:\n - [freeOf, n, v]\n - [dependsOn, u, v]\n output: n u n 1 - ^ * u v der *\n fold: true\n explain: "Bring the {n} down and drop the power by one, then multiply by the derivative of {u}."\n tags: [power, chain]\n\n - id: d-exponential-base\n name: Derivative of a constant to a power\n mode: differentiate\n pattern: a u ^ v der\n require:\n - [freeOf, a, v]\n - [dependsOn, u, v]\n output: a u ^ a ln * u v der *\n explain: "A constant base gives itself back, multiplied by the natural log of {a} and the derivative of {u}."\n tags: [power, chain]\n\n # ---- the standard functions, each with its chain-rule factor ---------\n # e^u is `=e u ^`: the base is the literal symbol e. Outranks the general\n # a^u rule (which would give e^u · ln e · u\').\n - id: d-exp\n name: Derivative of e to a power\n mode: differentiate\n pattern: =e u ^ v der\n require:\n - [dependsOn, u, v]\n output: =e u ^ u v der *\n priority: 7\n explain: "e to a power is its own derivative, times the derivative of {u}."\n tags: [chain]\n\n - id: d-ln\n name: Derivative of a natural log\n mode: differentiate\n pattern: u ln v der\n output: u v der u /\n explain: "The derivative of {u} over {u} itself."\n tags: [chain]\n\n - id: d-sqrt\n name: Derivative of a square root\n mode: differentiate\n pattern: u sqrt v der\n output: u v der 2 u sqrt * /\n explain: "The derivative of {u}, over twice the square root of {u}."\n tags: [chain]\n\n - id: d-sin\n name: Derivative of sine\n mode: differentiate\n pattern: u sin v der\n output: u cos u v der *\n explain: "Sine differentiates to cosine, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-cos\n name: Derivative of cosine\n mode: differentiate\n pattern: u cos v der\n output: u sin u v der * neg\n explain: "Cosine differentiates to minus sine, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-tan\n name: Derivative of tangent\n mode: differentiate\n pattern: u tan v der\n output: u v der u cos 2 ^ /\n explain: "The derivative of {u}, over cosine squared of {u}."\n tags: [chain, trig]\n\n # ---- the rest of the standard functions -----------------------------\n - id: d-csc\n name: Derivative of cosecant\n mode: differentiate\n pattern: u csc v der\n output: u csc u cot * u v der * neg\n explain: "Cosecant differentiates to minus cosecant times cotangent, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-sec\n name: Derivative of secant\n mode: differentiate\n pattern: u sec v der\n output: u sec u tan * u v der *\n explain: "Secant differentiates to secant times tangent, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-cot\n name: Derivative of cotangent\n mode: differentiate\n pattern: u cot v der\n output: u v der u sin 2 ^ / neg\n explain: "Minus the derivative of {u}, over sine squared of {u}."\n tags: [chain, trig]\n\n - id: d-arcsin\n name: Derivative of arcsine\n mode: differentiate\n pattern: u arcsin v der\n output: u v der 1 u 2 ^ - sqrt /\n explain: "The derivative of {u}, over the square root of 1 minus {u} squared."\n tags: [chain, trig]\n\n - id: d-arccos\n name: Derivative of arccosine\n mode: differentiate\n pattern: u arccos v der\n output: u v der 1 u 2 ^ - sqrt / neg\n explain: "Minus the derivative of {u}, over the square root of 1 minus {u} squared."\n tags: [chain, trig]\n\n - id: d-arctan\n name: Derivative of arctangent\n mode: differentiate\n pattern: u arctan v der\n output: u v der 1 u 2 ^ + /\n explain: "The derivative of {u}, over 1 plus {u} squared."\n tags: [chain, trig]\n\n - id: d-arcsec\n name: Derivative of arcsecant\n mode: differentiate\n pattern: u arcsec v der\n output: u v der u abs u 2 ^ 1 - sqrt * /\n explain: "The derivative of {u}, over the absolute value of {u} times the square root of {u} squared minus 1."\n tags: [chain, trig]\n\n - id: d-arccsc\n name: Derivative of arccosecant\n mode: differentiate\n pattern: u arccsc v der\n output: u v der u abs u 2 ^ 1 - sqrt * / neg\n explain: "Minus the derivative of {u}, over the absolute value of {u} times the square root of {u} squared minus 1."\n tags: [chain, trig]\n\n - id: d-arccot\n name: Derivative of arccotangent\n mode: differentiate\n pattern: u arccot v der\n output: u v der 1 u 2 ^ + / neg\n explain: "Minus the derivative of {u}, over 1 plus {u} squared."\n tags: [chain, trig]\n\n - id: d-sinh\n name: Derivative of hyperbolic sine\n mode: differentiate\n pattern: u sinh v der\n output: u cosh u v der *\n explain: "Hyperbolic sine differentiates to hyperbolic cosine, times the derivative of {u}."\n tags: [chain, hyperbolic]\n\n - id: d-cosh\n name: Derivative of hyperbolic cosine\n mode: differentiate\n pattern: u cosh v der\n output: u sinh u v der *\n explain: "Hyperbolic cosine differentiates to hyperbolic sine — no minus sign, unlike cosine — times the derivative of {u}."\n tags: [chain, hyperbolic]\n\n - id: d-tanh\n name: Derivative of hyperbolic tangent\n mode: differentiate\n pattern: u tanh v der\n output: u v der u cosh 2 ^ /\n explain: "The derivative of {u}, over hyperbolic cosine squared of {u}."\n tags: [chain, hyperbolic]\n\n - id: d-arcsinh\n name: Derivative of inverse hyperbolic sine\n mode: differentiate\n pattern: u arcsinh v der\n output: u v der u 2 ^ 1 + sqrt /\n explain: "The derivative of {u}, over the square root of {u} squared plus 1."\n tags: [chain, hyperbolic]\n\n - id: d-arccosh\n name: Derivative of inverse hyperbolic cosine\n mode: differentiate\n pattern: u arccosh v der\n output: u v der u 2 ^ 1 - sqrt /\n explain: "The derivative of {u}, over the square root of {u} squared minus 1."\n tags: [chain, hyperbolic]\n\n - id: d-arctanh\n name: Derivative of inverse hyperbolic tangent\n mode: differentiate\n pattern: u arctanh v der\n output: u v der 1 u 2 ^ - /\n explain: "The derivative of {u}, over 1 minus {u} squared."\n tags: [chain, hyperbolic]\n\n # log base a: `a u log` in MathZetta\'s postfix\n - id: d-log\n name: Derivative of a logarithm\n mode: differentiate\n pattern: a u log v der\n require:\n - [freeOf, a, v]\n output: u v der u a ln * /\n explain: "The derivative of {u}, over {u} times the natural log of {a}."\n tags: [chain]\n\n - id: d-abs\n name: Derivative of an absolute value\n mode: differentiate\n pattern: u abs v der\n output: u u abs / u v der *\n explain: "The absolute value keeps the sign of {u}: {u} over its absolute value, times the derivative of {u}."\n tags: [chain]\n\n # n-th root: `n u root`\n - id: d-root\n name: Derivative of a root\n mode: differentiate\n pattern: n u root v der\n require:\n - [freeOf, n, v]\n output: u v der n n u root n 1 - ^ * /\n fold: true\n explain: "The derivative of {u}, over {n} times the {n}th root of {u} to the power {n} minus 1."\n tags: [chain]\n','name: More derivatives\n\n# Derivative rules the CAS adds to rules/calculus.yaml (which calcvidnew also uses).\n\nrules:\n - id: d-general-power\n name: A power with the variable in both places\n mode: differentiate\n pattern: u w ^ v der\n require:\n - [dependsOn, u, v]\n - [dependsOn, w, v]\n output: u w ^ w v der u ln * w u v der * u / + *\n explain: "Write {u}^{w} as e^({w} ln {u}) and use the chain rule: the derivative is {u}^{w} times the derivative of {w} ln {u}."\n tags: [chain]\n','name: Integrals\n\n# mode: integrate. `f v 2 int` is ∫ f dv (MathZetta\'s postfix; the 2 counts f and v).\n# Each rule turns one integral into smaller ones, or into an answer. The CAS also\n# tries, when no rule fits: multiplying out, a linear substitution (∫ f(ax + b) dx\n# from the rule for ∫ f(u) du), and integration by parts for polynomial × e^, sin,\n# cos, ln, arctan. Definite integrals are the antiderivative between the limits.\n#\n# Patterns see the normal form: 1/x is "1 x /", x^-2 is "1 x 2 ^ /", √x is "x sqrt",\n# 1/√(1 - x²) is "1 x 2 ^ neg 1 + sqrt /".\n\nrules:\n # ---- splitting -----------------------------------------------------------\n - id: i-sum\n name: Sum rule\n mode: integrate\n pattern: u w + v 2 int\n output: u v 2 int w v 2 int +\n explain: "Integrate {u} and {w} separately, and add."\n tags: [split]\n\n - id: i-difference\n name: Difference rule\n mode: integrate\n pattern: u w - v 2 int\n output: u v 2 int w v 2 int -\n explain: "Integrate {u} and {w} separately, and subtract."\n tags: [split]\n\n - id: i-negate\n name: A minus sign\n mode: integrate\n pattern: u neg v 2 int\n output: u v 2 int neg\n explain: "The minus sign comes out of the integral."\n tags: [split]\n\n - id: i-constant-multiple\n name: Constant multiple\n mode: integrate\n pattern: c u * v 2 int\n commutative: true\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n output: c u v 2 int *\n priority: 5\n explain: "{c} doesn\'t change with {v}, so it comes out of the integral."\n tags: [split]\n\n - id: i-constant-divisor\n name: Dividing by a constant\n mode: integrate\n pattern: u c / v 2 int\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n output: u v 2 int c /\n priority: 5\n explain: "Dividing by {c} comes out of the integral."\n tags: [split]\n\n - id: i-constant-over\n name: A constant over something\n mode: integrate\n pattern: c u / v 2 int\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n when:\n c: [notOne]\n output: c 1 u / v 2 int *\n priority: 4\n explain: "{c} comes out of the integral, leaving ∫ 1/{u}."\n tags: [split]\n\n # ---- the table -----------------------------------------------------------\n - id: i-constant\n name: Integral of a constant\n mode: integrate\n pattern: c v 2 int\n require:\n - [freeOf, c, v]\n output: c v *\n priority: 10\n explain: "A constant {c} integrates to {c}·{v}."\n tags: [base]\n\n - id: i-variable\n name: Integral of the variable\n mode: integrate\n pattern: u v 2 int\n require:\n - [sameAs, u, v]\n output: v 2 ^ 2 /\n priority: 10\n explain: "∫ {v} d{v} = {v}²/2."\n tags: [base]\n\n - id: i-power\n name: Power rule\n mode: integrate\n pattern: u n ^ v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n when:\n n: [notMinusOne]\n output: v n 1 + ^ n 1 + /\n explain: "Add 1 to the power and divide by the new power: {result}."\n tags: [power]\n\n - id: i-reciprocal\n name: Integral of 1/x\n mode: integrate\n pattern: 1 u / v 2 int\n require:\n - [sameAs, u, v]\n output: v abs ln\n explain: "∫ 1/{v} d{v} = ln|{v}| (the power rule can\'t divide by 0 here)."\n tags: [log]\n\n - id: i-reciprocal-power\n name: Power rule (a power below)\n mode: integrate\n pattern: 1 u n ^ / v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n when:\n n: [notOne]\n output: v 1 n - ^ 1 n - /\n explain: "1/{v}^{n} is {v}^(-{n}): add 1 to the power and divide by it."\n tags: [power]\n\n - id: i-sqrt\n name: Integral of a square root\n mode: integrate\n pattern: u sqrt v 2 int\n require:\n - [sameAs, u, v]\n output: 2 v 3 2 / ^ * 3 /\n explain: "√{v} is {v}^(1/2): add 1 to the power and divide by 3/2."\n tags: [power]\n\n - id: i-reciprocal-sqrt\n name: Integral of 1/√x\n mode: integrate\n pattern: 1 u sqrt / v 2 int\n require:\n - [sameAs, u, v]\n output: 2 v sqrt *\n explain: "1/√{v} is {v}^(-1/2): add 1 to the power and divide by 1/2."\n tags: [power]\n\n - id: i-root\n name: Integral of a root\n mode: integrate\n pattern: n u root v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n output: v 1 n / 1 + ^ 1 n / 1 + /\n explain: "The {n}th root of {v} is {v}^(1/{n}): add 1 to the power and divide by it."\n tags: [power]\n\n - id: i-exp\n name: Integral of e^x\n mode: integrate\n pattern: =e u ^ v 2 int\n require:\n - [sameAs, u, v]\n output: =e v ^\n explain: "e^{v} is its own integral."\n tags: [exp]\n\n - id: i-exponential\n name: Integral of a^x\n mode: integrate\n pattern: a u ^ v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, a, v]\n output: a v ^ a ln /\n explain: "∫ {a}^{v} d{v} = {a}^{v} / ln {a}."\n tags: [exp]\n\n - id: i-ln\n name: Integral of ln x\n mode: integrate\n pattern: u ln v 2 int\n require:\n - [sameAs, u, v]\n output: v v ln * v -\n explain: "By parts: ∫ ln {v} d{v} = {v} ln {v} - {v}."\n tags: [log]\n\n - { id: i-sin, name: Integral of sin, mode: integrate, pattern: u sin v 2 int, require: [[sameAs, u, v]], output: v cos neg, tags: [trig], explain: "The derivative of -cos {v} is sin {v}." }\n - { id: i-cos, name: Integral of cos, mode: integrate, pattern: u cos v 2 int, require: [[sameAs, u, v]], output: v sin, tags: [trig], explain: "The derivative of sin {v} is cos {v}." }\n - { id: i-tan, name: Integral of tan, mode: integrate, pattern: u tan v 2 int, require: [[sameAs, u, v]], output: v cos abs ln neg, tags: [trig], explain: "tan = sin/cos, and -ln|cos {v}| differentiates to it." }\n - { id: i-sec-squared, name: Integral of sec², mode: integrate, pattern: 1 u cos 2 ^ / v 2 int, require: [[sameAs, u, v]], output: v tan, tags: [trig], explain: "The derivative of tan {v} is 1/cos²{v}." }\n - { id: i-sec-squared-written, name: Integral of sec², mode: integrate, pattern: u sec 2 ^ v 2 int, require: [[sameAs, u, v]], output: v tan, tags: [trig], explain: "The derivative of tan {v} is sec²{v}." }\n - { id: i-csc-squared, name: Integral of csc², mode: integrate, pattern: 1 u sin 2 ^ / v 2 int, require: [[sameAs, u, v]], output: v cot neg, tags: [trig], explain: "The derivative of -cot {v} is 1/sin²{v}." }\n - { id: i-sin-squared, name: Integral of sin², mode: integrate, pattern: u sin 2 ^ v 2 int, require: [[sameAs, u, v]], output: v 2 / 2 v * sin 4 / -, tags: [trig], explain: "sin²{v} = (1 - cos 2{v})/2, which integrates term by term." }\n - { id: i-cos-squared, name: Integral of cos², mode: integrate, pattern: u cos 2 ^ v 2 int, require: [[sameAs, u, v]], output: v 2 / 2 v * sin 4 / +, tags: [trig], explain: "cos²{v} = (1 + cos 2{v})/2, which integrates term by term." }\n - { id: i-sec, name: Integral of sec, mode: integrate, pattern: u sec v 2 int, require: [[sameAs, u, v]], output: v sec v tan + abs ln, tags: [trig], explain: "The derivative of ln|sec {v} + tan {v}| is sec {v}." }\n - { id: i-csc, name: Integral of csc, mode: integrate, pattern: u csc v 2 int, require: [[sameAs, u, v]], output: v csc v cot + abs ln neg, tags: [trig], explain: "The derivative of -ln|csc {v} + cot {v}| is csc {v}." }\n - { id: i-cot, name: Integral of cot, mode: integrate, pattern: u cot v 2 int, require: [[sameAs, u, v]], output: v sin abs ln, tags: [trig], explain: "cot = cos/sin, and ln|sin {v}| differentiates to it." }\n - { id: i-sec-tan, name: Integral of sec·tan, mode: integrate, pattern: u sec u tan * v 2 int, commutative: true, require: [[sameAs, u, v]], output: v sec, tags: [trig], explain: "The derivative of sec {v} is sec {v} tan {v}." }\n - { id: i-csc-cot, name: Integral of csc·cot, mode: integrate, pattern: u csc u cot * v 2 int, commutative: true, require: [[sameAs, u, v]], output: v csc neg, tags: [trig], explain: "The derivative of -csc {v} is csc {v} cot {v}." }\n - { id: i-sinh, name: Integral of sinh, mode: integrate, pattern: u sinh v 2 int, require: [[sameAs, u, v]], output: v cosh, tags: [trig], explain: "The derivative of cosh {v} is sinh {v}." }\n - { id: i-cosh, name: Integral of cosh, mode: integrate, pattern: u cosh v 2 int, require: [[sameAs, u, v]], output: v sinh, tags: [trig], explain: "The derivative of sinh {v} is cosh {v}." }\n - { id: i-arctan, name: Integral of 1/(1 + x²), mode: integrate, pattern: 1 u 2 ^ 1 + / v 2 int, require: [[sameAs, u, v]], output: v arctan, tags: [trig], explain: "The derivative of arctan {v} is 1/(1 + {v}²)." }\n - { id: i-arcsin, name: Integral of 1/√(1 - x²), mode: integrate, pattern: 1 u 2 ^ neg 1 + sqrt / v 2 int, require: [[sameAs, u, v]], output: v arcsin, tags: [trig], explain: "The derivative of arcsin {v} is 1/√(1 - {v}²)." }\n','name: Values and identities\n\n# The CAS\'s simplify rules (mode: simplify). They see expressions in normal form\n# (src/cas/form.js), as drawn: x/2, 2x - 3, -x, √x is "x sqrt",\n# ∛x is "3 x root", π/6 is "=pi 6 /", 2π/3 is "2 =pi * 3 /", e^x is "=e x ^".\n#\n# - a word is a slot (u, v, n …); a fixed symbol is written =pi, =e\n# - a number is itself; "1 2 /" is ½\n# - arithmetic (2 + 3, x + x, √8 = 2√2) is done for you before and after every rule\n# - a rule for a sum or product of two parts also fires on any two parts of a longer one\n# - tags pick what a step list shows (steps: \'brief\' hides value, identity, tidy …)\n#\n# To change one: copy it into a file of your own with the same id and edit it;\n# to turn one off: give its id with enabled: false. createCAS({ rules: [yours] }).\n\nrules:\n # ---- logs and exponentials -------------------------------------------\n - id: ln-one\n name: Log of 1\n pattern: 1 ln\n output: "0"\n explain: "e^0 = 1, so ln 1 = 0."\n tags: [value]\n\n - id: ln-e\n name: Log of e\n pattern: =e ln\n output: "1"\n explain: "e^1 = e, so ln e = 1."\n tags: [value]\n\n - id: ln-exp\n name: Log undoes e to a power\n pattern: =e u ^ ln\n output: u\n explain: "ln and e^ undo each other: ln(e^{u}) = {u}."\n tags: [inverse]\n\n - id: exp-ln\n name: e to a power undoes the log\n pattern: =e u ln ^\n output: u\n explain: "e^ and ln undo each other: e^(ln {u}) = {u} (for {u} > 0)."\n tags: [inverse]\n\n - id: exp-multiple-ln\n name: A multiple of a log in a power\n pattern: =e n u ln * ^\n when:\n n: [isRational]\n output: u n ^\n explain: "e^({n} ln {u}) = (e^(ln {u}))^{n} = {result}."\n tags: [inverse]\n\n - id: log-same-base\n name: Log of its own base\n pattern: b b log\n output: "1"\n explain: "{b}^1 = {b}, so the log of {b} to base {b} is 1."\n tags: [value]\n\n - id: log-of-power\n name: Log undoes a power of its base\n pattern: b b u ^ log\n output: u\n explain: "log base {b} and {b}^ undo each other."\n tags: [inverse]\n\n - id: power-of-log\n name: A power undoes the log to its base\n pattern: b b u log ^\n output: u\n explain: "{b}^(log base {b} of {u}) = {u}."\n tags: [inverse]\n\n # ---- roots and absolute value --------------------------------------------\n - id: sqrt-of-square\n name: Square root of a square\n pattern: u 2 ^ sqrt\n output: u abs\n explain: "√({u}²) is the size of {u}, whatever its sign: |{u}|."\n tags: [identity]\n\n - id: abs-squared\n name: Absolute value squared\n pattern: u abs 2 ^\n output: u 2 ^\n explain: "Squaring removes the sign anyway: |{u}|² = {u}²."\n tags: [identity]\n\n - id: abs-of-abs\n name: Absolute value twice\n pattern: u abs abs\n output: u abs\n explain: "|{u}| is never negative, so its absolute value is itself."\n tags: [identity]\n\n - id: abs-positive\n name: Absolute value of a positive number\n pattern: u abs\n when:\n u: [isPositiveConstant]\n output: u\n explain: "{u} is positive, so |{u}| = {u}."\n tags: [value]\n\n - id: abs-negative\n name: Absolute value of a negative number\n pattern: u abs\n when:\n u: [isNegativeConstant]\n output: u neg\n explain: "{u} is negative, so |{u}| = -({u})."\n tags: [value]\n\n - id: abs-of-exp\n name: e to a power is positive\n pattern: =e u ^ abs\n output: =e u ^\n explain: "e to any power is positive, so the absolute value changes nothing."\n tags: [identity]\n\n # ---- trigonometry: signs and turns ---------------------------------------\n - id: sin-odd\n name: Sine of a negative angle\n pattern: u sin\n when:\n u: [hasMinusSign]\n output: u neg sin neg\n explain: "sin(-θ) = -sin θ."\n tags: [symmetry]\n\n - id: cos-even\n name: Cosine of a negative angle\n pattern: u cos\n when:\n u: [hasMinusSign]\n output: u neg cos\n explain: "cos(-θ) = cos θ."\n tags: [symmetry]\n\n - id: tan-odd\n name: Tangent of a negative angle\n pattern: u tan\n when:\n u: [hasMinusSign]\n output: u neg tan neg\n explain: "tan(-θ) = -tan θ."\n tags: [symmetry]\n\n - id: sin-full-turn\n name: A full turn\n pattern: u sin\n when:\n u: [[piMultipleAtLeast, 2]]\n output: u 2 =pi * - sin\n explain: "Turning a full 2π brings you back: sin({u}) = sin({u} - 2π)."\n tags: [symmetry]\n\n - id: cos-full-turn\n name: A full turn\n pattern: u cos\n when:\n u: [[piMultipleAtLeast, 2]]\n output: u 2 =pi * - cos\n explain: "Turning a full 2π brings you back: cos({u}) = cos({u} - 2π)."\n tags: [symmetry]\n\n - id: tan-half-turn\n name: Tangent repeats every π\n pattern: u tan\n when:\n u: [[piMultipleAtLeast, 1]]\n output: u =pi - tan\n explain: "tan repeats every π: tan({u}) = tan({u} - π)."\n tags: [symmetry]\n\n - id: sin-half-turn\n name: A half turn\n pattern: u sin\n when:\n u: [[piMultipleAbove, 1], [piMultipleBelow, 2]]\n output: u =pi - sin neg\n explain: "Half a turn flips the sign: sin({u}) = -sin({u} - π)."\n tags: [symmetry]\n\n - id: cos-half-turn\n name: A half turn\n pattern: u cos\n when:\n u: [[piMultipleAbove, 1], [piMultipleBelow, 2]]\n output: u =pi - cos neg\n explain: "Half a turn flips the sign: cos({u}) = -cos({u} - π)."\n tags: [symmetry]\n\n - id: sin-second-quarter\n name: The second quarter turn\n pattern: u sin\n when:\n u: [[piMultipleAbove, 1/2], [piMultipleAtMost, 1]]\n output: =pi u - sin\n explain: "sin({u}) = sin(π - {u})."\n tags: [symmetry]\n\n - id: cos-second-quarter\n name: The second quarter turn\n pattern: u cos\n when:\n u: [[piMultipleAbove, 1/2], [piMultipleAtMost, 1]]\n output: =pi u - cos neg\n explain: "cos({u}) = -cos(π - {u})."\n tags: [symmetry]\n\n - id: tan-second-quarter\n name: The second quarter turn\n pattern: u tan\n when:\n u: [[piMultipleAbove, 1/2], [piMultipleBelow, 1]]\n output: =pi u - tan neg\n explain: "tan({u}) = -tan(π - {u})."\n tags: [symmetry]\n\n # ---- trigonometry: the standard angles -------------------------------------\n - { id: sin-0, name: Sine of 0, pattern: 0 sin, output: "0", tags: [value], explain: "sin 0 = 0." }\n - { id: sin-pi-6, name: Sine of π/6, pattern: =pi 6 / sin, output: 1 2 /, tags: [value], explain: "sin(π/6) = 1/2." }\n - { id: sin-pi-4, name: Sine of π/4, pattern: =pi 4 / sin, output: 2 sqrt 2 /, tags: [value], explain: "sin(π/4) = √2/2." }\n - { id: sin-pi-3, name: Sine of π/3, pattern: =pi 3 / sin, output: 3 sqrt 2 /, tags: [value], explain: "sin(π/3) = √3/2." }\n - { id: sin-pi-2, name: Sine of π/2, pattern: =pi 2 / sin, output: "1", tags: [value], explain: "sin(π/2) = 1." }\n - { id: sin-pi, name: Sine of π, pattern: =pi sin, output: "0", tags: [value], explain: "sin π = 0." }\n - { id: cos-0, name: Cosine of 0, pattern: 0 cos, output: "1", tags: [value], explain: "cos 0 = 1." }\n - { id: cos-pi-6, name: Cosine of π/6, pattern: =pi 6 / cos, output: 3 sqrt 2 /, tags: [value], explain: "cos(π/6) = √3/2." }\n - { id: cos-pi-4, name: Cosine of π/4, pattern: =pi 4 / cos, output: 2 sqrt 2 /, tags: [value], explain: "cos(π/4) = √2/2." }\n - { id: cos-pi-3, name: Cosine of π/3, pattern: =pi 3 / cos, output: 1 2 /, tags: [value], explain: "cos(π/3) = 1/2." }\n - { id: cos-pi-2, name: Cosine of π/2, pattern: =pi 2 / cos, output: "0", tags: [value], explain: "cos(π/2) = 0." }\n - { id: cos-pi, name: Cosine of π, pattern: =pi cos, output: "-1", tags: [value], explain: "cos π = -1." }\n - { id: tan-0, name: Tangent of 0, pattern: 0 tan, output: "0", tags: [value], explain: "tan 0 = 0." }\n - { id: tan-pi-6, name: Tangent of π/6, pattern: =pi 6 / tan, output: 3 sqrt 3 /, tags: [value], explain: "tan(π/6) = √3/3." }\n - { id: tan-pi-4, name: Tangent of π/4, pattern: =pi 4 / tan, output: "1", tags: [value], explain: "tan(π/4) = 1." }\n - { id: tan-pi-3, name: Tangent of π/3, pattern: =pi 3 / tan, output: 3 sqrt, tags: [value], explain: "tan(π/3) = √3." }\n - { id: arcsin-0, name: Arcsine of 0, pattern: 0 arcsin, output: "0", tags: [value], explain: "sin 0 = 0, so arcsin 0 = 0." }\n - { id: arcsin-half, name: Arcsine of 1/2, pattern: 1 2 / arcsin, output: =pi 6 /, tags: [value], explain: "sin(π/6) = 1/2, so arcsin(1/2) = π/6." }\n - { id: arcsin-1, name: Arcsine of 1, pattern: 1 arcsin, output: =pi 2 /, tags: [value], explain: "sin(π/2) = 1, so arcsin 1 = π/2." }\n - { id: arccos-0, name: Arccosine of 0, pattern: 0 arccos, output: =pi 2 /, tags: [value], explain: "cos(π/2) = 0, so arccos 0 = π/2." }\n - { id: arccos-half, name: Arccosine of 1/2, pattern: 1 2 / arccos, output: =pi 3 /, tags: [value], explain: "cos(π/3) = 1/2, so arccos(1/2) = π/3." }\n - { id: arccos-1, name: Arccosine of 1, pattern: 1 arccos, output: "0", tags: [value], explain: "cos 0 = 1, so arccos 1 = 0." }\n - { id: arccos-minus-1, name: Arccosine of -1, pattern: -1 arccos, output: =pi, tags: [value], explain: "cos π = -1, so arccos(-1) = π." }\n - { id: arctan-0, name: Arctangent of 0, pattern: 0 arctan, output: "0", tags: [value], explain: "tan 0 = 0, so arctan 0 = 0." }\n - { id: arctan-1, name: Arctangent of 1, pattern: 1 arctan, output: =pi 4 /, tags: [value], explain: "tan(π/4) = 1, so arctan 1 = π/4." }\n - { id: sinh-0, name: sinh of 0, pattern: 0 sinh, output: "0", tags: [value], explain: "sinh 0 = 0." }\n - { id: cosh-0, name: cosh of 0, pattern: 0 cosh, output: "1", tags: [value], explain: "cosh 0 = 1." }\n - { id: tanh-0, name: tanh of 0, pattern: 0 tanh, output: "0", tags: [value], explain: "tanh 0 = 0." }\n\n - { id: arctan-sqrt3, name: Arctangent of √3, pattern: 3 sqrt arctan, output: =pi 3 /, tags: [value], explain: "tan(π/3) = √3, so arctan √3 = π/3." }\n - { id: arctan-sqrt3-over-3, name: Arctangent of √3/3, pattern: 3 sqrt 3 / arctan, output: =pi 6 /, tags: [value], explain: "tan(π/6) = √3/3, so arctan(√3/3) = π/6." }\n\n # atan2(y, x): the angle of the point (x, y), in (-π, π]\n - id: atan2-right\n name: The angle of a point to the right\n pattern: y x atan2\n when:\n x: [isPositiveConstant]\n output: y x / arctan\n explain: "For x > 0, atan2(y, x) = arctan(y/x)."\n tags: [value]\n - id: atan2-left-up\n name: The angle of a point to the left\n pattern: y x atan2\n when:\n x: [isNegativeConstant]\n y: [isPositiveConstant]\n output: y x / arctan =pi +\n explain: "For x < 0 and y > 0, atan2(y, x) = arctan(y/x) + π."\n tags: [value]\n - id: atan2-left-down\n name: The angle of a point to the left\n pattern: y x atan2\n when:\n x: [isNegativeConstant]\n y: [isNegativeConstant]\n output: y x / arctan =pi -\n explain: "For x < 0 and y < 0, atan2(y, x) = arctan(y/x) - π."\n tags: [value]\n - { id: atan2-negative-axis, name: The angle of a point on the negative axis, pattern: 0 x atan2, when: { x: [isNegativeConstant] }, output: =pi, tags: [value], explain: "A point on the negative x-axis is at angle π." }\n - { id: atan2-up, name: Straight up, pattern: y 0 atan2, when: { y: [isPositiveConstant] }, output: =pi 2 /, tags: [value], explain: "A point straight up is at angle π/2." }\n - { id: atan2-down, name: Straight down, pattern: y 0 atan2, when: { y: [isNegativeConstant] }, output: =pi 2 / neg, tags: [value], explain: "A point straight down is at angle -π/2." }\n\n # the odd inverses take the sign out; arccos(-u) = π - arccos u\n - id: arcsin-odd\n name: Arcsine of a negative\n pattern: u arcsin\n when:\n u: [hasMinusSign]\n output: u neg arcsin neg\n explain: "arcsin(-x) = -arcsin x."\n tags: [symmetry]\n\n - id: arctan-odd\n name: Arctangent of a negative\n pattern: u arctan\n when:\n u: [hasMinusSign]\n output: u neg arctan neg\n explain: "arctan(-x) = -arctan x."\n tags: [symmetry]\n\n - id: arccos-negative\n name: Arccosine of a negative\n pattern: u arccos\n when:\n u: [hasMinusSign]\n output: =pi u neg arccos -\n explain: "arccos(-x) = π - arccos x."\n tags: [symmetry]\n\n # ---- trigonometry: identities --------------------------------------------\n - id: pythagorean\n name: sin² + cos² = 1\n pattern: u sin 2 ^ u cos 2 ^ +\n commutative: true\n output: "1"\n explain: "sin²{u} + cos²{u} = 1 for every angle."\n tags: [identity]\n\n - id: pythagorean-multiple\n name: sin² + cos² = 1\n pattern: a u sin 2 ^ * a u cos 2 ^ * +\n commutative: true\n output: a\n explain: "{a}·sin²{u} + {a}·cos²{u} = {a}(sin²{u} + cos²{u}) = {a}."\n tags: [identity]\n\n - id: one-minus-sin-squared\n name: 1 - sin² = cos²\n pattern: u sin 2 ^ neg 1 +\n output: u cos 2 ^\n explain: "1 - sin²{u} = cos²{u}."\n tags: [identity]\n\n - id: one-minus-cos-squared\n name: 1 - cos² = sin²\n pattern: u cos 2 ^ neg 1 +\n output: u sin 2 ^\n explain: "1 - cos²{u} = sin²{u}."\n tags: [identity]\n\n - id: sin-over-cos\n name: sin/cos is tan\n pattern: u sin u cos /\n output: u tan\n explain: "sin {u} / cos {u} = tan {u}."\n tags: [identity]\n\n - id: cos-over-sin\n name: cos/sin is cot\n pattern: u cos u sin /\n output: u cot\n explain: "cos {u} / sin {u} = cot {u}."\n tags: [identity]\n\n - id: sin-arcsin\n name: sin undoes arcsin\n pattern: u arcsin sin\n output: u\n explain: "sin(arcsin {u}) = {u}."\n tags: [inverse]\n\n - id: cos-arccos\n name: cos undoes arccos\n pattern: u arccos cos\n output: u\n explain: "cos(arccos {u}) = {u}."\n tags: [inverse]\n\n - id: tan-arctan\n name: tan undoes arctan\n pattern: u arctan tan\n output: u\n explain: "tan(arctan {u}) = {u}."\n tags: [inverse]\n\n - id: cosh-squared-minus-sinh-squared\n name: cosh² - sinh² = 1\n pattern: u cosh 2 ^ u sinh 2 ^ -\n output: "1"\n explain: "cosh²{u} - sinh²{u} = 1."\n tags: [identity]\n\n # ---- trigonometry: shifts by π/2 and π, written with an unknown angle ----------\n - { id: sin-plus-quarter, name: sin(u + π/2), pattern: u =pi 2 / + sin, commutative: true, output: u cos, tags: [symmetry], explain: "Shifting sine by a quarter turn gives cosine: sin({u} + π/2) = cos {u}." }\n - { id: cos-plus-quarter, name: cos(u + π/2), pattern: u =pi 2 / + cos, commutative: true, output: u sin neg, tags: [symmetry], explain: "cos({u} + π/2) = -sin {u}." }\n - { id: sin-minus-quarter, name: sin(u − π/2), pattern: u =pi 2 / - sin, output: u cos neg, tags: [symmetry], explain: "sin({u} - π/2) = -cos {u}." }\n - { id: cos-minus-quarter, name: cos(u − π/2), pattern: u =pi 2 / - cos, output: u sin, tags: [symmetry], explain: "cos({u} - π/2) = sin {u}." }\n - { id: sin-cofunction, name: sin(π/2 − u), pattern: u neg =pi 2 / + sin, commutative: true, output: u cos, tags: [symmetry], explain: "Sine of the complement is cosine: sin(π/2 - {u}) = cos {u}." }\n - { id: cos-cofunction, name: cos(π/2 − u), pattern: u neg =pi 2 / + cos, commutative: true, output: u sin, tags: [symmetry], explain: "Cosine of the complement is sine: cos(π/2 - {u}) = sin {u}." }\n - { id: tan-cofunction, name: tan(π/2 − u), pattern: u neg =pi 2 / + tan, commutative: true, output: u cot, tags: [symmetry], explain: "tan(π/2 - {u}) = cot {u}." }\n - { id: sin-supplement, name: sin(π − u), pattern: u neg =pi + sin, commutative: true, output: u sin, tags: [symmetry], explain: "sin(π - {u}) = sin {u}." }\n - { id: cos-supplement, name: cos(π − u), pattern: u neg =pi + cos, commutative: true, output: u cos neg, tags: [symmetry], explain: "cos(π - {u}) = -cos {u}." }\n - { id: sin-plus-half, name: sin(u + π), pattern: u =pi + sin, commutative: true, output: u sin neg, tags: [symmetry], explain: "Half a turn changes the sign: sin({u} + π) = -sin {u}." }\n - { id: cos-plus-half, name: cos(u + π), pattern: u =pi + cos, commutative: true, output: u cos neg, tags: [symmetry], explain: "Half a turn changes the sign: cos({u} + π) = -cos {u}." }\n - { id: tan-plus-half, name: tan(u + π), pattern: u =pi + tan, commutative: true, output: u tan, tags: [symmetry], explain: "Tangent repeats every π: tan({u} + π) = tan {u}." }\n - { id: sin-minus-half, name: sin(u − π), pattern: u =pi - sin, output: u sin neg, tags: [symmetry], explain: "sin({u} - π) = -sin {u}." }\n - { id: cos-minus-half, name: cos(u − π), pattern: u =pi - cos, output: u cos neg, tags: [symmetry], explain: "cos({u} - π) = -cos {u}." }\n\n # ---- trigonometry: more exact values (15°, 75°, 22.5°, 67.5°) -------------------\n - { id: sin-pi-12, name: Sine of π/12, pattern: =pi 12 / sin, output: 6 sqrt 2 sqrt - 4 /, tags: [value], explain: "sin(π/12) = sin(π/3 - π/4) = (√6 - √2)/4." }\n - { id: cos-pi-12, name: Cosine of π/12, pattern: =pi 12 / cos, output: 6 sqrt 2 sqrt + 4 /, tags: [value], explain: "cos(π/12) = cos(π/3 - π/4) = (√6 + √2)/4." }\n - { id: tan-pi-12, name: Tangent of π/12, pattern: =pi 12 / tan, output: 2 3 sqrt -, tags: [value], explain: "tan(π/12) = 2 - √3." }\n - { id: sin-5pi-12, name: Sine of 5π/12, pattern: 5 =pi * 12 / sin, output: 6 sqrt 2 sqrt + 4 /, tags: [value], explain: "sin(5π/12) = sin(π/4 + π/6) = (√6 + √2)/4." }\n - { id: cos-5pi-12, name: Cosine of 5π/12, pattern: 5 =pi * 12 / cos, output: 6 sqrt 2 sqrt - 4 /, tags: [value], explain: "cos(5π/12) = cos(π/4 + π/6) = (√6 - √2)/4." }\n - { id: tan-5pi-12, name: Tangent of 5π/12, pattern: 5 =pi * 12 / tan, output: 2 3 sqrt +, tags: [value], explain: "tan(5π/12) = 2 + √3." }\n - { id: sin-pi-8, name: Sine of π/8, pattern: =pi 8 / sin, output: 2 2 sqrt - sqrt 2 /, tags: [value], explain: "By the half-angle formula, sin(π/8) = √(2 - √2)/2." }\n - { id: cos-pi-8, name: Cosine of π/8, pattern: =pi 8 / cos, output: 2 2 sqrt + sqrt 2 /, tags: [value], explain: "By the half-angle formula, cos(π/8) = √(2 + √2)/2." }\n - { id: tan-pi-8, name: Tangent of π/8, pattern: =pi 8 / tan, output: 2 sqrt 1 -, tags: [value], explain: "tan(π/8) = √2 - 1." }\n - { id: sin-3pi-8, name: Sine of 3π/8, pattern: 3 =pi * 8 / sin, output: 2 2 sqrt + sqrt 2 /, tags: [value], explain: "sin(3π/8) = cos(π/8) = √(2 + √2)/2." }\n - { id: cos-3pi-8, name: Cosine of 3π/8, pattern: 3 =pi * 8 / cos, output: 2 2 sqrt - sqrt 2 /, tags: [value], explain: "cos(3π/8) = sin(π/8) = √(2 - √2)/2." }\n - { id: tan-3pi-8, name: Tangent of 3π/8, pattern: 3 =pi * 8 / tan, output: 2 sqrt 1 +, tags: [value], explain: "tan(3π/8) = √2 + 1." }\n\n # ---- trigonometry: a function of an inverse function (a right triangle) -----------\n - { id: sin-arccos, name: sin(arccos u), pattern: u arccos sin, output: u 2 ^ neg 1 + sqrt, tags: [inverse], explain: "In a right triangle with cos θ = {u}, the other side is √(1 - {u}²): sin(arccos {u}) = √(1 - {u}²)." }\n - { id: cos-arcsin, name: cos(arcsin u), pattern: u arcsin cos, output: u 2 ^ neg 1 + sqrt, tags: [inverse], explain: "In a right triangle with sin θ = {u}, cos θ = √(1 - {u}²)." }\n - { id: tan-arcsin, name: tan(arcsin u), pattern: u arcsin tan, output: u u 2 ^ neg 1 + sqrt /, tags: [inverse], explain: "tan(arcsin {u}) = {u}/√(1 - {u}²)." }\n - { id: tan-arccos, name: tan(arccos u), pattern: u arccos tan, output: u 2 ^ neg 1 + sqrt u /, tags: [inverse], explain: "tan(arccos {u}) = √(1 - {u}²)/{u}." }\n - { id: sin-arctan, name: sin(arctan u), pattern: u arctan sin, output: u u 2 ^ 1 + sqrt /, tags: [inverse], explain: "In a right triangle with tan θ = {u}, the long side is √(1 + {u}²): sin(arctan {u}) = {u}/√(1 + {u}²)." }\n - { id: cos-arctan, name: cos(arctan u), pattern: u arctan cos, output: 1 u 2 ^ 1 + sqrt /, tags: [inverse], explain: "cos(arctan {u}) = 1/√(1 + {u}²)." }\n - { id: sec-arctan, name: sec(arctan u), pattern: u arctan sec, output: u 2 ^ 1 + sqrt, tags: [inverse], explain: "sec(arctan {u}) = √(1 + {u}²)." }\n - { id: cos-arcsec, name: cos(arcsec u), pattern: u arcsec cos, output: 1 u /, tags: [inverse], explain: "arcsec {u} is the angle whose cosine is 1/{u}." }\n - { id: sin-arccsc, name: sin(arccsc u), pattern: u arccsc sin, output: 1 u /, tags: [inverse], explain: "arccsc {u} is the angle whose sine is 1/{u}." }\n - { id: tan-arccot, name: tan(arccot u), pattern: u arccot tan, output: 1 u /, tags: [inverse], explain: "arccot {u} is the angle whose tangent is 1/{u}." }\n\n # ---- trigonometry: the angle-sum formulas, read backward -------------------------\n - { id: sin-sum, name: sin(u + v), pattern: u sin v cos * u cos v sin * +, commutative: true, output: u v + sin, tags: [identity], explain: "sin {u} cos {v} + cos {u} sin {v} = sin({u} + {v})." }\n - { id: sin-difference, name: sin(u − v), pattern: u sin v cos * u cos v sin * -, commutative: true, output: u v - sin, tags: [identity], explain: "sin {u} cos {v} - cos {u} sin {v} = sin({u} - {v})." }\n - { id: sin-difference-led-by-minus, name: sin(u − v), pattern: u cos v sin * neg u sin v cos * +, commutative: true, output: u v - sin, tags: [identity], explain: "sin {u} cos {v} - cos {u} sin {v} = sin({u} - {v})." }\n - { id: cos-sum, name: cos(u + v), pattern: u cos v cos * u sin v sin * -, commutative: true, output: u v + cos, tags: [identity], explain: "cos {u} cos {v} - sin {u} sin {v} = cos({u} + {v})." }\n - { id: cos-difference, name: cos(u − v), pattern: u cos v cos * u sin v sin * +, commutative: true, output: u v - cos, tags: [identity], explain: "cos {u} cos {v} + sin {u} sin {v} = cos({u} - {v})." }\n\n # ---- logs: opt-in rewrites (run with cas.rewrite(x, \'expand-log\') or \'combine-log\') ----\n - id: ln-product\n name: Log of a product\n mode: expand-log\n pattern: a b * ln\n output: a ln b ln +\n explain: "ln({a}·{b}) = ln {a} + ln {b} (for positive {a}, {b})."\n tags: [log]\n\n - id: ln-quotient\n name: Log of a quotient\n mode: expand-log\n pattern: a b / ln\n output: a ln b ln -\n explain: "ln({a}/{b}) = ln {a} - ln {b} (for positive {a}, {b})."\n tags: [log]\n\n - id: ln-power\n name: Log of a power\n mode: expand-log\n pattern: a n ^ ln\n output: n a ln *\n explain: "ln({a}^{n}) = {n}·ln {a} (for positive {a})."\n tags: [log]\n\n - id: ln-root\n name: Log of a square root\n mode: expand-log\n pattern: a sqrt ln\n output: a ln 2 /\n explain: "ln √{a} = ½ ln {a}."\n tags: [log]\n\n - id: ln-sum-combine\n name: Sum of logs\n mode: combine-log\n pattern: a ln b ln +\n commutative: true\n output: a b * ln\n explain: "ln {a} + ln {b} = ln({a}·{b})."\n tags: [log]\n\n - id: ln-difference-combine\n name: Difference of logs\n mode: combine-log\n pattern: a ln b ln -\n output: a b / ln\n explain: "ln {a} - ln {b} = ln({a}/{b})."\n tags: [log]\n\n - id: ln-multiple-combine\n name: A multiple of a log\n mode: combine-log\n pattern: n a ln *\n when:\n n: [isRational]\n output: a n ^ ln\n explain: "{n}·ln {a} = ln({a}^{n})."\n tags: [log]\n','name: Solving by undoing\n\n# mode: isolate. Each rule undoes the outermost function on the side with the\n# unknown: ln u = r → u = e^r. The predicates hasVariable and freeOfVariable mean\n# "mentions / doesn\'t mention the unknown being solved for".\n#\n# The CAS does the rest itself: it moves terms without the unknown to the other\n# side, divides by a coefficient, and when the unknown appears in several places\n# it uses the polynomial methods (factoring, the quadratic formula) or splits a\n# product equal to 0. Every answer is checked in the original equation, so a\n# rule may give extra candidates (squaring both sides does): the wrong ones are\n# dropped, with a step saying so.\n#\n# An output can give several answers: `pm` (±) splits into two, and so does\n# `|` (or): "u r arcsin = u =pi r arcsin - = |".\n\nrules:\n - id: iso-swap\n name: Unknown on the left\n mode: isolate\n pattern: l r =\n when:\n l: [freeOfVariable]\n r: [hasVariable]\n output: r l =\n priority: 20\n explain: "Swap the sides so the unknown is on the left."\n tags: [tidy]\n\n - id: iso-ln\n name: Undo the log\n mode: isolate\n pattern: u ln r =\n when:\n u: [hasVariable]\n output: u =e r ^ =\n explain: "Raise e to each side: e^(ln {u}) = {u}."\n tags: [inverse]\n\n - id: iso-log\n name: Undo the log\n mode: isolate\n pattern: b u log r =\n when:\n u: [hasVariable]\n b: [freeOfVariable]\n output: u b r ^ =\n explain: "Raise {b} to each side: {b}^(log base {b} of {u}) = {u}."\n tags: [inverse]\n\n - id: iso-exp\n name: Undo e to a power\n mode: isolate\n pattern: =e u ^ r =\n when:\n u: [hasVariable]\n output: u r ln =\n explain: "Take ln of each side: ln(e^{u}) = {u}."\n tags: [inverse]\n\n - id: iso-exponential\n name: Undo a power of a number\n mode: isolate\n pattern: b u ^ r =\n when:\n u: [hasVariable]\n b: [freeOfVariable]\n output: u b r log =\n explain: "Take the log to base {b} of each side."\n tags: [inverse]\n\n - id: iso-square\n name: Undo the square\n mode: isolate\n pattern: u 2 ^ r =\n when:\n u: [hasVariable]\n output: u r sqrt pm =\n priority: 1\n explain: "Take the square root of each side; {u} can be positive or negative."\n tags: [inverse]\n\n - id: iso-even-power\n name: Undo an even power\n mode: isolate\n pattern: u n ^ r =\n when:\n u: [hasVariable]\n n: [isEvenWhole]\n output: u r 1 n / ^ pm =\n explain: "Take the root of each side (the {n}th root); {u} can be positive or negative."\n tags: [inverse]\n\n - id: iso-odd-power\n name: Undo an odd power\n mode: isolate\n pattern: u n ^ r =\n when:\n u: [hasVariable]\n n: [isOddWhole]\n output: u r 1 n / ^ =\n explain: "Take the root of each side (the {n}th root)."\n tags: [inverse]\n\n - id: iso-fractional-power\n name: Undo a power\n mode: isolate\n pattern: u n ^ r =\n when:\n u: [hasVariable]\n n: [isRational]\n output: u r 1 n / ^ =\n priority: -1\n explain: "Raise each side to the power 1/{n}."\n tags: [inverse]\n\n - id: iso-sqrt\n name: Undo the square root\n mode: isolate\n pattern: u sqrt r =\n when:\n u: [hasVariable]\n output: u r 2 ^ =\n explain: "Square each side (this can add answers, so each one is checked at the end)."\n tags: [inverse]\n\n - id: iso-root\n name: Undo the root\n mode: isolate\n pattern: n u root r =\n when:\n u: [hasVariable]\n n: [freeOfVariable]\n output: u r n ^ =\n explain: "Raise each side to the power {n}."\n tags: [inverse]\n\n - id: iso-reciprocal\n name: Undo the fraction\n mode: isolate\n pattern: c u / r =\n when:\n u: [hasVariable]\n c: [freeOfVariable]\n output: u c r / =\n explain: "{c}/{u} = {r}, so {u} = {c}/{r}."\n tags: [inverse]\n\n - id: iso-abs\n name: Undo the absolute value\n mode: isolate\n pattern: u abs r =\n when:\n u: [hasVariable]\n output: u r pm =\n explain: "|{u}| = {r} means {u} is {r} or -{r}."\n tags: [inverse]\n\n - id: iso-sin\n name: Undo the sine\n mode: isolate\n pattern: u sin r =\n when:\n u: [hasVariable]\n output: u r arcsin = u =pi r arcsin - = |\n explain: "Two angles in a turn have sine {r}: arcsin {r} and π - arcsin {r} (add any whole number of turns, 2πk, for the rest)."\n tags: [inverse, trig]\n\n - id: iso-cos\n name: Undo the cosine\n mode: isolate\n pattern: u cos r =\n when:\n u: [hasVariable]\n output: u r arccos pm =\n explain: "Two angles in a turn have cosine {r}: ±arccos {r} (add 2πk for the rest)."\n tags: [inverse, trig]\n\n - id: iso-tan\n name: Undo the tangent\n mode: isolate\n pattern: u tan r =\n when:\n u: [hasVariable]\n output: u r arctan =\n explain: "Take arctan of each side (add πk for the rest)."\n tags: [inverse, trig]\n\n - { id: iso-arcsin, name: Undo arcsin, mode: isolate, pattern: u arcsin r =, when: { u: [hasVariable] }, output: u r sin =, tags: [inverse], explain: "Take sin of each side." }\n - { id: iso-arccos, name: Undo arccos, mode: isolate, pattern: u arccos r =, when: { u: [hasVariable] }, output: u r cos =, tags: [inverse], explain: "Take cos of each side." }\n - { id: iso-arctan, name: Undo arctan, mode: isolate, pattern: u arctan r =, when: { u: [hasVariable] }, output: u r tan =, tags: [inverse], explain: "Take tan of each side." }\n - { id: iso-sinh, name: Undo sinh, mode: isolate, pattern: u sinh r =, when: { u: [hasVariable] }, output: u r arcsinh =, tags: [inverse], explain: "Take arcsinh of each side." }\n - { id: iso-tanh, name: Undo tanh, mode: isolate, pattern: u tanh r =, when: { u: [hasVariable] }, output: u r arctanh =, tags: [inverse], explain: "Take arctanh of each side." }\n - { id: iso-cosh, name: Undo cosh, mode: isolate, pattern: u cosh r =, when: { u: [hasVariable] }, output: u r arccosh pm =, tags: [inverse], explain: "Two numbers have cosh {r}: ±arccosh {r}." }\n - { id: iso-arcsinh, name: Undo arcsinh, mode: isolate, pattern: u arcsinh r =, when: { u: [hasVariable] }, output: u r sinh =, tags: [inverse], explain: "Take sinh of each side." }\n - { id: iso-arccosh, name: Undo arccosh, mode: isolate, pattern: u arccosh r =, when: { u: [hasVariable] }, output: u r cosh =, tags: [inverse], explain: "Take cosh of each side." }\n - { id: iso-arctanh, name: Undo arctanh, mode: isolate, pattern: u arctanh r =, when: { u: [hasVariable] }, output: u r tanh =, tags: [inverse], explain: "Take tanh of each side." }\n'],jp=['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'],Tp=new Set(["<",">","≤","≥"]),Lp=new Set(["sin","cos","tan","sec","csc","cot"]),Fp=new Set(["arcsin","arccos","arctan","arcsec","arccsc","arccot"]),Zp={normal:"Work out the numbers and collect like terms.","simplify.cancel":"Cancel the factors the top and bottom share.","simplify.expand":"Multiplying out gives something shorter.","simplify.factor":"Factoring gives something shorter.",expand:"Multiply out the brackets.",factor:"Write it as a product of factors.","factor.common":"Take out the common factor {common}.","factor.polynomial":"Factor what is left: {roots}.",together:"Write it as one fraction over a common denominator.",cancel:"Cancel the factors the top and bottom share: {canceled}.","solve.move":"Keep the terms with {v} on the left and move the others to the right.","solve.divide":"Divide both sides by {by}.","solve.multiply":"Multiply both sides by {by}.","solve.one-side":"Move everything to one side, so the equation reads … = 0.","solve.factor":"Factor the left side.","solve.zero-product":"A product is 0 exactly when one of its factors is 0.","solve.split":"There are two cases; solve each.","solve.quadratic":"The quadratic formula with a = {a}, b = {b}, c = {c}: {v} = (-b ± √(b² - 4ac)) / 2a, and b² - 4ac = {D}.","solve.no-real":"b² - 4ac = {D} is negative, so there are no real solutions.","solve.quadratic-complex":"The quadratic formula with a = {a}, b = {b}, c = {c}: {v} = (-b ± √(b² - 4ac)) / 2a. b² - 4ac = {D} is negative, so its square root is imaginary: √({D}) = {root}.","solve.roots":"{v}^{n} = {r} has {n} solutions, spaced evenly round a circle: |{r}|^(1/{n})·(cos θ + i sin θ), with θ = (arg {r} + 2πk)/{n} for k = 0 … {last}.","solve.clear-denominator":"Multiply both sides by {den} (an answer that makes it 0 is not allowed).","solve.substitute":"Write {u} for {kernel}: this is a polynomial in {u}.","solve.reject":"{value} is not a solution: {reason}.","solve.always":"This is true for every {v}.","solve.never":"This is never true, so there is no solution.","simplify.trig":"Write it with sin and cos, use sin² + cos² = 1 and the double-angle formulas, and cancel.","limit.substitute":"{f} is continuous at {v} = {a}: put {a} in.","limit.cancel":"{f} is 0/0 at {v} = {a}: cancel the common factor first.","limit.lhopital":"{f} is {form} as {v} → {a}: by L'Hôpital's rule, take the limit of the top's derivative over the bottom's.","limit.leading":"As {v} → {a}, the highest powers decide: {f} behaves like {lead}.","limit.zero-times-infinity":"{f} is 0·∞: write it as a quotient.","limit.combine":"{f} is ∞ − ∞: write it as one fraction.","limit.squeeze":"{bounded} stays between two bounds, and what it is multiplied by goes to 0: so does the product (the squeeze theorem).","limit.divide-power":"Divide the top and the bottom by {power}.","limit.conjugate":"{f} is ∞ − ∞ with a root: multiply top and bottom by the conjugate.","limit.exp-log":"{f} is {form}: write it as e to the power (exponent · ln base), and find the limit of the exponent.","limit.one-sided":"From the left {f} goes to {left}, from the right to {right}: the limit does not exist.","solve.sign-chart":"Where each side minus the other is 0, or has no value: {points}. It keeps one sign between them, so test one {v} in each interval, and each point.","solve.unsolved":"There is no exact method here for solving for {v}; try { approximate: true }.","solve.numeric":"Found {count} solution(s) numerically.","system.eliminate":"Use one equation to remove {v} from the others.","integrate.expand":"Multiply out, then integrate term by term.","integrate.substitute":"Let {u} = {inside}, so d{u} = {a} d{v}.","integrate.back":"Put {inside} back for {u}.","integrate.parts":"By parts with u = {u} and dv = {dv} d{v}: ∫ u dv = u·v - ∫ v du, where v = {V} and du = {du} d{v}.","integrate.constant":"The number {c} comes out of the integral.","integrate.divide":"The top has at least the degree of the bottom: divide first.","integrate.partial-fractions":"Split the fraction into simple fractions, one for each factor below.","integrate.evaluate":"Evaluate {F} at {b} and at {a}, and subtract.","integrate.improper":"An improper integral: at an infinite end, the limit of {F} as {v} goes there; then subtract.","integrate.u-substitution":"Let {u} = {inside}, so d{u} = {du} d{v}: the integral is in {u} alone.","integrate.complete-square":"Partial fractions, and complete the square in {Q}: the top that is a multiple of its derivative gives a log, the rest an arctangent.","integrate.parts-twice":"By parts twice: the integral of {e}·{t} comes back, so solve for it.","integrate.product-to-sum":"Write the product of sines and cosines as a sum.","integrate.odd-power":"Keep one {f} and write the rest with {other} (sin² + cos² = 1): then {other} is the substitution.","integrate.reduction":"The reduction formula for {f} to the power {n}.","integrate.trig-substitution":"Let {x} = {a}·sin θ: the root becomes {a}·cos θ.",substitute:"Put in the values."},Cp=["normal","rewrite","simplify","expand","factor","cancel","diff","differentiate","integrate","solve","solveSystem","substitute","approximate","equivalent","limit"];class Rp{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 Cp){const t=Rp.prototype[e];this[e]=(...e)=>su(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 Cl(e);if("string"!=typeof e)throw new Vl("expected an expression");if(this.read){const t=this.read(e);return Array.isArray(t)?Cl(t):"string"==typeof t?Zl(t):t}return Zl(e)}atPoints(e){if(!e||!Fl(e)||!e.s.includes("= der"))return e;const t=e.args.map(e=>this.atPoints(e)),[n,r]=t;if("der"===e.op&&Fl(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 Tl(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=wh(s,{digits:"number"==typeof n.approximate?n.approximate:15})}return{result:s,text:s?this.format(s):"",steps:Fh(t,Lh(n.steps)),...r}}variable(e,t){if(t&&!/^\\?[A-Za-z\u0370-\u03FF][A-Za-z0-9_\u0370-\u03FF′]*$/.test(t))throw new Vl(`"${t}" is not a variable name; for a derivative at a point write der(f, x = a)`);if(t)return t;const n=[...Qu(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 Pu(this.node(e))}rewrite(e,t,n={}){const r=this.node(e),s=this.set.view(t);if(!s.size)throw new Vl(`no rules in mode "${t}" (modes: ${this.set.modes().join(", ")})`);const i=_h(r,s,{format:this.format,order:n.order,variable:n.variable});return this.result(i.node,[...this.tidyStep(r,Pu(r)),...i.steps],n)}simplify(e,t={}){const n=this.node(e),r=[...this.tidyStep(n,Pu(n))],s=_h(n,this.set.view("simplify"),{format:this.format});r.push(...s.steps);let i=s.node,o=null;const a=Bu(i),l=[],u=0===Qu(i).size,c=u?null:lf(a);c&&l.push({node:sf(c),id:"simplify.cancel",name:"Cancel"});const h=_h(Vu(Rh(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:sf(Yh(a)),id:"simplify.factor",name:"Factor"});const f=e=>Wl(e,"pre").some(({node:e})=>Fl(e)&&Lp.has(e.op)&&Wl(e.args[0],"pre").some(({node:e})=>Fl(e)&&Fp.has(e.op)));for(const e of ep(this,i))l.push({node:e,id:"simplify.trig",name:"Trigonometric identities",prefer:f(i)&&!f(e)});let p=!1;for(const e of l)p&&"simplify.trig"===e.id&&!e.prefer||(e.prefer&&(p=!0),(Bl(e.node)<Bl(i)||e.prefer)&&(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=Vu(Rh(Bu(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=Yh(Bu(n)),s=sf(r),i=[],o=r.notes.find(e=>"factor.common"===e.id);return s.s!==Pu(n).s&&i.push(this.step(o?"factor.common":"factor","Factor",["factor"],n,s,o?{common:Vu(o.values.common)}:{})),this.result(s,i,t)}cancel(e,t={}){const n=this.node(e),r=Bu(n),s=lf(r);if(!s)return this.result(Pu(n),this.tidyStep(n,Pu(n)),t);const i=sf(s),o=af(r),a=Tl("/",[Vu(o.num),Vu(o.den)]),l=[];return"/"===n.op&&a.s===Pu(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(Vu(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=_h(Tl("der",[i,Il(s)]),this.set.view("differentiate"),{format:this.format,order:"pre"}),t=_h(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=_h(Tl("der",[e,Il(t)]),this.set.view("differentiate"),{format:this.format,order:"pre"});return _h(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(Fl(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=hp(this,r,a),u=_h(l.node,this.set.view("simplify"),{format:this.format}),c=[...l.steps,...u.steps];if(i&&o){const e=kp(this,u.node,a,i,o,r);c.push(e.step);const t=_h(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=Tl("+",[h,Il(String(n.constant))])),this.result(h,c,n,{variable:a})}solve(e,t,n={}){const r=this.node(e),s=this.variable(r,t);if(Fl(r)&&Tp.has(r.op))return this.inequality(r,s,n);const i=ff(this,r,s,n);let o=i.solutions;if(n.approximate){const e="number"==typeof n.approximate?n.approximate:15;o=o.map(t=>wh(t,{digits:e}))}const a=o.map(e=>Tl("=",[Il(s),e])),l=a.length?a.reduce((e,t)=>e?Tl("|",[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:Fh(i.steps,Lh(n.steps))}}inequality(e,t,n){const r=If(this,e,t),s={solutions:[],variable:t,unsolved:[],always:!1,steps:Fh(r.steps,Lh(n.steps))};if(!r.pieces)return{...s,pieces:null,intervals:"",result:null,unsolved:[e],text:`no exact solution found for ${t}`};const i=Il(t),o=1===r.pieces.length&&!r.pieces[0].lo&&!r.pieces[0].hi,a=r.pieces.map(({lo:e,hi:t,loClosed:n,hiClosed:r})=>e&&t&&e.s===t.s?Tl("=",[i,e]):e||t?e?t?Tl(r?"≤":"<",[Tl(n?"≤":"<",[e,i]),t]):Tl(n?"≥":">",[i,e]):Tl(r?"≤":"<",[i,t]):null).filter(Boolean).reduce((e,t)=>e?Tl("|",[e,t]):t,null),l=r.pieces.length?r.pieces.map(({lo:e,hi:t,loClosed:n,hiClosed:r})=>e&&t&&e.s===t.s?`{${this.format(e)}}`:`${n?"[":"("}${e?this.format(e):"-∞"}, ${t?this.format(t):"∞"}${r?"]":")"}`).join(" ∪ "):"∅",u=o?`true for every ${t}`:a?this.format(a):"no solution";return{...s,pieces:r.pieces,intervals:l,result:a,always:o,text:u}}limit(e,t,n,r={}){null==n||"object"!=typeof n||Array.isArray(n)||n.type||(r=n,n=void 0);const s=this.node(e),i=Xf(s);if(!i&&Wl(s,"pre").some(({node:e})=>Xf(e))){let e=s;for(const{node:t,path:n}of Wl(s,"post").filter(({node:e})=>Xf(e)).reverse()){const r=this.limit(t,void 0,void 0,{steps:!1});if(!r.exists)return r;if(r.infinite)throw new Vl("a limit inside an expression that is infinite is not worked out here");e=Ul(e,n,r.result)}return{...this.simplify(e,r),exists:!0,infinite:!1}}const o=i?i.f:s,a=i?i.v:this.variable(s,t),l=i?i.to:"number"==typeof n?zl(String(n)):this.node(n??"0"),u="right"===r.side||"+"===r.side?1:"left"===r.side||"-"===r.side?-1:i?i.side:0;try{const{value:e,steps:t}=Uf(this,o,a,Jf(l),u);return{...this.result((c=e,c.inf?c.inf>0?Ff:Il("-∞"):c.fin),t,r),exists:!0,infinite:Boolean(e.inf)}}catch(e){if(!(e instanceof _f))throw e;return{result:null,text:"does not exist",exists:!1,reason:e.message,steps:[]}}var c}solveSystem(e,t,n={}){const r=e.map(e=>this.node(e)),s=t??[...new Set(r.flatMap(e=>[...Qu(e)]))].sort(),i=function(e,t,n){const r=[],s=t.map(t=>{const r=hf(t)?$u([Bu(t.args[0]),Tu(Bu(t.args[1]))]):Bu(t),s=n.map(t=>{const n=Ph(r,t);if(!n||Math.max(0,...n.keys())>1)throw new Vl(`not linear in ${t}`);const s=n.get(1)??au(Jl.ZERO);if(!hu(s))throw new Vl(`the coefficient of ${t} must be a number (it is ${e.format(Vu(s))})`);return s.q});let i=r;for(let e=0;e<n.length;e++)i=$u([i,qu([au(s[e].neg()),Bu(Il(n[e]))])]);for(const e of n)if(Dh(i,e))throw new Vl(`not linear in ${e}`);return{coeffs:s,rhs:Tu(i)}}),i=()=>s.map(e=>uf(Vu($u(e.coeffs.map((e,t)=>qu([au(e),Bu(Il(n[t]))])))),Vu(e.rhs))).reduce((e,t)=>e?Tl("&",[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=qu([au(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=$u([s[e].rhs,qu([au(n.neg()),c.rhs])])}r.push(e.step("system.eliminate","Eliminate",["eliminate"],u,i(),{v:Il(n[t])})),a.push(t),o++}for(const e of s.slice(o))if(!hu(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],Vu(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:Fh(i.steps,Lh(n.steps))}}substitute(e,t,n={}){const r=this.node(e);let s=r;for(const[e,n]of Object.entries(t))s=gf(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:[...Fh(o,Lh(n.steps)),...i.steps]}}defined(e){const t=this.set.view("define");return t.size?_h(e,t,{format:this.format}).node:e}approximate(e,t={}){const n=this.defined(this.node(e));if(Qu(n).size&&!t.scope){const e=wh(Pu(n),t);return{result:e,text:this.format(e),number:null,exact:!1}}const r=vh(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(Tl("-",[n,r])),i=this.simplify(s,{steps:!1}).result;if("num"===i.type&&"0"===i.token)return{equal:!0,how:"exact"};const o=[...Qu(s)];if(!o.length)try{return{equal:Math.abs(vh(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=vh(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 Bp(e={}){const t=!1===e.defaults?[]:[..._p,...e.complex?jp:[]],{specs:n,messages:r}=function(e){Sh();const t=[],n={};for(const r of e){const e="string"==typeof r?Nc(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");$l(t.symbol)||yl({symbol:String(t.symbol),arity:"any"===t.arity?gl: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=su(e.complex,()=>Nh(n));return new Rp(s,{...Zp,...r},e.format??Sp,e.read??null,Boolean(e.complex))}const Pp=Symbol.for("inlinemath.expressions"),Dp=new Map,Wp={re:"Re",im:"Im",conj:"overline"},Up=["Re","Im","re","im","conj","arg"];function Vp(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),`\\:${Wp[e.op]??e.op}`)):t.push(e.token)};return n(e),t}function Hp(e,t){if(!t)return e;const n=new Map;for(const[e,r]of Object.entries(t))if("number"==typeof r?Number.isFinite(r):"bigint"==typeof r||"string"==typeof r)try{n.set(e,mr(String(r)))}catch{}if(!n.size)return e;const r=function(e){let t;try{t=E(e)}catch{return new Set}const n=e=>"symbol"===e?.type?e.value:"op"===e?.type&&["=","→"].includes(e.op)&&"symbol"===e.args[0].type?e.args[0].value:null,r=new Set;return _(t,e=>{if("op"!==e.type||e.args.length<2)return;const t=e.op.startsWith("\\:")?e.op.slice(2):e.op;["der","int","lim","diff","derivative","differentiate","integrate","integral","solve","limit"].includes(t)&&n(e.args[1])&&r.add(n(e.args[1]))}),r}(e);return e.flatMap(e=>n.has(e)&&!r.has(e)?n.get(e):[e])}const Gp={right:"right",r:"right","+":"right",left:"left",l:"left","-":"left"},Qp=new Set(["simplify","expand","factor","cancel","diff","integrate","solve","approx","limit"]),Xp={integral:"integrate",differentiate:"diff",approximate:"approx",simp:"simplify"};function Jp(e={}){const t=e.rules||e.names?null:e.complex?"complex":"default";if(t&&Dp.has(t))return Dp.get(t);const n=[...e.names??[],...e.complex?Up:[],...Qp,...Object.keys(Xp)],r=Bp({...e,read:e=>mr(e,{names:n}),format:Sp});return t&&Dp.set(t,r),r}const Yp=e=>String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");var Kp='/*\n * Inline Math stylesheet. Everything is under .mv; colors are left to the page.\n *\n * The numbers marked "metric" must match the constants at the top of\n * src/layout.js (line-height 1, bar 0.06em, gap 0.1em); everything else can\n * be changed freely.\n *\n * Handy hooks:\n * .mv-n[data-node="4"] one node (ids from MathZetta)\n * .mv-var .mv-num .mv-word variables, numbers, function names\n * .mv-op-frac .mv-op-pow … a kind of operation\n * .mv-hl the class highlight() adds\n * --mv-hl highlight color\n */\n\n.mv {\n display: inline-block;\n font-family: "Inline Math Roman", "Latin Modern Roman", "STIX Two Text", "Cambria", "Times New Roman", serif;\n font-size: 1.2em;\n font-style: normal;\n font-weight: normal;\n line-height: 1; /* metric */\n white-space: nowrap;\n text-indent: 0;\n text-align: left;\n letter-spacing: 0;\n}\n.mv-display { display: block; text-align: center; margin: 0.6em 0; }\n.mv span, .mv svg { line-height: 1; }\n.mv-n { display: inline-block; border-radius: 0.12em; }\n\n/* ---- letters and signs -------------------------------------------------- */\n.mv-var { font-style: italic; padding-right: 0.03em; }\n.mv-num, .mv-word, .mv-name, .mv-ord, .mv-text, .mv-d, .mv-conj { font-style: normal; }\n.mv-prime { margin-left: 0.04em; }\n.mv-bin { margin: 0 0.22em; }\n.mv-rel { margin: 0 0.28em; }\n.mv-conj { margin: 0 0.6em; } /* x = 2 or x = 3 */\n.mv-punct { margin-right: 0.17em; }\n.mv-sign { margin-right: 0.04em; }\n.mv-times { display: inline-block; width: 0.06em; }\n.mv-callgap { display: inline-block; width: 0.05em; }\n.mv-fnspace { display: inline-block; width: 0.17em; }\n.mv-space { display: inline-block; width: 0.33em; }\n.mv-dx { display: inline-block; margin-left: 0.17em; }\n.mv-text { margin: 0 0.25em; }\n/* Tighter spacing in limits and exponents: n=1, x→0. */\n.mv-script .mv-rel, .mv-sup .mv-rel, .mv-sub .mv-rel { margin: 0 0.12em; }\n.mv-script .mv-bin, .mv-sup .mv-bin, .mv-sub .mv-bin { margin: 0 0.1em; }\n\n/* ---- fractions (metric: padding and border) ------------------------------ */\n.mv-frac { display: inline-flex; flex-direction: column; align-items: stretch; margin: 0 0.12em; }\n.mv-numer, .mv-denom { display: block; text-align: center; padding: 0 0.1em; }\n.mv-numer { padding-bottom: 0.1em; }\n.mv-denom { padding-top: 0.1em; border-top: 0.06em solid currentColor; }\n.mv-frac-nobar > .mv-denom { border-top: 0; }\n.mv-scaled { display: inline-block; }\n\n/* ---- scripts ----------------------------------------------------------------- */\n.mv-sup, .mv-sub { display: inline-block; margin-left: 0.04em; }\n.mv-subsup, .mv-limits { display: inline-flex; flex-direction: column; justify-content: space-between; align-items: flex-start; margin-left: 0.04em; }\n.mv-limits { margin-left: 0.02em; margin-right: 0.12em; }\n.mv-limits > .mv-lower { margin-left: -0.3em; }\n.mv-script { display: block; }\n.mv-under { display: inline-flex; flex-direction: column; align-items: center; margin-right: 0.15em; }\n.mv-under > .mv-script { margin-top: 0.05em; }\n.mv-bigop { display: inline-flex; flex-direction: column; align-items: center; margin: 0 0.12em; }\n.mv-bigop > .mv-script { display: block; margin: 0.08em 0; }\n.mv-bigop > svg { display: block; }\n\n/* ---- radicals (metric: border and padding-top) ----------------------------- */\n.mv-sqrt { display: inline-block; white-space: nowrap; }\n.mv-radicand { display: inline-block; position: relative; border-top: 0.06em solid currentColor; padding: 0.1em 0.1em 0 0.06em; }\n/* the hook, in the radicand\'s left margin (layout.js sets its width and that margin): from the bar\'s center\n (just below the middle of the 0.06em border above the box) to the bottom of what it holds, so the tip always meets the bar */\n.mv-hook { position: absolute; top: -0.02em; height: calc(100% + 0.02em); overflow: visible; } /* a hair below the center: never above the bar */\n.mv-rootindex { display: inline-block; margin: 0 -0.32em 0 0.12em; }\n\n/* ---- delimiters: drawn at the full height of what they enclose -------------- */\n.mv-fence { display: inline-block; position: relative; }\n.mv-delim { position: absolute; top: 0; bottom: 0; height: 100%; }\n.mv-delim-l { left: 0.03em; }\n.mv-delim-r { right: 0.03em; }\nspan.mv-delim { width: 0.16em; border: 0 solid currentColor; box-sizing: border-box; }\n.mv-delim.mv-lbrack { border-width: 0.06em 0 0.06em 0.06em; left: 0.06em; }\n.mv-delim.mv-rbrack { border-width: 0.06em 0.06em 0.06em 0; right: 0.06em; }\n.mv-delim.mv-vert { border-left-width: 0.06em; width: 0; left: 0.07em; }\n.mv-delim.mv-vert.mv-delim-r { left: auto; right: 0.07em; }\n.mv-delim.mv-lfloor { border-width: 0 0 0.06em 0.06em; }\n.mv-delim.mv-rfloor { border-width: 0 0.06em 0.06em 0; }\n.mv-delim.mv-lceil { border-width: 0.06em 0 0 0.06em; }\n.mv-delim.mv-rceil { border-width: 0.06em 0.06em 0 0; }\n/* around one line: inline, placed from the baseline like a typed bracket (0.25em below it, 0.75em above),\n not stretched over the line box, which sits higher or lower in every font; the margins keep the widths */\n.mv-fence-line > .mv-delim { position: static; display: inline-block; vertical-align: -0.25em; height: 1em; }\n.mv-fence-line > svg.mv-delim-l { margin: 0 0.07em 0 0.03em; }\n.mv-fence-line > svg.mv-delim-r { margin: 0 0.03em 0 0.07em; }\n.mv-fence-line > span.mv-delim-l { margin: 0 0.08em 0 0.06em; }\n.mv-fence-line > span.mv-delim-r { margin: 0 0.06em 0 0.08em; }\n.mv-fence-line > .mv-delim.mv-vert.mv-delim-l { margin: 0 0.11em 0 0.07em; }\n.mv-fence-line > .mv-delim.mv-vert.mv-delim-r { margin: 0 0.07em 0 0.11em; }\n\n/* ---- shapes ----------------------------------------------------------------- */\n.mv svg { overflow: visible; }\n.mv svg path[stroke] { stroke-width: 0.065em; stroke-linecap: round; stroke-linejoin: round; }\n.mv-intsign path[stroke] { stroke-width: 0.075em; }\n.mv-bigsign { display: inline-block; margin: 0 0.06em; }\n.mv-intsign { margin-right: 0.12em; }\n\n/* ---- piecewise ------------------------------------------------------------- */\n.mv-cases { display: inline-grid; grid-template-columns: auto auto; column-gap: 1em; row-gap: 0.25em; align-items: baseline; text-align: left; margin: 0 0.1em; }\n.mv-case-value, .mv-case-cond { display: block; }\n.mv-matrix { display: inline-grid; column-gap: 0.8em; row-gap: 0.3em; align-items: baseline; justify-items: center; margin: 0 0.15em; }\n.mv-matrix-row { display: contents; }\n.mv-matrix-cell { display: block; }\n\n/* ---- decorations: \\boxed \\cancel \\overline \\vec … --------------------------- */\n.mv-boxed { display: inline-block; border: 0.06em solid currentColor; padding: 0.16em 0.2em; }\n.mv-over { display: inline-block; position: relative; padding-top: 0.14em; }\n.mv-over::before { content: \'\'; position: absolute; left: 0; right: 0; top: 0.21em; border-top: 0.06em solid currentColor; } /* metric */\n.mv-over-low::before { top: 0.48em; }\n.mv-underline { display: inline-block; border-bottom: 0.06em solid currentColor; padding-bottom: 0.06em; }\n.mv-cancel { display: inline-block; position: relative; }\n.mv-cancel-line { position: absolute; left: 0; top: 0; width: 100%; height: 100%; overflow: visible; pointer-events: none; }\n.mv-accent { display: inline-block; position: relative; padding-top: 0.3em; }\n.mv-accent-mark { position: absolute; top: -0.27em; left: 0; right: 0; text-align: center; font-size: 0.7em; line-height: 0.6; } /* metric: measured over F, h, A */\n/* ˆ ˜ ˙ ¨ are spacing marks that sit high in their em: full size, pulled down onto the letter */\n.mv-accent-hat, .mv-accent-widehat, .mv-accent-tilde, .mv-accent-dot, .mv-accent-ddot { font-size: 1em; line-height: 1; top: 0.02em; }\n/* over an italic letter the mark leans with it, right of the box\'s center */\n.mv-accent:has(> .mv-var) > .mv-accent-mark { transform: translateX(0.1em); }\n/* a letter with no ascender (x, u, α; layout.js adds -low): the mark comes down to its top */\n.mv-accent-low > .mv-accent-mark { top: 0.08em; }\n.mv-accent-low > .mv-accent-hat, .mv-accent-low > .mv-accent-widehat, .mv-accent-low > .mv-accent-tilde, .mv-accent-low > .mv-accent-dot, .mv-accent-low > .mv-accent-ddot { top: 0.31em; }\n\n/* ---- interaction -------------------------------------------------------------- */\n.mv-hl { background: var(--mv-hl, rgba(255, 200, 0, 0.35)); box-shadow: 0 0 0 0.08em var(--mv-hl, rgba(255, 200, 0, 0.35)); }\n/* Windows high contrast (and other forced colors) drops backgrounds and shadows: outline a highlight instead */\n@media (forced-colors: active) {\n .mv-hl { outline: 0.08em solid Highlight; outline-offset: 0.04em; }\n}\n.mv-clickable .mv-n { cursor: pointer; }\n.mv-editable .mv-n:hover { outline: 1px dashed rgba(0, 0, 0, 0.25); }\n/* the box editing a part in place (view.editable, or a Markdown textbox variable) */\n.mv-edit { transform: translateY(-50%); z-index: 1000; box-sizing: content-box; padding: 0.1em 0.35em; font-family: inherit;\n border: 1px solid #1a5fb4; border-radius: 0.25em; background: #fff; color: #111; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.18); }\n.mv-edit[aria-invalid="true"] { border-color: #c33; outline: 2px solid #c33; }\n/* the live region a view announces steps through ({ announce: true }): read, never seen */\n.mv-sr-only, .mv-sr-math { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }\n.mv-clickable .mv-n:hover { outline: 1px dashed rgba(0, 0, 0, 0.25); }\n/* the keyboard: the expression is one tab stop, and the part the arrow keys are on is ringed */\n.mv[tabindex]:focus-visible { outline: 0.1em solid #1a5fb4; outline-offset: 0.12em; }\n.mv[tabindex]:focus .mv-focus { outline: 0.1em solid #1a5fb4; outline-offset: 0.06em; border-radius: 0.1em; }\n/* while a part is ringed, the whole expression\'s ring steps back so the part is the one that stands out */\n.mv[tabindex]:focus-visible:has(.mv-focus) { outline: 1px dashed #1a5fb4; }\n@media (forced-colors: active) {\n .mv[tabindex]:focus-visible, .mv[tabindex]:focus .mv-focus { outline-color: Highlight; }\n}\n\n/* ---- steps (stepsHTML from \'@mathzetta/inlinemath/cas\') ---------------------------------------- */\n.mv-steps { margin: 0; padding-left: 1.6em; }\n.mv-step { margin: 0.5em 0 0.9em; }\n.mv-step-name { display: block; font-size: 0.85em; font-weight: 600; color: #555; }\n.mv-step-maths { display: flex; flex-wrap: wrap; align-items: center; gap: 0.4em 0.8em; margin: 0.15em 0; }\n.mv-step-arrow { color: #888; }\n.mv-step-why { margin: 0.1em 0 0; font-size: 0.9em; color: #444; }\n\n/* ---- Markdown with math (markdownToHTML from \'@mathzetta/inlinemath/markdown\') ------------------- */\n.mv-md-math { display: inline-block; vertical-align: middle; }\n.mv-md-display { display: block; text-align: center; margin: 0.6em 0; overflow-x: auto; }\n.mv-md-block { margin: 0.8em 0; }\n.mv-md-error code { background: rgba(200, 60, 0, 0.08); color: #a33; border-bottom: 1px dotted #a33; }\n/* saved variables: $A := 2+2$ draws A ≔ 2 + 2; $A := [[…]]$ an input that sets A */\n.mv-md-input-def { display: inline-flex; align-items: center; gap: 0.3em; }\n.mv-md-assign { margin: 0 0.1em; }\n.mv-md-input { font: inherit; font-size: 0.9em; }\ninput.mv-md-textbox { font-family: inherit; padding: 0.05em 0.3em; field-sizing: content; min-width: 3ch; }\ninput.mv-md-textbox[aria-invalid="true"] { outline: 2px solid #c33; outline-offset: 1px; }\ninput.mv-md-slider { vertical-align: middle; }\n.mv-md-output { font-variant-numeric: tabular-nums; min-width: 2ch; }\n';const em=Kp;if("undefined"!=typeof document&&!document.getElementById("inlinemath-css")){const e=document.createElement("style");e.id="inlinemath-css",e.textContent=Kp,document.head.append(e)}return e.CSS=em,e.DEFAULTS=Ko,e.PATHS=zo,e.View=Ma,e.casBlocks=function(e={}){const t=e.cas??Jp(),n=void 0===e.steps?{}:{steps:e.steps},r=(e,s)=>{let i;try{i=t.read(e)}catch{return yo(e,s)}const o=s&&s[Pp];o&&(i=i.flatMap(e=>Object.hasOwn(o,e)?o[e]:[e])),i=Hp(i,s);const a=i[i.length-1],l=a?.startsWith("\\:")?Xp[a.slice(2)]??a.slice(2):null,u=l&&Qp.has(l),c="der"===a||"int"===a||"lim"===a;if(!u&&!c)return yo(e,s);const h=t.node(i),f=c&&h.op!==a,p=u?h.args:[h],m=e=>e?e.s:void 0,d=(e,r,s)=>{if(!r||"="!==r.op)return t.diff(e,m(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(f?"simplify-read":u?l:"der"===a?"derivative":"lim"===a?"lim":"antiderivative"){case"simplify-read":g=t.simplify(h,n);break;case"simplify":g=t.simplify(p[0],n);break;case"expand":g=t.expand(p[0],n);break;case"factor":g=t.factor(p[0],n);break;case"cancel":g=t.cancel(p[0],n);break;case"diff":g=d(p[0],p[1],p[2]?Number(p[2].s):1);break;case"integrate":g=t.integrate(p[0],m(p[1]),{...n,...p[3]?{from:p[2].s,to:p[3].s}:{}});break;case"solve":g=t.solve(p[0],m(p[1]),n);break;case"lim":g=t.limit(h,void 0,void 0,n);break;case"limit":g=(([e,r,s,i])=>{let o=i?Gp[i.s.replace(/^\\/,"")]:void 0;if(i&&!o)throw new Error(`a side is right or left, not ${i.s}`);if(r&&"→"===r.op){[r,s]=r.args;const e="^"===s.op?s.args[1].s.replace(/^\\/,""):null;"+"!==e&&"-"!==e||(o=Gp[e],s=s.args[0])}return t.limit(e,m(r),s,{...n,...o?{side:o}:{}})})(p);break;case"approx":g=t.approximate(p[0],{...n,digits:p[1]?Number(p[1].s):15});break;case"derivative":g=d(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=ml(Vp(g.result));return/^-?\d+(\.\d+)?$/.test(v)?v:`(${v})`};return r},e.createVariables=Ra,e.extractMath=Da,e.layout=sa,e.markdownToHTML=function(e,t={}){return il(Ha(e,t,t.variables||null),t)},e.mathCAS=Jp,e.nodeAt=da,e.numberTree=va,e.pathOf=ga,e.render=function(e,t,n={}){return new Ma(e,t,n)},e.renderMarkdown=sl,e.renderMarkdownInto=function(e,t,n={}){const r=void 0===n.variables?Ba:n.variables||null;ll();const s=ol.get(e);s&&s.stop(s.store!==r);let i=Ha(t,n,r,e);if(e.innerHTML=il(i,n),!r)return ol.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{xa(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=ga(u,c)||[];let f=null;for(let e=h.length;e>=0&&!f;e--){const t=da(u,h.slice(0,e));t&&void 0!==t.from&&(f={node:t,depth:e})}const p=f&&r.definitions().get(f.node.from);if(p&&p.input&&"textbox"===p.input.kind){s.preventDefault();const t=p.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=>xa(e),c=da(u,h);return void qa(o,a(za(c,l)),{label:`Edit ${t}`,parse:e=>xa(e,{blocks:n.blocks}),commit:e=>{const n=ka(za(f.node,l),h.slice(f.depth),e);r.set(t,a(n))}})}const m=p&&i.defs.get(p.name),d=m&&m.key===p.key&&void 0!==m.start?{...i.math[l],start:m.start,end:m.end,raw:t.slice(m.start,m.end)}:i.math[l];e.dispatchEvent(new CustomEvent("inlinemath:select",{bubbles:!0,detail:{index:l,start:d.start,end:d.end,raw:d.raw,source:d.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,ll(),(()=>{const s=Ha(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),al.delete(h),ol.delete(e),t&&r.own(e,null)}const h={element:e,store:r,stop:c,connected:()=>o};return al.add(h),ol.set(e,h),e},e.select=pa,e.shouldAnimate=Sa,e.signature=fa,e.stepsHTML=function(e,t={}){return`<ol class="mv-steps">${e.map(e=>{const n=$a(Vp(Zl(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>${$a(Vp(Zl(e.to)),t)}`,s=e.explanation?`<p class="mv-step-why">${Yp(e.explanation)}</p>`:"";return`<li class="mv-step" data-rule="${Yp(e.id)}"><span class="mv-step-name">${Yp(e.name)}</span><div class="mv-step-maths">${n}${r}</div>${s}</li>`}).join("")}</ol>`},e.toHTML=$a,e.toText=ml,e.tokensOf=Vp,e.treeOf=xa,e.variables=Ba,e}({});
|
|
1
|
+
/* Inline Math 0.4.2 — 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),arcsec:r(1),arccsc:r(1),arccot: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),evaluated:r(4),setbuilder: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"},"\\implies":{prec:15,assoc:"right",arity:2,fixity:"infix"},"\\iff":{prec:14,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,f="",p="",m={[f]:"dot",[p]:"cross"},d="",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,evaluated:h,setbuilder:h,arcsin:h,arccos:h,arctan:h,arcsec:h,arccsc:h,arccot:h,arcsinh:h,arccosh:h,arctanh:h,atan2:h,_:h,"!":90,"\\not":85,"^":80,"*":70,"/":70,frac:70,[f]:70,[p]: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,"\\implies":15,"\\iff":14,"?:":10,"?":9,",":5},v=e=>Object.prototype.hasOwnProperty.call(g,e),b=new Set(["^","?:","?","log"]),y=["(","{","["],w=[")","}","]"];function x(e,t=!1){return"string"==typeof e&&(t?k:$).test(e)}const $=/^(?:\d+\.?\d*|\.\d+|\d*\.\d+\.\.)$/,k=/^-?(?:\d+\.?\d*|\.\d+|\d*\.\d+\.\.)$/;for(const e of[g])Object.setPrototypeOf(e,null);const q=e=>({type:"number",value:String(e)}),M=e=>({type:"symbol",value:e}),A=(e,t)=>({type:"op",op:e,args:t}),S=['"',"'","`"];function N(e){return x(e,!0)?q(e):S.includes(e[0])?{type:"string",value:e}:M(e)}const O={"0-":"neg",sqrtpow:"root",pow:"^","==":"=","!==":"≠="};function E(e){if(!Array.isArray(e)||0===e.length)throw new Error("Empty postfix");const n=[],r=[];if(e.forEach((e,s)=>{const i=O[e]??String(e),l=a(i);if(!l)return n.push({...N(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({...A(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 I(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 z(e){if(Array.isArray(e))return E(e);if(e&&"object"==typeof e&&e.type)return e;throw new Error("Expected a postfix array or an expression tree")}function _(e,t,n=null){t(e,n),"op"===e.type&&e.args.forEach(n=>_(n,t,e))}function j(e){let t="";return _(e,e=>{!t&&"symbol"===e.type&&1===e.value.length&&/[a-zA-Zʹ-Ͽ]/.test(e.value)&&(t=e.value)}),t}for(const e of[O])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 C(e){for(;"op"===e.type&&e.args.length;)e=e.args[0];return"op"===e.type?"":e.value}function Z(e,t,n){const r=e=>"symbol"===e.type?e.value===t?n:e:"op"!==e.type?e:F.has(e.op)&&function(e,t){if("setbuilder"===e.op){const n=e.args[0];return("symbol"===n.type?n.value:n.args?.[0]?.value)===t}const n=e.args[1];return"symbol"===n?.type?n.value===t:"op"===n?.type&&["=","→"].includes(n.op)&&"symbol"===n.args[0]?.type&&n.args[0].value===t}(e,t)?{...e,id:void 0,args:e.args.map((t,n)=>function(e,t,n,r){if("setbuilder"===e)return 0===n&&"op"===t.type&&"∈"===t.op?{...t,id:void 0,args:[t.args[0],r(t.args[1])]}:t;if(0===n)return t;if(1===n)return"op"!==t.type||"="!==t.op&&"→"!==t.op?t:{...t,id:void 0,args:[t.args[0],...t.args.slice(1).map(r)]};return r(t)}(e.op,t,n,r))}:{...e,id:void 0,args:e.args.map(r)};return r(e)}const F=new Set(["der","int","lim","\\sumidx","\\prodidx","evaluated","setbuilder"]);function L(e){if("op"!==e.type||"∈"!==e.op&&"∉"!==e.op)return null;const[t,n]=e.args;if("op"!==n.type||"setbuilder"!==n.op)return null;let[r,s]=n.args,i=null;if("op"===r.type&&"∈"===r.op&&"symbol"===r.args[0].type&&([r,i]=r.args),"symbol"!==r.type)return null;const o=Z(s,r.value,t),a=i?{type:"op",op:"&",args:[{type:"op",op:"∈",args:[t,i]},o]}:o;return"∉"===e.op?{type:"op",op:"\\not",args:[a]}:a}function R(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 B(e){if("*"!==e.op)return!1;const[t,n]=e.args;return"number"===t.type&&"-1"===t.value&&"-1"!==C(n)}function P(e){return"op"!==e.type||a(e.op)?.group?null:"sum"===e.op?"+":"prod"===e.op?"*":B(e)?"neg":e.op}const W=new Set(["=","===","≠","≠=","<",">","≤","≥","≈","≡","→"]),D=(e,t,n)=>("op"!==t.type||"?:"!==t.op||!W.has(e.op))&&c(e.op,P(t),n);function U(e,t){const n=P(t),r=n&&a(n)?.prec;return r?"!"===e?r<=a("!").prec:"\\not"===e?r<a("\\not").prec:r<70||Y(t)||"\\not"===n:"\\not"!==e&&Y(t)}function V(e,t,n={}){const r=n.left?"bracket":X(e),s=n.right?"bracket":Q(t);return"digit"!==s&&"sign"!==s&&"word"!==r&&"word"!==s&&"other"!==r&&("frac"!==s||"digit"!==r&&"frac"!==r)}function H(e){return 1===e.length||Boolean(T[e])||/^Δ.$/.test(e)||/^d[A-Za-z\u03B1-\u03C9]$/.test(e)||/^.′+$/.test(e)}function G(e){return"op"===e.type&&!a(e.op)?.group&&(a(e.op)?.prec??100)<70&&!["sum","prod"].includes(e.op)}function Q(e){if("number"===e.type)return e.value.startsWith("-")?"sign":"digit";if("op"!==e.type)return"symbol"===e.type&&H(e.value)?"name":"word";const t=e.op;return"neg"===t||"pm"===t||B(e)?"sign":"/"===t?"frac":a(t)?.group||G(e)?"bracket":J(e)||["der","int","lim","comb"].includes(t)?"call":["^","!","_"].includes(t)?G(e.args[0])?"bracket":Q(e.args[0]):["*","sum","prod","perm"].includes(t)?Q(e.args[0]):"other"}function X(e){if("number"===e.type)return"digit";if("op"!==e.type)return"symbol"===e.type&&H(e.value)?"name":"word";const t=e.op;return"/"===t?"frac":"^"===t||"_"===t?"script":a(t)?.group||G(e)||J(e)||["der","int","lim","comb","perm"].includes(t)?"bracket":["*","neg","pm","sum","prod"].includes(t)?X(e.args[e.args.length-1]):"other"}function J(e){if("op"!==e.type)return!1;const t=a(e.op);return"prefix"===t?.fixity&&100===t.prec}function Y(e){if("number"===e.type)return e.value.startsWith("-");if("op"!==e.type)return!1;if("neg"===e.op||B(e))return!0;const t=a(e.op);return"infix"===t?.fixity&&!D(e,e.args[0],"left")&&Y(e.args[0])}const K=e=>"symbol"===e.type&&1===e.value.length&&/[a-zA-Zʹ-Ͽ]/.test(e.value),ee=e=>e.slice(2),te=new Set(["{}","()","[]","(]","[)","setbuilder","∪","∩"]);const ne=e=>"string"==typeof e&&e.startsWith("\\:")&&"startswith"===e.slice(2).toLowerCase(),re=e=>(null==e?"":String(e)).replace(/[A-Z]/g,e=>String.fromCharCode(e.charCodeAt(0)+32));function se(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&&ie(i.args[1],n);)s++,i=i.args[0];return{n:s,body:i,by:n,at:r,variable:"symbol"===i.type&&H(i.value)}}const ie=(e,t)=>e.type===t.type&&e.value===t.value&&"op"!==e.type,oe=new Set(["<",">","≤","≥","=","===","≠","≠=","&","|","\\not","\\xor","\\nand","\\nor","\\implies","\\iff","∈","∉","≈","≡"]);function ae(e){return"op"===e.type&&(!!("="===e.op&&(t=e.args[1],"op"===t.type&&oe.has(t.op)||"symbol"===t.type&&("true"===t.value||"false"===t.value)))||e.args.some(ae));var t}const le=new Set(["<",">","≤","≥","=","≠"]);function ue(e){if("op"!==e.type||!le.has(e.op)||2!==e.args.length)return null;const[t,n]=e.args;if("op"!==t.type||!le.has(t.op)||2!==t.args.length)return null;return{type:"op",op:"&",args:[ue(t)??t,{type:"op",op:e.op,args:[t.args[1],n]}]}}for(const e of[T])Object.setPrototypeOf(e,null);const ce={pmatrix:["(",")"],bmatrix:["[","]"],vmatrix:["|","|"]};function he(e){if(!e||"op"!==e.type)return null;if(Object.prototype.hasOwnProperty.call(ce,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 fe(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 pe=e=>Array.isArray(e)&&e.length>0&&!e.some(Array.isArray);function me(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 fe(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 de(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 ve(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=ge(n,e,s);i?(r+=t.get(e.slice(s,s+i)),s+=i):r+=e[s++]}return r}}function ge(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 ve(e){const t=new Set([e.toLowerCase(),e.toUpperCase(),be(e)]);return t.delete(e),t}function be(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 ye=[["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.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("],["asec(","arcsec("],["acsc(","arccsc("],["acot(","arccot("],["\\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",f],["\\times",p],["×",p],["·",f],["÷","/"],["->","→"],["\\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 "],["\\Longrightarrow"," \\implies "],["\\Rightarrow"," \\implies "],["\\implies"," \\implies "],["⇒"," \\implies "],["⟹"," \\implies "],["\\Longleftrightarrow"," \\iff "],["\\Leftrightarrow"," \\iff "],["\\iff"," \\iff "],["⇔"," \\iff "],["⟺"," \\iff "],["\\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.",d],["\\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 "],["∞","∞"],["⋅",f],["−","-"],["\\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 we=e=>" "===e||"\t"===e||"\n"===e,xe="({[",$e=")}]";const ke="ⅆ",qe=new RegExp(String.raw`(\\(?:mathrm|operatorname|text)\{d\}\s*|d)([A-Za-zα-ω](?![A-Za-z0-9])|\\(?:${"alpha|beta|gamma|delta|epsilon|varepsilon|zeta|eta|theta|vartheta|iota|kappa|lambda|mu|nu|xi|rho|sigma|tau|upsilon|phi|varphi|chi|psi|omega"})(?![A-Za-z]))`,"g");function Me(e){const t=[String.raw`\left\{`,String.raw`\left\lbrace`,String.raw`\{`,String.raw`\lbrace`,"{"],n=[String.raw`\right\}`,String.raw`\right\rbrace`,String.raw`\}`,String.raw`\rbrace`,"}"],r=/\\[A-Za-z{]/.test(e);for(let s=0,i=0;s<50;s++){let s=-1,o="";for(let n=i;n<e.length&&s<0;n++){const i=t.find(t=>e.startsWith(t,n));i&&("{"===i&&(r||/[\\^_A-Za-z]$/.test(e.slice(0,n)))||("{"!==i||"{"!==e[n+1]?(s=n,o=i):n++))}if(s<0)return e;let a=0,l=null,u=null,c=-1,h=0;for(let t=s+o.length;t<e.length;t++){const s=n.find(n=>e.startsWith(n,t));if(0===a&&s&&("{"===o?"}"===s:"}"!==s)){c=t,o+="|"+s;break}if(!"([{".includes(e[t])||"{"===e[t]&&"\\"===e[t-1]?")]}".includes(e[t])&&"\\"!==e[t-1]&&a--:a++,0===a&&"?"===e[t]&&h++,0===a&&!l){const n=/^(?:\\middle\s*\||\\mid(?![A-Za-z])|:(?!=)|\|)/.exec(e.slice(t));n&&":"===n[0]&&h?h--:n&&"|"!==n[0]?l={at:t,length:n[0].length}:n&&r&&!u&&!/\\left\s*$|\\right\s*$|\\middle\s*$/.test(e.slice(0,t))&&(u={at:t,length:1})}}if(l??=u,c<0||!l){i=s+1;continue}const f=e.slice(s+o.split("|")[0].length,l.at).trim(),p=e.slice(l.at+l.length,c).trim();if(!f||!p){i=s+1;continue}const m=o.split("|")[1];e=`${e.slice(0,s)}setbuilder((${f}),(${p}))${e.slice(c+m.length)}`,i=s}return e}const Ae=String.raw`\\(?:[Bb]igg?|right)[lrm]?`,Se=new RegExp(`(?:${Ae}\\s*([\\]|])|(\\]))\\s*(?=[_^])`,"g");function Ne(e,t){let n=t;for(;" "===e[n];)n++;if("{"===e[n]){let t=0;for(let r=n;r<e.length;r++)if("{"===e[r])t++;else if("}"===e[r]&&0===--t)return{value:e.slice(n+1,r).trim(),end:r+1};return null}const r=/^\\[A-Za-z]+/.exec(e.slice(n));return r?{value:r[0],end:n+r[0].length}:"-"===e[n]&&/\d/.test(e[n+1]??"")?{value:e.slice(n,n+2),end:n+2}:e[n]?{value:e[n],end:n+1}:null}function Oe(e,t){let n=t;for(;" "===e[n];)n++;const r=e[n];if("_"!==r&&"^"!==r)return null;const s=Ne(e,n+1);if(!s)return null;let i=s.end;for(;" "===e[i];)i++;const o="_"===r?"^":"_";if(e[i]!==o)return null;const a=Ne(e,i+1);return a?"_"===r?{lo:s.value,hi:a.value,end:a.end}:{lo:a.value,hi:s.value,end:a.end}:null}function Ee(e,t,n){let r=0;for(let s=t-1;s>=0;s--){if(n){if("]"===e[s])r++;else if("["===e[s]){if(0===r)return{start:s,end:s+1};r--}continue}const i=e.slice(0,s+1),o=/\\right\s*[\]|)}.]$|\\[Bb]igg?r?\s*[\]|]$/.exec(i),a=/\\left\s*(?:[[(.]|\\\{)$|\\[Bb]igg?l?\s*\[$/.exec(i);if(o&&s+1<t)r++,s-=o[0].length-1;else if(a){if(0===r)return{start:s+1-a[0].length,end:s+1};r--,s-=a[0].length-1}}return null}function Ie(e,t){let n=0;for(let r=t-1;r>=0;r--){const t=e[r];if(")]}".includes(t))n++;else if("([{".includes(t)){if(0===n)return r+1;n--}else{if(0===n&&/[=<>&,]/.test(t))return r+1;if(0===n&&/\\(?:approx|leq?|geq?|neq?|to|quad|qquad)$/.test(e.slice(0,r+1)))return r+1}}return 0}function ze(e){for(let t=0;t<50;t++){Se.lastIndex=0;let t=null;for(let n=Se.exec(e);n;n=Se.exec(e)){const r=Oe(e,n.index+n[0].length);if(!r)continue;const s=Boolean(n[2]),i="|"===(n[1]??n[2]),o=Ee(e,n.index,s);if((o||i&&!/^\\right/.test(n[0]))&&(!o||!/\\left\s*\|$/.test(e.slice(o.start,o.end)))){t={m:n,limits:r,opener:o};break}}if(!t)return e;const{m:n,limits:r,opener:s}=t,i=s?s.start:Ie(e,n.index),o=e.slice(s?s.end:i,n.index).trim(),a=/^\s*([A-Za-zα-ωΑ-Ω]|\\[A-Za-z]+)\s*=\s*([\s\S]+)$/.exec(r.lo),l=r.hi.replace(/^\s*(?:[A-Za-zα-ωΑ-Ω]|\\[A-Za-z]+)\s*=\s*/,""),u=a?`evaluated((${o}),${a[1]},${a[2]},${l})`:`evaluated((${o}),${r.lo},${l})`;e=`${e.slice(0,i)}${i>0&&/[^\s(=]/.test(e[i-1])?" ":""}${u}${e.slice(r.end)}`}return e}const _e={__proto__:null,sine:"sin",cosine:"cos",tangent:"tan",secant:"sec",cosecant:"csc",cotangent:"cot"};const je=100;const Te={__proto__:null},Ce={__proto__:null};[..."⁰¹²³⁴⁵⁶⁷⁸⁹"].forEach((e,t)=>{Te[e]=String(t)}),[..."₀₁₂₃₄₅₆₇₈₉"].forEach((e,t)=>{Ce[e]=String(t)}),Object.assign(Te,{"⁺":"+","⁻":"-","⁼":"=","⁽":"(","⁾":")","ᵃ":"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(Ce,{"₊":"+","₋":"-","₌":"=","₍":"(","₎":")","ₐ":"a","ₑ":"e","ₕ":"h","ᵢ":"i","ⱼ":"j","ₖ":"k","ₗ":"l","ₘ":"m","ₙ":"n","ₒ":"o","ₚ":"p","ᵣ":"r","ₛ":"s","ₜ":"t","ᵤ":"u","ᵥ":"v","ₓ":"x"});const Ze=new RegExp(`[${Object.keys(Te).join("")}]+|[${Object.keys(Ce).join("")}]+`,"g");const Fe={__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"},Le=new RegExp(`(?<![\\w.,^_])(\\d+)[ \\t]?([${Object.keys(Fe).join("")}])`,"g"),Re=/(?<![\w.,^_/])(\d+)[ \t]+([1-9]\d*)\/(\d+)(?![\d./^!])/g,Be=/(?<![\w.,^_])(\d+)\s*\\[dtc]?frac\s*(?:\{\s*(\d+)\s*\}\s*\{\s*(\d+)\s*\}|(\d)(\d)(?!\d))/g;function Pe(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 We(e,t){const n=[];let r=0,s=0;for(let i=0;i<e.length;i++)xe.includes(e[i])?r++:$e.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 De(e,t,n){let r=0;const s=new RegExp(`\\b${n}\\b`,"iy");for(let n=t;n<e.length;n++)if(xe.includes(e[n]))r++;else if($e.includes(e[n])){if(--r<0)return-1}else if(0===r&&(s.lastIndex=n,s.test(e)))return n;return-1}function Ue(e,t){let n=0;for(let r=t;r<e.length;r++)if(xe.includes(e[r]))n++;else if($e.includes(e[r])&&--n<0)return r;return e.length}function Ve(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(xe.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 Ge(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 Qe(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 Xe=new Set(["pmatrix","bmatrix","vmatrix"]);function Je(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 Xe.has(r)?r+"("+o.join(", ")+")"+a:"["+o.join(", ")+"]"+a}function Ye(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 Ke(e){const{lower:t,upper:n,next:r}=function(e){let t="",n="",r=0;return"_"===e[0]&&([t,r]=Ye(e,0),"^"===e[r]&&([n,r]=Ye(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(xe.includes(e[n]))t++;else if($e.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 et(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($e.includes(n[e])?r--:xe.includes(n[e])&&r++,0===r)return"("+n.slice(0,e)+","+t+")"+n.slice(e+1);return!1}function tt(e){return"{"===e[0]||e.length<2?e:"{"+e[0]+"}{"+e[1]+"}"+e.slice(2)}const nt=/[A-Za-z\u0370-\u03FF]/;function rt(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 st(e,t){const n=/^\^(?:\{(\d+)\}|(\d))/.exec(e.slice(t));return n?[Number(n[1]??n[2]),t+n[0].length]:[1,t]}function it(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 ot(e,t){if(xe.includes(e[t])){let n=0;for(let r=t;r<e.length;r++)if(xe.includes(e[r]))n++;else if($e.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(xe.includes(e[r]))n++;else{if($e.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 at=(e,t,n)=>`der(${e},${t}${n>1?","+n:""})`;const lt="strtktk",ut="ABCDEFGHIJ",ct=e=>lt+[...String(e)].map(e=>ut[e]).join(""),ht=new RegExp(`^${lt}[${ut}]+$`);function ft(e){let t="";for(let n=0;n<e.length;n++){const r=e[n];if('"'===r||"`"===r){const r=pt(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=pt(e,n);t+=e.slice(n,r+1),n=r}else t+=r}return t}function pt(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 mt=new RegExp(`${lt}[${ut}]+|§\\d+§`,"g");function dt(e,t){return t&&0!==t.size?e.map(e=>"string"!=typeof e?e:e.replace(mt,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 gt={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; })",times:"((a, b) => { const L = Array.isArray; const m = (v) => L(v) && v.length > 0 && v.every((r) => L(r) && r.length > 0 && r.length === v[0].length && !r.some(L)) && (v.length > 1 || v[0].length > 1); const l = (v) => L(v) && v.length > 0 && !v.some(L); const p = (A, B) => (A[0].length === B.length ? A.map((r) => B[0].map((_, j) => r.reduce((s, x, k) => s + x * B[k][j], 0))) : NaN); const e = (x, y) => (L(x) && L(y) ? (x.length === y.length ? x.map((t, i) => e(t, y[i])) : NaN) : L(x) ? x.map((t) => e(t, y)) : L(y) ? y.map((t) => e(x, t)) : x * y); if (m(a) && m(b)) return p(a, b); if (m(a) && l(b)) { const c = p(a, b.map((y) => [y])); return L(c) ? c.map((r) => r[0]) : c; } if (l(a) && m(b)) { const c = p([a], b); return L(c) ? c[0] : c; } return e(a, b); })",same:"((a, b) => { const s = (x, y) => (Array.isArray(x) && Array.isArray(y) ? x.length === y.length && x.every((v, i) => s(v, y[i])) : x == y); return s(a, b); })",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.abs(n % 2) === 1 ? -Math.pow(-x, 1 / n) : Math.pow(x, 1 / n)))",contains:"((s, t) => { const f = (x) => (x == null ? String() : String(x)).replace(/[A-Z]/g, (c) => String.fromCharCode(c.charCodeAt(0) + 32)); return f(s).includes(f(t)); })",startswith:"((s, t) => { const f = (x) => (x == null ? String() : String(x)).replace(/[A-Z]/g, (c) => String.fromCharCode(c.charCodeAt(0) + 32)); return f(s).startsWith(f(t)); })"},vt="lambda x: str().join(chr(ord(c) + 32) if 65 <= ord(c) <= 90 else c for c in (str() if x is None or x != x else str(int(x)) if isinstance(x, float) and x.is_integer() else str(x)))",bt=`lambda s, t, f=${vt}: f(t) in f(s)`,yt=`lambda s, t, f=${vt}: f(s).startswith(f(t))`,wt={contains:`(${bt})`,startswith:`(${yt})`},xt={contains:`np.vectorize(${bt}, otypes=[bool])`,startswith:`np.vectorize(${yt}, otypes=[bool])`};for(const e of[gt,wt,xt])Object.setPrototypeOf(e,null);const $t="([{",kt=")]}";function qt(e,t){let n=0;for(let r=t;r<e.length;r++)if($t.includes(e[r]))n++;else if(kt.includes(e[r])&&0===--n)return r;return-1}function Mt(e){if(!e.trim())return[];const t=[];let n=0,r=0;for(let s=0;s<e.length;s++)$t.includes(e[s])?n++:kt.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 At(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=qt(e,i);if(o<0)continue;const a=n(Mt(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 St=e=>new RegExp(`(?<![\\w.])(${e})\\s*\\(`,"g"),Nt=e=>`(${e})`,Ot=e=>/^\[.*\]$/s.test(e.trim())?`{${e.trim().slice(1,-1)}}`:e,Et=[...Object.entries(gt),...Object.entries(xt),...Object.entries(wt)];const It={IF:e=>e.length>=2&&`((${e[0]}) ? (${e[1]}) : (${e[2]??"false"}))`,AND:e=>e.length&&`(${e.map(Nt).join(" & ")})`,OR:e=>e.length&&`(${e.map(Nt).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]})`,MMULT:e=>2===e.length&&`((${e[0]}) * (${e[1]}))`};function zt(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 _t(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=qt(e,o)+1;else{const t=n.exec(e.slice(o));i=t?o+t[0].length:0,t&&"("===e[i]&&(i=qt(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=zt(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),At(e,/(?<![\w.])([A-Z][A-Z0-9]*(?:\.[A-Z]+)?)\s*\(/g,(e,t)=>It[t[1]]?.(e)||null)}const jt={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"},Tt="strtktk[A-J]+";function Ct(e){for(let t=!0;t;){const n=e;t=(e=e.replace(new RegExp(`(${Tt})\\s*\\|\\|\\s*(${Tt})`,"g"),"$1 + $2"))!==n}const t=new RegExp(`^\\(typeof\\(([^()]*)\\)\\s+IN\\s+\\(${Tt},\\s*${Tt}\\)\\s+AND\\s+(.*)\\)$`,"s");for(let n=e.lastIndexOf("(typeof(");n>=0;n=n>0?e.lastIndexOf("(typeof(",n-1):-1){const r=qt(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=At(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=At(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})`,Nt(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=>jt[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=qt(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 Zt={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"},Ft={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",dot:"np_times",matmul:"np_times",multiply:"np_times",array_equal:"np_equal"};const Lt=e=>e.replace(/(?<![\w.])set\s*\(\s*\)/g,"∅"),Rt={inf:"∞",nan:"NaN"};function Bt(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)=>Zt[t]?`Math.${Zt[t]}`:Ft[t]?Ft[t]:Rt[t]??e),e=e.replace(/(?<![\w.])(?:math|Math)\.(factorial|isfinite|isclose|prod|inf|nan|abs|trunc)\b/g,(e,t)=>Rt[t]??t),e=e.replace(/(?<![\w.])Number\.(isInteger|isFinite)\b/g,(e,t)=>t.toLowerCase()),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)=>Wt[t]??e),e=e.replace(/(?<![\w.])sympy\.(Reals|Integers|Naturals0?|Rationals|Complexes)\b/g,(e,t)=>Wt[t]),e.replace(/(?<![\w.])sympy\.(\w+)/g,(e,t)=>Dt[t]??Pt[t]??e)}(e=e.replace(/(?<![\w.])scipy\.(?:special|integrate)\.(\w+)/g,"$1")),(e=e.replace(/\bMZ_INFINITY\b/g,"∞")).replace(/(?<![\w.])mz_(?=\w+\s*\()/g,"")}const Pt={pi:"π",E:"e",oo:"∞",true:"true",false:"false",nan:"NaN",I:"i"},Wt={Reals:"ℝ",Integers:"ℤ",Naturals:"ℕ",Naturals0:"ℕ",Rationals:"ℚ",Complexes:"ℂ"},Dt={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",Implies:"sympy_implies",Equivalent:"sympy_iff",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:""},Ut={open:"()",Lopen:"(]",Ropen:"[)"};const Vt=e=>{const t=/^\((.*)\)$/s.exec(e.trim());return t?Mt(t[1]):null},Ht=e=>t=>2===t.length&&`${e[0]}${t[0]}, ${t[1]}${e[1]}`,Gt=e=>Vt(e)??[e],Qt={where:e=>3===e.length&&`((${e[0]}) ? (${e[1]}) : (${e[2]}))`,both:e=>2===e.length&&`((${e[0]}) & (${e[1]}))`,either:e=>2===e.length&&`((${e[0]}) ∨ (${e[1]}))`,np_times:e=>2===e.length&&`((${e[0]}) * (${e[1]}))`,np_equal:e=>2===e.length&&`((${e[0]}) = (${e[1]}))`,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]}) ∈ ${Ot(e[1])})`,contains:e=>2===e.length&&`((${e[1]}) ∈ ${Ot(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]}))`,radians:e=>1===e.length&&`((${e[0]})°)`,degrees:e=>1===e.length&&`((${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]}))`,...Object.fromEntries([2,3,4].map(e=>[`mat${e}`,t=>t.length===e*e&&`[${Array.from({length:e},(n,r)=>`[${Array.from({length:e},(n,s)=>t[s*e+r]).join(", ")}]`).join(", ")}]`])),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(Nt).join(" & ")})`,sympy_or:e=>e.length&&`(${e.map(Nt).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_implies:e=>2===e.length&&`((${e[0]}) \\implies (${e[1]}))`,sympy_iff:e=>2===e.length&&`((${e[0]}) \\iff (${e[1]}))`,sympy_nor:e=>2===e.length&&`((${e[0]}) \\nor (${e[1]}))`,sympy_piecewise:e=>{const t=e.map(Vt);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:Ht("[]"),sympy_interval_open:Ht("()"),sympy_interval_Lopen:Ht("(]"),sympy_interval_Ropen:Ht("[)"),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=Gt(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&&Gt(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&&Gt(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:Xt("sum"),prod:Xt("prod")};function Xt(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=Mt(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 Jt(e){e=function(e){for(let t=e.lastIndexOf("(lambda");t>=0;t=t>0?e.lastIndexOf("(lambda",t-1):-1){const n=qt(e,t);if(n<0||"("!==e[n+1])continue;const r=qt(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=Mt(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=At(e,St("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=At(e,St(Object.keys(Qt).join("|")),(e,t)=>Qt[t[1]](e)||null);for(let t=(e=At(e,St("float"),(e,t,n)=>{if(1!==e.length)return null;const r=/^\s*\.is_integer\(\s*\)/.exec(n);return r?[`((${e[0]}) ∈ ℤ)`,r[0].length]:`(${e[0]})`})).lastIndexOf(".includes(");t>=0;t=t>0?e.lastIndexOf(".includes(",t-1):-1){const n=t+9,r=qt(e,n);let s=t;if(kt.includes(e[t-1])){let n=0;for(s=t-1;s>=0;s--)if(kt.includes(e[s]))n++;else if($t.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)}) ∈ ${Ot(e.slice(s,t))})${e.slice(r+1)}`)}return e}for(const e of[It,jt,Zt,Ft,Pt,Wt,Dt,Ut,Qt,Rt])Object.setPrototypeOf(e,null);const Yt=String.raw`(?:\([^()]*\)|\[[^\[\]]*\]|\{[^{}]*\}|(?<![\w.′^])[\w.′^]+)`,Kt=e=>e.trim().split(/\s+/).join(String.raw`\s+`),en=e=>new RegExp(String.raw`(?<![\w.])${Kt(e)}(?![\w.])`,"gi"),tn=[["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","="]],nn="[<>≤≥=≠≈]",rn={second:2,third:3,fourth:4,fifth:5,sixth:6,seventh:7,eighth:8,ninth:9,tenth:10};Object.setPrototypeOf(rn,null);const sn=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",arcsecant:"arcsec",arccosecant:"arccsc",arccotangent:"arccot","hyperbolic sine":"sinh","hyperbolic cosine":"cosh","hyperbolic tangent":"tanh",floor:"floor",ceiling:"ceil"}).sort((e,t)=>t[0].length-e[0].length),on=[["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 an integer","∈ ℤ"],["is not an integer","∉ ℤ"],["is a natural number","∈ ℕ"],["is a real number","∈ ℝ"],["is real","∈ ℝ"],["is a rational number","∈ ℚ"],["is rational","∈ ℚ"],...[["the integers","ℤ"],["the natural numbers","ℕ"],["the real numbers","ℝ"],["the rational numbers","ℚ"],["the complex numbers","ℂ"]].flatMap(([e,t])=>[[`is not in ${e}`,`∉ ${t}`],[`is in ${e}`,`∈ ${t}`]])],an=/(?<![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;tn.map(([e])=>e),on.map(([e])=>e),sn.map(([e])=>`${e} of`);const ln=de([[" 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 ","→"],["===","=...="]]),un=de([...ye,...function(){const e=[],t=(t,n)=>{e.push([t,n],[t+"(",n+"("])};for(const n of["sin","cos","tan","cot","csc","sec"]){e.push(["Math."+n+"(",n+"("],["\\"+n+"(",n+"("],["\\"+n,n]);for(const e of["sin","cos","tan"].includes(n)?["","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}()]),cn=[["code",function(e){return/^\s*=|[(.%^<_eE]|\|\||\bif\b|\b(?:True|False|None|TRUE|FALSE|NULL)\b/.test(e)?(/^\s*=(?!=)/.test(e)&&(e=_t(e)),e=function(e){for(const[t,n]of Et)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]?qt(e,s):-1;if(i<0)continue;let o=e.slice(s+1,i);"gcd"===t&&(o=o.trim().replace(/^\[|\]$/g,""));const a="times"===t||"same"===t?Mt(o):null,l="factorial"===t?`((${o})!)`:2===a?.length?`((${a[0]}) ${"times"===t?"*":"="} (${a[1]}))`:`${t}(${o})`;e=e.slice(0,r)+l+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=qt(e,n),s=e.lastIndexOf("Number(",t);r<0||s<0||qt(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),e=function(e){return e.includes("set")?Lt(At(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&&qt(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=Bt(e=Ct(e=(e=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($t.includes(e[t]))s++;else{if(kt.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(kt.includes(e[t]))s++;else{if($t.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=Jt(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(!an.test(e))return e;let t=e;const n=(e,n,r,s="∈")=>{t=t.replace(new RegExp(String.raw`(?<![\w.])${Kt(e)}\s+(${Yt})\s+(?:and|to)\s+(${Yt})(?:\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+(${Yt})\s+to\s+(${Yt})`,"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`(${Yt})\s+`;t=t.replace(new RegExp(r+String.raw`is\s+(not\s+)?within\s+(${Yt})\s*(%|\s+percent)?\s+of\s+(${Yt})`,"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+(${Yt})`,"gi"),"(($1) mod ($2) = 0)"),t=t.replace(new RegExp(r+String.raw`is\s+(not\s+)?divisible\s+by\s+(${Yt})`,"gi"),(e,t,n,r)=>`((${t}) mod (${r}) ${n?"≠":"="} 0)`),t=t.replace(new RegExp(String.raw`(${Yt})\s+divides\s+(${Yt})`,"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)`),t=t.replace(new RegExp(r+String.raw`is\s+(not\s+)?a\s+whole\s+number(?![\w.])`,"gi"),(e,t,n)=>n?`((${t}) ∉ ℤ ∨ (${t}) < 0)`:`((${t}) ∈ ℤ & (${t}) ≥ 0)`);for(const[e,n]of on)t=t.replace(en(e),` ${n} `);t=t.replace(en("is not in")," ∉ ").replace(en("is in")," ∈ ").replace(en("is an element of")," ∈ ");for(const[e,n]of tn)t=t.replace(en(e),` ${n} `);t=t.replace(en("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`(${Yt})\s*(${nn})\s*(${Yt})\s+(and|or)\s+(${nn})`,"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+(${Yt})`,"gi"),"abs($1)"),t=t.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?square\s+root\s+of\s+(${Yt})`,"gi"),"sqrt($1)"),t=t.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?cube\s+root\s+of\s+(${Yt})`,"gi"),"root(3, $1)"),t=t.replace(new RegExp(String.raw`(${Yt})\s+to\s+the\s+power\s+of\s+(${Yt})`,"gi"),"($1)^($2)"),t=t.replace(new RegExp(String.raw`(${Yt})\s+to\s+the\s+(${Object.keys(rn).join("|")}|(\d+|n)(?:st|nd|rd|th))(?:\s+power)?(?![\w.])`,"gi"),(e,t,n,r)=>`(${t})^(${rn[n.toLowerCase()]??r})`),t=t.replace(new RegExp(String.raw`(${Yt})\s+to\s+the\s+(${Yt})(?![\w.])`,"gi"),"($1)^($2)");for(const[e,n]of sn)t=t.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?${Kt(e)}\s+of\s+(${Yt})`,"gi"),`${n}($1)`);t=t.replace(new RegExp(String.raw`(${Yt})\s+squared(?![\w.])`,"gi"),"($1)^2"),t=t.replace(new RegExp(String.raw`(${Yt})\s+cubed(?![\w.])`,"gi"),"($1)^3"),t=t.replace(new RegExp(String.raw`(?<![\w.])half\s+of\s+(${Yt})`,"gi"),"($1)/2"),t=t.replace(new RegExp(String.raw`(?<![\w.])twice\s+(${Yt})`,"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+)${Kt(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",ln],["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(;we(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(;we(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(Le,(e,t,n)=>`(${t}+${Fe[n]})`),e=e.replace(Re,(e,t,n,r)=>Number(n)<Number(r)&&3!==n.length?`(${t}+${n}/${r})`:e),e.replace(Be,(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(Ze,e=>{const t=e[0]in Te;return`${t?"^":"_"}{${[...e].map(e=>(t?Te:Ce)[e]).join("")}}`})}(e))),e=function(e){return e.replace(/(?:\{\s*\}|(?<![\w}\])′]))_\s*(?:\{\s*([^{}]+?)\s*\}|([A-Za-z0-9]+?))\s*(?:\\mathrm\{([CP])\}|([CP]))\s*_\s*(?:\{\s*([^{}]+?)\s*\}|([A-Za-z0-9]))/g,(e,t,n,r,s,i,o)=>`${"C"===(r??s)?"comb":"perm"}(${t??n},${i??o})`)}(function(e){return e.replace(/(?<![A-Za-z\\])([A-Za-z])\^\s*\{?\s*\(\s*([1-9]\d*)\s*\)\s*\}?(?=\s*\()/g,(e,t,n)=>{if(n.length>3||Number(n)>je)throw new Error(`A derivative f^{(n)} is read up to n = ${je}`);return t+"′".repeat(Number(n))})}(function(e){return e.replace(/(?<![A-Za-z\\])(arc)?(sine|cosine|tangent|secant|cosecant|cotangent)(?![A-Za-z])(?=\s*\(|\s+(?:[A-Za-z](?![A-Za-z])|\d|\\))/gi,(e,t,n)=>(t?"arc":"")+_e[n.toLowerCase()])}(e))),e=function(e){if(/\\[io]*int|∫|(?<![A-Za-z])int\(|\\partial|∂|(?<![A-Za-z])d\s*\/\s*d|frac\s*\{\s*(?:\\mathrm\s*\{\s*d\s*\}|\\operatorname\s*\{\s*d\s*\}|d)/.test(e))return e;const t=[];for(const n of e.matchAll(qe)){const r=e.slice(0,n.index),s=e.slice(n.index+n[0].length),i="d"!==n[1];if(!i&&(/[A-Za-z0-9\\^_/]$|frac\s*\{$/.test(r)||/^\s*[/}]/.test(s)&&!/\{\s*$/.test(r)))continue;const o=i||/\\[,;:! ]\s*$/.test(r);t.push({m:n,strong:o})}const n=t.length>=2?t:t.filter(e=>e.strong);for(const{m:t}of n.reverse())e=e.slice(0,t.index)+ke+t[2]+e.slice(t.index+t[0].length);return e}(e),/\\/.test(e)||(e=Me(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=De(e,n+2,"then");if(r<0)return e;const s=e.slice(n+2,r),i=De(e,r+4,"else"),o=Ue(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.replace(/(?<![.\w=])\.\.\.(?![.\w=])/g,"⋯").replace(/∅/g,"\\{\\}")),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=He(e);for(let t=0;t<e.length-1;t++)if("?"===e[t]&&":"!==e[t+1])e=Ve(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=e.replace(/(?<![\d.])\d{1,3}(?:[ \u00A0\u202F]\d{3})+(?![\d])/g,e=>e.replace(/[ \u00A0\u202F]/g,""))).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)||/[A-Za-z\u0370-\u03FF′]/.test(r)&&/^\\[A-Za-z]/.test(e.slice(n+t.length,n+t.length+2))&&!/\\[A-Za-z]+$/.test(e.slice(0,n))||/[A-Za-z\u0370-\u03FF′]/.test(r)&&/\d/.test(s)&&!/\\[A-Za-z]+$/.test(e.slice(0,n))?" ":/\d/.test(r)&&/\d/.test(s)&&!/\\[A-Za-z]+\s*\d*$/.test(e.slice(0,n))?"*":""})}],["symbols",un],["bar",function(e){let t=0;for(let n=e.indexOf(d,t);n>=0;n=e.indexOf(d,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&&hn(),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)+at(e.slice(r,t+1),"x",s)+e.slice(t+1+s),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&&nt.test(e[t-1]);let r,s=null,i=t;if(e.startsWith("frac{",t)){const n=rt(e,t+4),r=n&&rt(e,n[1]);s=r&&it(n[0],r[0]),s&&(i=r[1])}else if("d"===e[t]&&!n){let[n,r]=st(e,t+1),o="";if(nt.test(e[r]??"")&&"/"===e[r+1]&&(o=e[r++]),"/"===e[r]&&"d"===e[r+1]&&nt.test(e[r+2]??"")){const t=e[r+2],[,a]=st(e,r+3);s={n:n,of:o,by:t},i=a}}if(s){if(s.of)r=at(s.of,s.by,s.n);else{const[t,n]=ot(e,i);if(!t)continue;r=at(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=Je(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"+Qe(e.slice(t+1)):"sqrt"===r(4)&&(e=e.slice(0,t-4)+"sqrt"+Qe(e.slice(t+1)));else if("⌊"===n||"⌈"===n)e=e.slice(0,t)+Ge(e.slice(t));else if("t"===n)"\\int"===s(3)&&(e=e.slice(0,t-3)+Ke(e.slice(t+1)));else if("m"===n)"\\binom"===s(5)&&(e=e.slice(0,t-5)+"\\binom"+tt(e.slice(t+1)));else if("d"===n&&"dd"===s(1)&&"("===e[t+2]){const n=et(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(d);t>=0;t=e.indexOf(d)){const n=hn;e.startsWith("(der(",t+1)||n();const r=fn(e,t+1,"(",")"),s=fn(e,t+5,"(",")");(s<0||r!==s+1)&&n();const i=pn(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=fn(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 f=a.includes("=")?a:`${c}=${a}`;e=`${e.slice(0,t)}der(${u},${f}${h?`,${h}`:""})${e.slice(l+1)}`}return e}],["tidy",e=>e.replace(/ {2,}/g," ").trim()]],hn=()=>{throw new Error("A bar with one limit (\\left. … \\right|_{x = a}) is read only after a derivative, \\left.\\frac{d}{dx} f\\right|_{x=a}; with two, \\left. F \\right|_a^b, it is F at b minus F at a")};function fn(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 pn(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 mn(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=ct(t.size);t.set(l,s+o+s),n+=l,r=i+1}return{text:n,strings:t}}(ft(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&&dn.test(e.slice(0,i));if(gn(e,i)||a&&"{"===e[i+2]?i+=1:o=a,!e.startsWith("{{",i)){s=i;continue}const l=vn(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=ct(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 cn){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 dn=/(?:\\[A-Za-z]+\*?|[\^_}\]])$/;function gn(e,t){let n=0;for(;"\\"===e[t-1-n];)n++;return n%2==1}function vn(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 bn=Object.keys(g).filter(e=>100===g[e]&&/^[a-z]{2,}$/.test(e)),yn=["frac"],wn=[...Object.keys(T),"pi","tau","inf","infinity","exp"],xn="\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+/),$n=new Set([...wn,...xn,"simplify","expand","factor","cancel","diff","integrate","solve","approx","limit","true","false","null","undefined","unchanged","deg","mod","pmod","NaN","Infinity"]),kn=/^[a-zA-ZͰ-Ͽ]$/,qn=new Set(["f","g","h","u","v","F","G","H"]),Mn=e=>bn.includes(e)||yn.includes(e),An=[...bn,...yn,...wn].sort((e,t)=>t.length-e.length),Sn=[...bn,...yn,"pi"].sort((e,t)=>t.length-e.length);function Nn(e,t=An){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 On(e){if(Mn(e))return!0;const t=Nn(e,Sn);return t.length>1&&Mn(t[t.length-1])&&!$n.has(e)}function En(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=>kn.test(e)))||1===e.length||$n.has(e)||Mn(e))return[e];var r;if("Δ"===e[0]&&2===e.length)return[e];if("latex"===t)return In(Nn(e),n);if(e.length<=2)return[...e];const s=In(Nn(e,Sn),n),i=s.findIndex(e=>e.length>1);if(i<0)return[e];if("pi"===s[i]&&!s.some(e=>bn.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 In(e,t){const n=e[e.length-1];return t||!bn.includes(n)?e:[...e.slice(0,-1),...n]}const zn="§",_n=/[A-Za-zͰ-Ͽ′]/,jn=e=>/^[A-Za-zͰ-Ͽ][A-Za-zͰ-Ͽ′]*$/.test(e);function Tn(e,t="plain"){if("string"!=typeof e)throw new Error("Tokenizer input must be a string");const n=[];let r="";const s=e=>{r&&(jn(r)?n.push(...function(e,t,n){if((e=>ht.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 qn.has(e)?[i+e]:[e];if(v(e))return[e];const n=En(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 En(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===zn){s(o);const r=e.indexOf(zn,t+1);if(r<0)throw new Error(`An unmatched ${zn}`);const a=e.slice(t,r+1);n.push(y.includes(e[r+1])?i+a:a),t=r;continue}if("ⅆ"===o&&/[A-Za-z\u0370-\u03FF]/.test(e[t+1]??""))r&&s(o),r="",n.push("d"+e[t+1]),t+=1;else{if(jn(r)&&/[0-9]/.test(o)&&v(r+o)){const{op:s,end:i}=Cn(e,t,r+o);n.push(s),r="",t=i;continue}if(_n.test(o)&&"′"!==o&&x(r)&&(n.push(r),r=""),_n.test(o)&&(""===r?"′"!==o:jn(r)))r+=o;else if(/[0-9]/.test(o)&&jn(r)&&!On(r))r+=o;else if(jn(r)&&s(" "===o?e[t+1]:o),"(){}[]".includes(o))r&&n.push(...Zn(r,o)),r="",n.push(o);else if("_"!==o&&" "!==o){if(v(r+o)){const{op:s,end:i}=Cn(e,t,r+o);n.push(s),r="",t=i;continue}if(v(o)){s(o);const{op:r,end:i}=Cn(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 Cn(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 Zn(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)||Mn(e)||x(e[0])?[e]:[i+e]}const Fn=70,Ln=100,Rn="%mod",Bn=/^d[A-Za-z\u0370-\u03FF]$/,Pn=e=>y.includes(e),Wn=e=>w.includes(e),Dn=e=>o(e)||g[e]===Ln&&"_"!==e,Un=new Set(["\\comb","\\perm","comb","perm"]),Vn={frac:"/","\\binom":"\\binom"},Hn=new Set(["<",">","≤","≥","=","==","===","≠","≠=","!=","!==","&","|","\\not","\\xor","\\implies","\\iff","∈","∉","true","false"]),Gn={"\\comb":"comb","\\perm":"perm",deg:"°","π":"pi","∨":"|"};class Qn{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(Wn(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||Wn(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===Rn)return{lbp:Fn,run:()=>{this.next(),this.parseExpression(Fn),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:Ln,run:()=>{this.next(),this.parseScript(),this.emit("_")}};if(Un.has(e))return{lbp:Ln,run:()=>{this.next(),this.parseExpression(Ln),this.emit(e)}};const n=g[e];if("="===e&&void 0!==n)return{lbp:n,run:()=>this.equals(n)};if(void 0!==n&&!Dn(e)&&"\\not"!==e&&!(e in Vn)){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||Dn(e)||Bn.test(e)?Fn:71,run:()=>{this.parseExpression(Fn),this.emit("*")}}}startsOperand(e){return void 0===e||Wn(e)||"|"===e?"|"===e:e!==Rn&&(!!(Pn(e)||Dn(e)||e in Vn)||!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(Fn,!0),this.emit("mod")}equals(e){this.next(),this.parseExpression(e),Hn.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(Pn(n))e++;else if(Wn(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(Pn(e))return this.bracket(e,"{"===e&&("∈"===t||"∉"===t));if("|"===e)return this.absolute();if("-"===e||"+"===e){return"^"===t&&(void 0===n||Wn(n))||Pn(t)&&Wn(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 Vn)return this.parseScript(),this.parseScript(),this.emit(Vn[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(Dn(e))return this.functionCall(e);if(e===Rn)throw new Error("'%' is missing an operand");if(Wn(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(Wn(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();Wn(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(Pn(e))return this.parseOperand();if("-"===e||"+"===e)return this.parseOperand();if(Dn(e))return this.parseOperand();if(this.next(),void 0===e||Wn(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&&!Pn(this.peek()))return this.emit(e);this.argument(),this.emit(e),t&&this.emit(...t,"^")}argument(){const e=this.peek();if(Pn(e))return this.next(),this.bracket(e);this.parseExpression(Fn,!0)}}function Xn(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(qn.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)||Pn(r)||Wn(r)||"_"===r||o(r)||x(r)?n.push(r):n.push(...Jn(r,t));return n}function Jn(e,t){if("%"===e)return[Rn];if(!e.includes("%"))return Yn(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(Rn),""!==e&&r.push(...Yn(e,t))}),r}function Yn(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,Xn(Tn(s,t),t))];var s}for(const e of[Vn,Gn])Object.setPrototypeOf(e,null);const Kn=new Set(["()","[]","{}","(]","[)"]),er={pow:"^",sqrtpow:"root","\\binom":"comb","\\comb":"comb","\\perm":"perm",frac:"/","==":"=","!==":"≠=",...Object.fromEntries(Object.keys(m).map(e=>[e,"*"]))},tr=new Set(["round","fixed","der"]),nr=e=>o(e)||100===g[e];function rr(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(Kn.has(o)){const t=s(r(o));if(!t.length&&"{}"!==o&&!nr(e[l+1]))throw new Error("Empty brackets");return void n.push(A(o,t))}const u=er[o]??o,c=a(u);if(!c){if("?"===o||"abs("===o)throw new Error(`Unmatched '${o[0]}'`);return void n.push(N(o))}let h;if(nr(o)&&Kn.has(e[l-1])&&n[n.length-1]?.op===e[l-1])h=n.pop().args;else{let e=c.arity===t||tr.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 f=function(e,t){switch(e){case"sqrt":if(2===t.length)return A("root",t);break;case"round":if(1===t.length)return A("round",[t[0],q(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 A("sum"===e?"\\sumidx":"\\prodidx",t);break}case"evaluated":if(3===t.length)return A("evaluated",[t[0],M(j(t[0])||"x"),t[1],t[2]]);break;case"det":if(t.length>1&&t.every(e=>"op"===e.type&&"[]"===e.op))return A("det",[A("[]",t)]);break;case"fixed":if(1===t.length)return A("fixed",[t[0],q(2)]);break;case"der":if(1===t.length)return A("der",[t[0],M("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=A("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 A("ln",[t[1]]);break;case"lim":return ir(e,t),A("lim",function(e){const t=e=>{if("op"!==e.type)return null;if("^"===e.op&&"symbol"===e.args[1].type&&sr[e.args[1].value])return{point:e.args[0],side:sr[e.args[1].value]};const n=e.args.length?t(e.args[e.args.length-1]):null;return n&&{point:{...e,args:[...e.args.slice(0,-1),n.point]},side:n.side}},[n,r,s]=e;if(2===e.length&&"op"===r.type&&"→"===r.op){const[e,s]=r.args,i=t(s);if(i)return[n,e,i.point,M(i.side)]}const i=3===e.length&&t(s);return i?[n,r,i.point,M(i.side)]:e}(t));case"\\:if":if(2===t.length||3===t.length)return A("?:",[t[0],t[1],t[2]??M("unchanged")]);throw new Error("if() takes a condition, a value, and optionally an alternative")}return ir(e,t),A(e,t)}(u,h);m[o]&&"*"===f.op&&(f.written=m[o]),n.push(f)}),1!==n.length)throw new Error(n.length?"Some values are not connected by an operator":"Empty expression");const o=["=","<",">","≤","≥","≠","≈","≡","∈","∉"],l=n[0];return l.list&&l.list.length>1&&l.list.every(e=>"op"===e.type&&o.includes(e.op))?l.list.reduce((e,t)=>A("&",[e,t])):i(n[0],"end")}const sr={"\\+":"r","\\-":"l"};function ir(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[er,sr])Object.setPrototypeOf(e,null);const or=new RegExp(`[${Object.keys(m).join("")}]`,"g"),ar=e=>e.replace(or,"*"),lr=/\\(?:text|textrm|textit|mathrm|mathit|operatorname)\{\s*([A-Za-z][A-Za-z0-9 ]*[A-Za-z0-9])\s*\}/g;const ur=e=>/^[a-z][a-z0-9]*$/.test(e)&&v(e);function cr(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=We(e.slice(t+13,n),"\\\\").map(e=>We(e,"&")).filter(e=>e.join("").trim());let s=null;const i=/=|<|>|\\(?:le|ge|leq|geq|neq|ne|lt|gt)(?![A-Za-z])/;if(r.length>1&&r.every(e=>1===e.length&&i.test(e[0])))s=r.map(e=>`(${e[0].trim().replace(/\s*[,;.]$/,"")})`).join(" \\land "),e=e.slice(0,t)+`(${s})`+e.slice(n+11);else{for(let e=r.length-1;e>=0;e--){const t=r[e][0].trim().replace(/\s*[,;]$/,""),n=Pe(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=function(e){return e=ze(e),e=Me(e),e=e.replace(/\\(?:[Bb]igg?)[lrm]?(?![A-Za-z])\s*/g,""),e=e.replace(/\^\s*(?:\\circ\b|\{\s*\\circ\s*\})|\\degree\b|\\textdegree\b/g,"°"),e=e.replace(/\\(?:cdots|ldots|dotsb|dotsc|dots)(?![A-Za-z])/g,"⋯"),e=e.replace(/(\d*)\.(\d*)\\overline\s*\{\s*(\d+)\s*\}/g,(e,t,n,r)=>`${t||"0"}.${n}${r}${r}..`),e=e.replace(/\\(?:emptyset|varnothing)(?![A-Za-z])/g,"\\{\\}"),e=e.replace(/\(\s*([A-Za-z])\s*\\circ\s*([A-Za-z])\s*\)\s*\(([^()]*)\)/g,"$1($2($3))"),e}(e),e.replace(/\{\}\^\{([^{}]*)\}\s*\\mathrm\{P\}\s*_\{([^{}]*)\}/g,"\\perm($1,$2)")):/[\]|]\s*_/.test(e)?ze(e):e}let hr=null;function fr(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=ft(e);let s="";for(let i=0;i<r.length;i++){const o=r[i];if('"'===o||"`"===o||"'"===o){const o=pt(r,i);s+=e.slice(i,o+1).replaceAll(t,n),i=o}else s+=e[i]}return s}(e,zn,"")).includes(zn))throw new Error(`The character ${zn} 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=`${zn}${r.size}${zn}`,r.set(t,e),s.set(e,t)),t};e=e.replace(lr,(e,t)=>ur(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}}(cr(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?hr:t.blocks;return mn(e,{evaluate:n?e=>n(e,t.scope):void 0})}(o,{blocks:t.blocks,scope:t.scope}),f=e=>dt(dt(e,c),a).map(e=>"string"==typeof e?e.replaceAll("",zn):e);n.mode=l,n.cleaned=ar(f([u])[0]),n.cleanSteps=h.map(([e,t])=>[e,ar(t)]);const p=Tn(u,l);n.tokens=p.map(ar);const m=f(function(e,t="plain"){return new Qn(Xn(e,t)).parseAll().map(e=>Gn[e]??e)}(p,l));n.rawPostfix=m.map(ar);const d={},g=I(rr(m),d);n.postfix=g,n.written=d,n.tree=E(g),Object.keys(d).length&&_(n.tree,e=>{d[e.id]&&(e.written=d[e.id])})}catch(e){n.error=e instanceof RangeError?"Nested too deeply":e.message}return n}const pr=e=>"string"==typeof e&&e.length>80?`${e.slice(0,77)}…`:e;function mr(e,t={}){const n=fr(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 "${pr(e)}": ${n.error}`)}function dr(e,t={}){const n=fr(e,t);if(n.error)throw new Error(`Failed to parse expression "${pr(e)}": ${n.error}`);return n.tree}const gr=(e,t)=>"string"==typeof e?dr(e,t):z(e),vr=e=>Array.isArray(e)&&0===e.length,br=me({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(Tr+=e/16,Tr>jr)throw new Error("Too much to work out")},fail:e=>{throw new Error(e)}}),yr=e=>fe(e)&&(e.length>1||e[0].length>1),wr=e=>pe(e)&&!yr(e),xr=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},$r=(e,t)=>yr(e)&&yr(t)?br.times(e,t):yr(e)&&wr(t)?br.timesVector(e,t):wr(e)&&yr(t)?br.vectorTimes(e,t):xr((e,t)=>e*t)(e,t),kr=(e,t)=>n=>{const r=n.length>1&&n.every(wr)?n:n[0];if(!fe(r))throw new Error(`${t}() needs a matrix`);return e(r)},qr=(e,t)=>([n,r])=>{if(!pe(n)||!pe(r))throw new Error(`${t}() needs two lists`);return e(n,r)},Mr={det:kr(br.det,"det"),inv:kr(br.inverse,"inv"),inverse:kr(br.inverse,"inverse"),transpose:kr(br.transpose,"transpose"),trace:kr(br.trace,"trace"),tr:kr(br.trace,"tr"),rank:kr(br.rank,"rank"),rref:kr(br.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 br.identity(e)},dot:qr(br.dot,"dot"),cross:qr(br.cross,"cross"),linsolve:([e,t])=>{if(!fe(e)||!Array.isArray(t))throw new Error("linsolve() needs a matrix and a list");return br.solve(e,t)}},Ar=(e,t)=>e.args.map(e=>"op"===e.type&&"[]"===e.op?e.args.map(e=>Zr(e,t)):[Zr(e,t)]),Sr={pi:Math.PI,"π":Math.PI,e:Math.E,tau:2*Math.PI,"τ":2*Math.PI,"∞":1/0,"-∞":-1/0,true:!0,false:!1,"°":Math.PI/180},Nr=(e,t)=>t?Nr(t,e%t):Math.abs(e),Or=(e,t)=>(e%t+t)%t,Er=(e,t)=>Array.isArray(e)&&Array.isArray(t)?e.length===t.length&&e.every((e,n)=>Er(e,t[n])):e==t,Ir={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=>Mr.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,arcsec:e=>Math.acos(1/e),arccsc:e=>Math.asin(1/e),arccot:e=>Math.PI/2-Math.atan(e),arcsinh:Math.asinh,arccosh:Math.acosh,arctanh:Math.atanh},zr={"+":(e,t)=>Array.isArray(e)||Array.isArray(t)?xr((e,t)=>e+t)(e,t):e+t,"-":(e,t)=>Array.isArray(e)||Array.isArray(t)?xr((e,t)=>e-t)(e,t):e-t,"*":$r,"/":(e,t)=>yr(t)?$r(e,br.inverse(t)):Array.isArray(e)||Array.isArray(t)?xr((e,t)=>e/t)(e,t):e/t,"^":(e,t)=>{if(!yr(e))return Array.isArray(e)?xr((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 br.power(e,BigInt(t))},mod:Or,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)},"=":Er,"===":(e,t)=>e===t,"≠":(e,t)=>!Er(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),"\\implies":(e,t)=>!e||Boolean(t),"\\iff":(e,t)=>Boolean(e)===Boolean(t)},_r={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(Nr,0),"()":e=>e,"[]":e=>e,"{}":e=>e};const jr=5e6;let Tr=0,Cr=0;function Zr(e,t){if(++Tr>jr)throw new Error("Too much to work out");switch(e.type){case"number":return e.value.endsWith("..")?Number(function(e){const t=function(e){const t=/^(-?)(\d*)\.(\d+)\.\.$/.exec(e);if(!t)return null;const[,n,r,s]=t;let i=1;for(let e=1;2*e<=s.length;e++)if(s.slice(-e)===s.slice(-2*e,-e)){i=e;break}const o=s.slice(-i);let a=s;for(;a.endsWith(o);)a=a.slice(0,-i);return{sign:n,whole:r||"0",prefix:a,block:o}}(e);if(!t)return e.replace(/\.+$/,"");const{sign:n,whole:r,prefix:s,block:i}=t;return`${n}${r}.${(s+i.repeat(Math.ceil(20/i.length)+1)).slice(0,Math.max(s.length+i.length,17))}`}(e.value)):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(Sr,e.value))return Sr[e.value];if(R(e.value))return Number(R(e.value));throw new Error(`No value for '${e.value}'`)}const n=ue(e);if(n)return Zr(n,t);const{op:r,args:s}=e;if("?:"===r)return Zr(s[0],t)?Zr(s[1],t):Zr(s[2],t);if("setbuilder"===r)throw new Error("A set described by a condition has no list of values (test membership in it: y ∈ {x | P})");if(("∈"===r||"∉"===r)&&L(e))return Zr(L(e),t);if("∈"===r||"∉"===r){const n=function(e){if("op"!==e.type||"∈"!==e.op&&"∉"!==e.op||2!==e.args.length)return null;const[t,n]=e.args;return"string"===n.type||e.textSearch?{text:t,within:n}:"string"!==t.type||("op"===n.type?te.has(n.op):"symbol"===n.type&&/^[ℝℤℕℚℂ∅]$/u.test(n.value))?null:{text:t,within:n}}(e);if(n){const e=Zr(n.within,t);if(!Array.isArray(e))return re(e).includes(re(Zr(n.text,t)))===("∈"===r)}else if("symbol"===s[1].type&&t&&Object.prototype.hasOwnProperty.call(t,s[1].value)){const e=Zr(s[1],t);if("string"==typeof e)return re(e).includes(re(Zr(s[0],t)))===("∈"===r)}return function(e,t){const[n,r]=e.args,s=Zr(n,t);let i;if("symbol"===r.type&&Fr[r.value])return i=Fr[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=>Zr(e,t)),o="["===r.op[0]?s>=e:s>e,a="]"===r.op[1]?s<=n:s<n;i=o&&a}else{const e=Zr(r,t);i=Array.isArray(e)&&e.includes(s)}return"∈"===e.op?i:!i}(e,t)}if(ne(r)){const[n,r]=function(e){if(2!==e.args.length)throw new Error('startswith takes a value and the text it starts with: startswith(name, "Mc")');return e.args}(e).map(e=>Zr(e,t));return re(n).startsWith(re(r))}if("random"===r)return Math.random();if("evaluated"===r){const[e,n,r,i]=s,o=r=>Zr(e,{...t,[n.value]:Zr(r,t)});return o(i)-o(r)}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:j(n);if(!a)throw new Error(`Can't evaluate '${r}' without an index`);const l=Zr(i,t),u=Zr(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=Zr(n,{...t,[a]:e});c="\\sumidx"===r?c+s:c*s}return c}if("pmod"===r){const[e,n]=s,r=Zr(n,t);if("op"===e.type&&["≡","="].includes(e.op)){const[n,s]=e.args.map(e=>Zr(e,t));return(n-s)%r===0}return Or(Zr(e,t),r)}if("pmatrix"===r||"bmatrix"===r)return Ar(e,t);if("vmatrix"===r)return br.det(Ar(e,t));if("^"===r&&"symbol"===s[1].type&&"T"===s[1].value&&!Object.prototype.hasOwnProperty.call(t,"T")){const e=Zr(s[0],t);if(yr(e))return br.transpose(e)}const i=s.map(e=>Zr(e,t));if(r.startsWith("\\:")&&Object.prototype.hasOwnProperty.call(Mr,r.slice(2)))return Mr[r.slice(2)](i);if(Ir[r]&&1===i.length)return Ir[r](i[0]);if(zr[r]&&2===i.length)return zr[r](i[0],i[1]);if(_r[r])return _r[r](i);throw new Error(`Can't evaluate '${r}'`)}const Fr={"ℝ":Number.isFinite,"ℤ":Number.isInteger,"ℕ":e=>Number.isInteger(e)&&e>0,"ℚ":Number.isFinite,"ℂ":e=>"number"==typeof e&&!Number.isNaN(e)};for(const e of[Sr,Ir,zr,_r,Fr,Mr])Object.setPrototypeOf(e,null);class Lr extends Error{}class Rr extends Error{}class Br extends Rr{}const Pr={bits:2e5,factorial:2e4,terms:1e5,rootIndex:12,steps:5e6,places:1e4};let Wr=0;function Dr(e){if(Wr+=e,Wr>Pr.steps)throw new Rr("too much to work out")}const Ur=(e,t)=>Dr(Number(e)*(t/64)/128);let Vr=0;const Hr=e=>e<0n?-e:e,Gr=0xFFFFFFFFFFFFn,Qr=e=>0n===e?0:Hr(e).toString(2).length;function Xr(e,t){for(e=Hr(e),t=Hr(t);t;)[e,t]=[t,e%t];return e}function Jr(e,t=1n){if(0n===t)throw new Lr("division by zero");if(t<0n&&(e=-e,t=-t),t>Gr&&(e>Gr||-e>Gr)){const n=Math.min(e.toString(16).length-(e<0n?1:0),t.toString(16).length)/16;if(Wr+=1+n*n/2,Wr>Pr.steps)throw new Rr("too much to work out")}const n=Xr(e,t)||1n;return{n:e/n,d:t/n}}const Yr=Jr(0n),Kr=Jr(1n),es=(e,t)=>Jr(e.n*t.d+t.n*e.d,e.d*t.d),ts=(e,t)=>Jr(e.n*t.n,e.d*t.d),ns=(e,t)=>Jr(e.n*t.d,e.d*t.n),rs=e=>({n:-e.n,d:e.d}),ss=(e,t)=>{const n=e.n*t.d-t.n*e.d;return n<0n?-1:n>0n?1:0},is=e=>{const t=e.n/e.d;return e.n<0n&&t*e.d!==e.n?t-1n:t};function os(e){if(e.n<0n)return-os(rs(e));const t=Qr(e.n),n=Qr(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 as(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 Rr(`'${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=es(Jr(BigInt(o||"0")),Jr(s-r,(10n**BigInt(e)-1n)*10n**BigInt(n.length)))}else l=Jr(BigInt(o+a||"0"),10n**BigInt(a.length));if(Math.abs(s)>Pr.bits/3)throw new Rr("too large to calculate");return s&&(l=s>0?ts(l,Jr(10n**BigInt(s))):ns(l,Jr(10n**BigInt(-s)))),n<0n?rs(l):l}function ls(e,t=0,n=0,r=null){return 0n===e.n?{kind:"x",c:Yr,pi:0,e:0,root:null}:{kind:"x",c:e,pi:t,e:n,root:r}}const us=(e,t=1n)=>ls(Jr(BigInt(e),BigInt(t))),cs=ls(Kr,1),hs=ls(Kr,0,1),fs=e=>null!==e&&"object"==typeof e&&"x"===e.kind,ps=e=>fs(e)&&!e.pi&&!e.e&&!e.root,ms=e=>fs(e)?0n===e.c.n:0===e,ds=e=>ps(e)&&1n===e.c.d?e.c.n:null,gs=(e,t)=>Object.assign(e,{group:t}),vs=e=>({kind:"s",text:e});function bs(e,t){return e&&t?e.n===t.n&&e.r===t.r:e===t}const ys=(e,t)=>0===ss(e.c,t.c)&&e.pi===t.pi&&e.e===t.e&&bs(e.root,t.root);function ws(e){const t=Math.max(0,Qr(e)-60);return t+Math.log2(Number(e>>BigInt(t)))}function xs(e){if("number"==typeof e)return e;if(Hs(e)&&ei(e),fs(e)){let t=os(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**(ws(e)/t)}(e.root.r,e.root.n);if(!(0n===e.c.n||0!==t&&Number.isFinite(t)&&Number.isFinite(n))){const t=ws(e.c.n<0n?-e.c.n:e.c.n)-ws(e.c.d)+ws(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 Rr("not a number")}function $s(e,...t){if(Number.isNaN(e))throw new Lr("undefined");if(!Number.isFinite(e)&&t.every(Number.isFinite))throw new Rr("too large to calculate");return e}const ks=e=>"boolean"==typeof e?e:fs(e)?0n!==e.c.n:"number"==typeof e?0!==e:Boolean(e);function qs(e){if("bigint"==typeof e)return ls(Jr(e));if("number"==typeof e)return Number.isFinite(e)?ls(Number.isInteger(e)&&Math.abs(e)<=Number.MAX_SAFE_INTEGER?Jr(BigInt(e)):as(String(e))):e;if("boolean"==typeof e)return e;if("string"==typeof e)return/^-?(\d+\.?\d*|\.\d+)(\.\.)?$/.test(e.trim())?ls(as(e)):Xi(dr(e),{});if(Array.isArray(e))return!e.group&&fe(e)?gs(e.map(e=>gs(e.map(qs),"[]")),"[]"):gs(e.map(qs),e.group||"()");if(fs(e)||"function"==typeof e)return e;throw new Rr(`can't use ${typeof e} as a value`)}function Ms(e){if(Array.isArray(e))return e.map(Ms);if(Gs(e)){const{re:t,im:n}=ti(e);return{re:xs(t),im:xs(n)}}return Hs(e)?fo(e,{decimal:!1,places:null,digits:12,maxDigits:50}):e&&"s"===e.kind?e.text:"boolean"==typeof e?e:xs(e)}function As(e,t){if(e<2n)return e;const n=BigInt(t);let r=1n<<BigInt(Math.ceil(Qr(e)/t));for(;;){const t=((n-1n)*r+e/r**(n-1n))/n;if(t>=r)return r;r=t}}function Ss(e,t,n,r=0,s=0){if(0n===n)return ls(Yr);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++}Wr+=o/4;const a=As(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=As(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?ls(ts(e,Jr(i*o.r)),r,s):ls(ts(e,Jr(i)),r,s,o)}function Ns(e,t){const n=ts(e.c,t.c);if(Qr(n.n)+Qr(n.d)>Pr.bits)return null;const r=e.pi+t.pi,s=e.e+t.e;if(!e.root||!t.root)return ls(n,r,s,e.root||t.root);const i=zi(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 Qr(o)>4e3?null:Ss(n,i,o,r,s)}function Os(e){if(0n===e.c.n)throw new Lr("division by zero");const t=ls(ns(Kr,e.c),-e.pi,-e.e);if(!e.root)return t;const{n:n,r:r}=e.root;return Qr(r)*(n-1)>4e3?null:Ns(t,Ss(Jr(1n,r),n,r**BigInt(n-1)))}function Es(e,t){if(0n===t){if(0n===e.c.n)throw new Lr("0^0 is undefined");return ls(Kr)}if(t<0n){const n=Os(e);return n&&Es(n,-t)}if((Qr(e.c.n)+Qr(e.c.d)+(e.root?Qr(e.root.r):0))*Number(t)>Pr.bits||t>100000n)return null;const n=Jr(e.c.n**t,e.c.d**t),r=Number(t);if(!e.root)return ls(n,e.pi*r,e.e*r);const{n:s,r:i}=e.root,o=i**(t/BigInt(s));return Ss(ts(n,Jr(o)),s,i**(t%BigInt(s))||1n,e.pi*r,e.e*r)}function Is(e,t,n){if(!ps(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 Lr("not a real number");o=!0,s=-s}const a=function(e,t){const n=e.n*e.d**BigInt(t-1);return Qr(n)>4e3?null:Ss(Jr(1n,e.d),t,n)}({n:s,d:i},Number(n));return a?o?ls(rs(a.c),a.pi,a.e,a.root):a:null}function zs(e){return t=>Array.isArray(t)?gs(t.map(t=>zs(e)(t)),t.group):e(t)}function _s(e){const t=(n,r)=>{const s=Array.isArray(n),i=Array.isArray(r);if(s&&i){if(n.length!==r.length)throw new Lr("lists of different lengths");return gs(n.map((e,n)=>t(e,r[n])),n.group)}return s?gs(n.map(e=>t(e,r)),n.group):i?gs(r.map(e=>t(n,e)),r.group):e(n,r)};return t}const js=(e,t)=>fs(e)&&fs(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||!bs(e.root,t.root))return null;const n=es(e.c,t.c);return Qr(n.n)+Qr(n.d)>Pr.bits?null:ls(n,e.pi,e.e,e.root)}(e,t)||$s(xs(e)+xs(t),xs(e),xs(t)),Ts=e=>fs(e)?ls(rs(e.c),e.pi,e.e,e.root):-xs(e),Cs=(e,t)=>fs(e)&&fs(t)&&Ns(e,t)||$s(xs(e)*xs(t),xs(e),xs(t)),Zs=_s((e,t)=>Hs(e)||Hs(t)?ci(e,t):js(e,t)),Fs=zs(e=>Hs(e)?hi(e):Ts(e)),Ls=(e,t)=>Zs(e,Fs(t)),Rs=_s((e,t)=>Hs(e)||Hs(t)?pi(e,t):Cs(e,t)),Bs=_s((e,t)=>Hs(e)||Hs(t)?function(e,t){if(!Hs(t)){if(ms(t))throw new Lr("division by zero");return Js(Ys(e).map(e=>({vars:e.vars,re:Ps(e.re,t),im:Ps(e.im,t)})))}if(Gs(t))return pi(e,ni(si(ti(t))));const n=function(e,t){const n=new Set(t.flatMap(e=>e.vars.map(([e])=>e)));if(1!==n.size)return null;const[r]=n,s=e=>e.vars.find(([e])=>e===r)?.[1]??0,i=t.reduce((e,t)=>s(t)>s(e)?t:e),o=s(i);if(1!==i.vars.length)return null;let a=e;const l=[];for(let e=0;e<1e3&&a.length;e++){const e=a.reduce((e,t)=>s(t)>s(e)?t:e);if(s(e)<o)return null;const n={vars:fi(e.vars,[[r,-o]]),...ri(e,si(i))};l.push(n);const u=ci(Js(a),hi(pi(Js([n]),Js(t))));a=ms(u)?[]:Ys(u)}return a.length?null:Js(l)}(Ys(e),[...t.terms.values()]);if(null===n)throw new Rr(`no value for '${Ks(t)}'`);return n}(e,t):Ps(e,t));function Ps(e,t){if(ms(t))throw new Lr("division by zero");if(fs(e)&&fs(t)){const n=Os(t),r=n&&Ns(e,n);if(r)return r}return $s(xs(e)/xs(t),xs(e),xs(t))}const Ws=_s((e,t)=>{if(Hs(e)||Hs(t))return function(e,t){if(Hs(t)){Gs(t)||ei(t),Hs(e)&&!Gs(e)&&ei(e);const n=ti(t);return fs(e)&&ys(e,hs)?ai(n):ai(ri(n,li(ti(e))))}const n=ds(t);if(null!==n)return n>=0n?mi(e,n):(Gs(e)||ei(e),mi(ni(si(ti(e))),-n));Gs(e)||ei(e);return ui(ti(e),t)}(e,t);try{return Ds(e,t)}catch(n){if(Us&&n instanceof Lr&&"not a real number"===n.message)return ui({re:e,im:us(0)},t);throw n}});function Ds(e,t){if(fs(e)&&ps(t)){const{n:n,d:r}=t.c,s=1n===r?Es(e,n):Is(e,n,r);if(s)return s}const n=xs(e),r=xs(t);if(0===n&&0===r)throw new Lr("0^0 is undefined");if(0===n&&r<0)throw new Lr("division by zero");if(n<0&&!Number.isInteger(r))throw new Lr("not a real number");const s=n**r;if(0===s&&0!==n)throw new Br("too small to calculate");return $s(s,n,r)}let Us=!1;const Vs=5e3,Hs=e=>null!==e&&"object"==typeof e&&"p"===e.kind,Gs=e=>Hs(e)&&1===e.terms.size&&e.terms.has(""),Qs=()=>Js([{vars:[],re:us(0),im:us(1)}]),Xs=e=>e.map(([e,t])=>1===t?e:`${e}^${t}`).join("*");function Js(e){const t=new Map;for(const n of e){const e=Xs(n.vars),r=t.get(e);t.set(e,r?{vars:n.vars,re:js(r.re,n.re),im:js(r.im,n.im)}:n)}for(const[e,n]of t)ms(n.re)&&ms(n.im)&&t.delete(e);if(t.size>Vs)throw new Rr("too many terms to work out");return t.size?1===t.size&&t.has("")&&ms(t.get("").im)?t.get("").re:{kind:"p",terms:t}:us(0)}function Ys(e){if(Hs(e))return[...e.terms.values()];if("boolean"==typeof e)return[{vars:[],re:us(e?1:0),im:us(0)}];if(!fs(e)&&"number"!=typeof e)throw new Rr("not a number");return[{vars:[],re:e,im:us(0)}]}const Ks=e=>[...e.terms.values()].find(e=>e.vars.length)?.vars[0][0];function ei(e){if(Gs(e))throw new Rr("a complex number has no real value here");throw new Rr(`no value for '${Ks(e)}'`)}const ti=e=>Gs(e)?e.terms.get(""):{re:e,im:us(0)},ni=({re:e,im:t})=>Js([{vars:[],re:e,im:t}]),ri=(e,t)=>({re:js(Cs(e.re,t.re),Ts(Cs(e.im,t.im))),im:js(Cs(e.re,t.im),Cs(e.im,t.re))});function si(e){const t=js(Cs(e.re,e.re),Cs(e.im,e.im));if(ms(t))throw new Lr("division by zero");return{re:Ps(e.re,t),im:Ts(Ps(e.im,t))}}const ii=e=>ms(e.im)?di(e.re,us(0))<0?Ts(e.re):e.re:Ds(js(Cs(e.re,e.re),Cs(e.im,e.im)),us(1,2));function oi(e){return ms(e.im)?di(e.re,us(0))<0?cs:us(0):ms(e.re)?di(e.im,us(0))>0?ls(Jr(1n,2n),1):ls(Jr(-1n,2n),1):Math.atan2(xs(e.im),xs(e.re))}function ai(e){const t=ms(e.re)?us(1):Ds(hs,e.re);return ni({re:Cs(t,xi("cos",e.im)),im:Cs(t,xi("sin",e.im))})}function li(e){if(ms(e.re)&&ms(e.im))throw new Lr("ln 0 is undefined");return{re:ki(ii(e)),im:oi(e)}}function ui(e,t){if(ms(e.re)&&ms(e.im))return Ds(us(0),t);const n=Ds(ii(e),t),r=Cs(t,oi(e));return ni({re:Cs(n,xi("cos",r)),im:Cs(n,xi("sin",r))})}function ci(e,t){return Js([...Ys(e),...Ys(t)])}function hi(e){return Js(Ys(e).map(e=>({vars:e.vars,re:Ts(e.re),im:Ts(e.im)})))}function fi(e,t){const n=new Map(e);for(const[e,r]of t)n.set(e,(n.get(e)??0)+r);return[...n].filter(([,e])=>0!==e).sort(([e],[t])=>e<t?-1:e>t?1:0)}function pi(e,t){const n=Ys(e),r=Ys(t);Dr(n.length*r.length);const s=[];for(const e of n)for(const t of r)s.push({vars:fi(e.vars,t.vars),...ri(e,t)});return Js(s)}function mi(e,t){if(!Gs(e)&&t>1000n)throw new Rr("too large to calculate");if(Hs(e)&&!Gs(e)&&function(e,t){const n=e.terms.size;let r=1;for(let e=1;e<=Math.min(t,n-1)&&r<=Vs;e++)r=r*(t+e)/e;const s=new Map;for(const t of e.terms.values())for(const[e]of t.vars)s.set(e,[0,0]);for(const t of e.terms.values())for(const[e,n]of s){const r=t.vars.find(([t])=>t===e)?.[1]??0;n[0]=Math.min(n[0],r),n[1]=Math.max(n[1],r)}let i=1;for(const[e,n]of s.values())if((i*=t*(n-e)+1)>Vs)break;return Math.min(r,i)}(e,Number(t))>Vs)throw new Rr("too many terms to work out");if(Gs(e)&&t>1n){const{re:n,im:r}=ti(e),s=e=>fs(e)?Qr(e.c.n)+Qr(e.c.d)+(e.root?Qr(e.root.r):0):64;if(Number(t)*Math.max(s(n),s(r),1)>2e4)return ui(ti(e),us(t))}let n=us(1),r=e;for(let e=t;e>0n;e>>=1n)1n&e&&(n=pi(n,r)),e>1n&&(r=pi(r,r));return n}function di(e,t){if(Gs(e)||Gs(t))throw new Rr("complex numbers have no order");if(ps(e)&&ps(t))return ss(e.c,t.c);if(fs(e)&&fs(t)&&ys(e,t))return 0;const n=xs(e),r=xs(t);if(n===r)return 0;const s=fs(e)&&fs(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 gi(e,t,n=!1){return Array.isArray(e)||Array.isArray(t)?Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,r)=>gi(e,t[r],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:"boolean"==typeof e||"boolean"==typeof t?!!n&&gi("boolean"==typeof e?us(e?1:0):e,"boolean"==typeof t?us(t?1:0):t):Hs(e)||Hs(t)?function(e,t){const n=Ls(e,t);return Hs(n)?!Gs(n)&&ei(n):ms(n)}(e,t):0===di(e,t)}const vi={0:()=>us(0),2:()=>us(1,2),3:()=>Ss(Jr(1n,2n),2,2n),4:()=>Ss(Jr(1n,2n),2,3n),6:()=>us(1)};function bi(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=vi[t];return r?n<0?Fs(r()):r():null}const yi=e=>bi(e+6),wi=(e,t)=>Math.abs(e)<1e-15&&Math.abs(t)>1e-6?0:e;function xi(e,t){const n=function(e){if(ms(e))return 0;if(!fs(e)||1!==e.pi||e.e||e.root)return null;const t=ts(e.c,Jr(12n));return 1n!==t.d?null:Number((t.n%24n+24n)%24n)}(t);if(null!==n){const t=bi(n),r=yi(n);if(t&&r)switch(e){case"sin":return t;case"cos":return r;case"tan":return Bs(t,r);case"cot":return Bs(r,t);case"sec":return Bs(us(1),r);case"csc":return Bs(us(1),t)}}const r=xs(t),s=wi(Math.sin(r),r),i=wi(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 Lr("undefined");return $s(o)}function $i(e,t){const n={arcsin:[-6,6],arccos:[0,12],arctan:[-5,5]}[e],r=t=>"arcsin"===e?bi(t):"arccos"===e?yi(t):yi(t)&&!ms(yi(t))?Bs(bi(t),yi(t)):null;if(fs(t))for(let e=n[0];e<=n[1];e++){const n=r(e);if(n&&fs(n)&&ys(n,t))return ls(Jr(BigInt(e),12n),1)}const s=xs(t);if("arctan"!==e&&Math.abs(s)>1)throw new Lr("not a real number");return{arcsin:Math.asin,arccos:Math.acos,arctan:Math.atan}[e](s)}function ki(e){if(Hs(e))return Gs(e)?ni(li(ti(e))):ei(e);if(Us&&di(e,us(0))<0)return ni({re:ki(Ts(e)),im:cs});if(fs(e)){if(0n===e.c.n)throw new Lr("ln 0 is undefined");if(e.c.n<0n)throw new Lr("not a real number");if(1n===e.c.n&&1n===e.c.d&&!e.pi&&!e.root)return us(e.e)}const t=xs(e);if(t<=0)throw new Lr(0===t?"ln 0 is undefined":"not a real number");return Math.log(t)}function qi(e){if(e<.5)return Math.PI/(Math.sin(Math.PI*e)*qi(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 Mi(e,t){Hs(e)&&ei(e);const n=ds(e)??("number"==typeof e&&Number.isInteger(e)?BigInt(e):null);if(null===n)throw new Lr(`${t} needs whole numbers`);return n}const Ai=(e,t)=>Number(t)*Qr(e)>Pr.bits;const Si=zs(e=>ps(e)?ls(Jr(is(e.c))):qs(Math.floor(xs(e)))),Ni=zs(e=>ps(e)?ls(Jr(-is(rs(e.c)))):qs(Math.ceil(xs(e))));function Oi(e,t){const n=Number(Mi(t,"round"));if(Math.abs(n)>Pr.places)throw new Rr("too many decimal places");if(ps(e)){const t=Jr(10n**BigInt(Math.abs(n))),r=n>=0?ts(e.c,t):ns(e.c,t),s=is(es(ts(Jr(2n),Jr(Hr(r.n),r.d)),Kr))/2n,i=Jr(r.n<0n?-s:s);return ls(n>=0?ns(i,t):ts(i,t))}if(n>15)return xs(e);const r=10**n;return 0===r?0:Math.sign(xs(e))*Math.round(Math.abs(xs(e))*r)/r}const Ei=(e,t)=>e.toFixed(Math.min(t,100))+(t>100?"0".repeat(t-100):"");function Ii(e,t){if(ms(t))throw new Lr("division by zero");if(ps(e)&&ps(t))return ls(es(e.c,rs(ts(t.c,Jr(is(ns(e.c,t.c)))))));const n=xs(e),r=xs(t);return $s((n%r+r)%r)}const zi=(e,t)=>e/_i(e,t)*t,_i=(e,t)=>t?_i(t,e%t):e,ji={pi:()=>cs,"π":()=>cs,tau:()=>ls(Jr(2n),1),"τ":()=>ls(Jr(2n),1),e:()=>hs,"∞":()=>1/0,"-∞":()=>-1/0,true:()=>!0,false:()=>!1,"°":()=>ls(Jr(1n,180n),1)},Ti={abs:e=>Gs(e)?ii(ti(e)):fs(e)?ls(Jr(Hr(e.c.n),e.c.d),e.pi,e.e,e.root):Math.abs(xs(e)),floor:Si,ceil:Ni,sqrt:e=>Ws(e,us(1,2)),ln:zs(ki),loglog:zs(e=>ki(ki(e))),logloglog:zs(e=>ki(ki(ki(e)))),expm1:zs(e=>ms(e)?us(0):Math.expm1(xs(e))),sinh:zs(e=>ms(e)?us(0):Math.sinh(xs(e))),cosh:zs(e=>ms(e)?us(1):Math.cosh(xs(e))),tanh:zs(e=>ms(e)?us(0):Math.tanh(xs(e))),arcsinh:zs(e=>ms(e)?us(0):Math.asinh(xs(e))),arccosh:zs(e=>{const t=xs(e);if(t<1)throw new Lr("not a real number");return 1===t?us(0):Math.acosh(t)}),arctanh:zs(e=>{const t=xs(e);if(Math.abs(t)>=1)throw new Lr("undefined");return ms(e)?us(0):Math.atanh(t)}),"!":zs(function(e){const t=ds(e)??("number"==typeof e&&Number.isInteger(e)?BigInt(e):null);if(null!==t){if(t<0n)throw new Lr("factorial of a negative number");if(t>BigInt(Pr.factorial))throw new Rr("too large to calculate");Ur(t,Number(t)*Math.log2(Number(t)+1));let e=1n;for(let n=2n;n<=t;n++)e*=n;return ls(Jr(e))}const n=xs(e);if(n<0&&Number.isInteger(n))throw new Lr("factorial of a negative number");return $s(qi(n+1),n)}),neg:Fs,pm:e=>gs([e,Fs(e)],"pm"),"\\not":e=>!ks(e),det:e=>Di.det(e)};for(const e of["sin","cos","tan","csc","sec","cot"])Ti[e]=zs(t=>xi(e,t));for(const e of["arcsin","arccos","arctan"])Ti[e]=zs(t=>$i(e,t));const Ci=e=>{if(ms(e))throw new Lr("not a real number");return Bs(us(1),e)};Ti.arcsec=zs(e=>$i("arccos",Ci(e))),Ti.arccsc=zs(e=>$i("arcsin",Ci(e))),Ti.arccot=zs(e=>Ls(ls(Jr(1n,2n),1),$i("arctan",e)));const Zi=new Set(["pmatrix","bmatrix"]),Fi=e=>fe(e)&&(Zi.has(e.group)||"[]"===e.group&&e.every(e=>"[]"===e.group)&&(e.length>1||e[0].length>1)),Li=e=>pe(e)&&!Fi(e)&&"pm"!==e.group,Ri=me({add:Zs,sub:Ls,mul:Rs,div:Bs,charge:Dr,isZero:e=>fs(e)?0n===e.c.n:Math.abs(xs(e))<1e-12,zero:()=>us(0),one:()=>us(1),size:e=>Math.abs(xs(e)),fail:e=>{throw new Lr(e)},make:(e,t)=>gs(e.map(e=>gs(e,"[]")),t&&t.group?t.group:"bmatrix")}),Bi=(e,t)=>gs(e,t&&t.group?t.group:"[]"),Pi=(e,t)=>(...n)=>{const r=n.length>1&&n.every(Li)?gs(n.map(e=>gs(e,"[]")),"[]"):n[0];if(n.length>1&&r===n[0])throw new Rr(`${e} of more than one thing`);if(!Fi(r))throw new Rr(`${e} of something that isn't a matrix`);return t(r)};function Wi(e,t){return Fi(e)&&Fi(t)?Ri.times(e,t):Fi(e)&&Li(t)?Bi(Ri.timesVector(e,t),t):Li(e)&&Fi(t)?Bi(Ri.vectorTimes(e,t),e):Rs(e,t)}const Di={det:Pi("det",e=>Ui(e)),inv:Pi("inv",Ri.inverse),inverse:Pi("inverse",Ri.inverse),transpose:Pi("transpose",Ri.transpose),trace:Pi("trace",Ri.trace),tr:Pi("tr",Ri.trace),rank:Pi("rank",e=>us(Ri.rank(e))),rref:Pi("rref",Ri.rref),identity:e=>{const t=ds(e);if(null===t||t<1n||t>100n)throw new Rr("identity(n) needs a whole number n");return Ri.identity(Number(t))},dot:(e,t)=>{if(!Li(e)||!Li(t))throw new Rr("dot of something that isn't a vector");return Ri.dot(e,t)},cross:(e,t)=>{if(!Li(e)||!Li(t))throw new Rr("cross of something that isn't a vector");return Bi(Ri.cross(e,t),e)},linsolve:(e,t)=>{if(!Fi(e)||!Fi(t)&&!Li(t))throw new Rr("linsolve(A, b) needs a matrix and a vector");return Fi(t)?Ri.solve(e,t):Bi(Ri.solve(e,t),t)}};function Ui(e){if(!e.some(e=>e.some(Hs)))return Ri.det(e);if(e.length!==e[0].length)throw new Lr(`a ${e.length} by ${e[0].length} matrix has no determinant`);if(e.length>6)throw new Rr("too large to calculate");const t=e=>1===e.length?e[0][0]:e[0].reduce((n,r,s)=>{const i=e.slice(1).map(e=>e.filter((e,t)=>t!==s)),o=Rs(r,t(i));return s%2?Ls(n,o):Zs(n,o)},us(0));return t(e)}function Vi(e,t){const n=e.args.map(e=>gs("op"===e.type&&"[]"===e.op?e.args.map(t):[t(e)],"[]"));if(n.some(e=>e.length!==n[0].length))throw new Lr("rows of different lengths");return gs(n,"vmatrix"===e.op?"bmatrix":e.op)}const Hi={"+":Zs,"-":Ls,"*":Wi,"/":(e,t)=>Fi(t)?Wi(e,Ri.inverse(t)):Bs(e,t),"^":function(e,t){if(!Fi(e))return Ws(e,t);const n=ds(t);if(null===n)throw new Rr("a matrix to a power that is not a whole number");return Ri.power(e,n)},"±":(e,t)=>gs([Zs(e,t),Ls(e,t)],"pm"),mod:_s(Ii),log:_s(function(e,t){if(fs(e)&&ys(e,hs))return ki(t);const n=xs(e),r=xs(t);if(n<=0||1===n)throw new Lr("not a valid base");if(r<=0)throw new Lr(0===r?"log 0 is undefined":"not a real number");const s=Math.log(r)/Math.log(n);if(ps(e)&&ps(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&&ys(i,o))return ls(Jr(BigInt(r),n))}return s}),root:_s((e,t)=>Ws(t,Bs(us(1),e))),atan2:(e,t)=>Math.atan2(xs(e),xs(t)),round:Oi,fixed:function(e,t){const n=Number(Mi(t,"fixed"));if(n<0)throw new Lr("fixed needs 0 or more decimal places");const r=Oi(e,t);if(ps(r)){const e=r.c.n*10n**BigInt(n)/r.c.d,t=(e<0n?-e:e).toString().padStart(n+1,"0");return vs(`${e<0n?"-":""}${t.slice(0,t.length-n)}${n?"."+t.slice(-n):""}`)}return vs(Ei(xs(r),n))},perm:function(e,t){const n=Mi(e,"permutations"),r=Mi(t,"permutations");if(r<0n||r>n)throw new Lr("undefined");if(r>BigInt(Pr.terms)||Ai(n,r))throw new Rr("too large to calculate");Ur(r,Number(r)*Qr(n));let s=1n;for(let e=n-r+1n;e<=n;e++)s*=e;return ls(Jr(s))},comb:function(e,t){const n=Mi(e,"combinations");let r=Mi(t,"combinations");if(r<0n||r>n)throw new Lr("undefined");if(n-r<r&&(r=n-r),r>BigInt(Pr.terms)||Ai(n,r))throw new Rr("too large to calculate");Ur(2n*r,Number(r)*Qr(n));let s=1n;for(let e=1n;e<=r;e++)s=s*(n-r+e)/e;return ls(Jr(s))},"=":(e,t)=>gi(e,t,!0),"===":(e,t)=>gi(e,t),"≠":(e,t)=>!gi(e,t,!0),"≠=":(e,t)=>!gi(e,t),"≈":(e,t)=>Math.abs(xs(e)-xs(t))<=1e-9*Math.max(1,Math.abs(xs(e)),Math.abs(xs(t))),"<":(e,t)=>di(e,t)<0,">":(e,t)=>di(e,t)>0,"≤":(e,t)=>di(e,t)<=0,"≥":(e,t)=>di(e,t)>=0,"&":(e,t)=>ks(e)&&ks(t),"|":(e,t)=>ks(e)||ks(t),"\\xor":(e,t)=>ks(e)!==ks(t),"\\nor":(e,t)=>!(ks(e)||ks(t)),"\\nand":(e,t)=>!(ks(e)&&ks(t)),"\\implies":(e,t)=>!ks(e)||ks(t),"\\iff":(e,t)=>ks(e)===ks(t)},Gi={sum:e=>e.reduce((e,t)=>Zs(e,t),us(0)),prod:e=>e.reduce((e,t)=>Rs(e,t),us(1)),max:e=>e.reduce((e,t)=>di(t,e)>0?t:e),min:e=>e.reduce((e,t)=>di(t,e)<0?t:e),mean:e=>Bs(Gi.sum(e),us(e.length)),gcd:e=>ls(Jr(e.map(e=>Mi(e,"gcd")).reduce(Xr)))},Qi=["∈","∉","∪","∩","pmod","random","(]","[)"];function Xi(e,t){if(++Wr>Pr.steps)throw new Rr("too much to work out");switch(e.type){case"number":return ls(as(e.value));case"string":return vs(e.value.slice(1,-1));case"symbol":return Ji(e.value,t)}const n=ue(e);if(n)return Xi(n,t);const{op:r,args:s}=e,i=e=>Xi(e,t);if("?:"===r)return ks(i(s[0]))?i(s[1]):i(s[2]);if("_"===r){if(s.every(e=>"op"!==e.type))return Ji(`${s[0].value}_${s[1].value}`,t);throw new Rr("subscript")}if("der"===r)return function(e,t){const[n,r]=e.args;if("op"===r.type&&"="===r.op){const e=no(r.args[0]);if(!e)throw new Rr("a derivative at a point names its variable: der(f, x = a)");return ro(n,e,xs(Xi(r.args[1],t)),t)}const s=no(r);if(!s||!t[Ki]?.has(s))throw new Rr(`a derivative needs a point: der(f, ${s||"x"} = a)`);return ro(n,s,xs(t[s]),t)}(e,t);if("evaluated"===r){const[e,n,r,o]=s;return Ls(Xi(e,eo(t,n.value,i(o))),Xi(e,eo(t,n.value,i(r))))}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]=[no(r),s,i];else{if(3!==e.length||o(r))throw new Rr("an integral needs limits to be calculated");[a,l,u]=[j(n)||"x",r,s]}let c=xs(Xi(l,t)),h=xs(Xi(u,t));if(c===h)return us(0);let f=1;c>h&&([c,h]=[h,c],f=-1);const p=to(n,a,t),{value:m,error:d}=so(p,c,h);return uo(f*m,d)}(s,t);if("lim"===r)return function(e,t){const[n,r,s,i]=e;let o,a,l=0;if(2===e.length&&"op"===r.type&&"→"===r.op)[o,a]=[no(r.args[0]),r.args[1]];else if(2===e.length)[o,a]=[j(n),r];else{if(!(e.length>=3))throw new Rr("a limit needs a point");[o,a]=[no(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 Rr("a limit needs a variable");const u=Xi(a,t),c=xs(u),h=to(n,o,t);let f,p;if(Number.isFinite(c))if(l){({value:f,error:p}=oo(e=>h(c+l*e*Math.max(1,Math.abs(c)))));try{const e=Xi(n,eo(t,o,u));if(Math.abs(xs(e)-f)<=Math.max(p,1e-6*Math.max(1,Math.abs(f))))return e}catch(e){if(!(e instanceof Lr))throw e}}else{const e=oo(e=>h(c+e*Math.max(1,Math.abs(c)))),r=oo(e=>h(c-e*Math.max(1,Math.abs(c))));if(e.value===r.value)({value:f,error:p}=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 Lr("the limit does not exist");f=(e.value+r.value)/2,p=Math.max(e.error,r.error,Math.abs(e.value-r.value))}try{const e=Xi(n,eo(t,o,u));if(Math.abs(xs(e)-f)<=1e-6*Math.max(1,Math.abs(f)))return e}catch(e){if(!(e instanceof Lr))throw e}}else({value:f,error:p}=oo(e=>h(Math.sign(c)/e)));return Number.isFinite(f)?uo(f,p):f}(s,t);if("\\sumidx"===r||"\\prodidx"===r)return function(e,t,n){const[r,s,i]=t;if(t.length<3)throw new Rr("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=j(r)||"n";const l=Mi(Xi(a,n),"a sum"),u=Xi(i,n),c=e?Zs:Rs;if(u===1/0){if(!e)throw new Rr("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 Lr("undefined");s+=t}if(n.push(a),r.push(s),o>=6&&r[r.length-1]===r[r.length-2]&&!lo(e,t,i))return uo(s,0)}if(lo(e,t,i))throw new Lr("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 Lr("the series diverges");if(Math.abs(o)>1e-6*Math.max(1,Math.abs(s))&&u>=.9)throw new Rr("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),f=r.slice(-8,-1),p=(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]},m=p(c,h),d=p(n.slice(-8,-1).map(e=>1/e),f);return uo(m,Math.abs(m-d))}(to(r,o,n),Number(l))}const h=Mi(u,"a sum");if(h-l+1n>BigInt(Pr.terms))throw new Rr("too many terms to add one by one");let f=us(e?0:1);for(let e=l;e<=h;e++)f=c(f,Xi(r,eo(n,o,ls(Jr(e)))));return f}("\\sumidx"===r,s,t);if(["()","[]","{}"].includes(r))return gs(s.map(i),r);if("pmatrix"===r||"bmatrix"===r)return Vi(e,i);if("vmatrix"===r)return Ui(Vi(e,i));if("^"===r&&"symbol"===s[1].type&&"T"===s[1].value&&!Object.prototype.hasOwnProperty.call(t,"T")){const e=i(s[0]);if(Fi(e))return Ri.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?ms(Ii(Ls(n(e.args[0]),n(e.args[1])),r)):Ii(n(e),r)}(s,i);if("setbuilder"===r)throw new Rr("a set described by a condition has no list of values");if(L(e))return i(L(e));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)&&fs(s))i="ℝ"===r.value||("ℚ"===r.value?ps(s):ps(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=di(s,e),a=di(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=>gi(s,t(e)))}return"∈"===e.op?i:!i}(e,i);if(void 0!==t)return t}if(Qi.includes(r))return Yi(e,t);if(r.startsWith("\\:")){const n=r.slice(2),o=Object.prototype.hasOwnProperty.call(t,n)?t[n]:void 0;if("function"!=typeof o&&Object.prototype.hasOwnProperty.call(Di,n))return Di[n](...s.map(i));if("function"!=typeof o&&ne(r))return Yi(e,t);if("function"!=typeof o)throw new Rr(`no function ${r.slice(2)}`);return qs(o(...s.map(e=>Ms(i(e)))))}if(Ti[r]&&1===s.length)return Ti[r](i(s[0]));if(Hi[r]&&2===s.length)return Hi[r](i(s[0]),i(s[1]));if(Gi[r])return Gi[r](s.map(i));throw new Rr(`can't calculate '${r}'`)}function Ji(e,t){if(Object.prototype.hasOwnProperty.call(t,e))return t[e];if(Object.prototype.hasOwnProperty.call(ji,e))return ji[e]();if(R(e))return ls(as(R(e)));if("i"===e)return Qs();if(/^[A-Za-z\u0370-\u03FF][A-Za-z0-9_\u0370-\u03FF′]*$/.test(e))return Js([{vars:[[e,1]],re:us(1),im:us(0)}]);throw new Rr(`no value for '${e}'`)}function Yi(e,t){const n={};for(const[e,r]of Object.entries(t))"function"!=typeof r&&(n[e]=Ms(r));try{return qs(function(e,t={}){0===Cr&&(Tr=0),Cr++;try{return Zr(gr(e),t)}finally{Cr--}}(e,n))}catch(e){throw new Rr(e.message)}}const Ki=Symbol("bound"),eo=(e,t,n)=>({...e,[t]:n,[Ki]:new Set([...e[Ki]??[],t])});function to(e,t,n){return r=>{try{return xs(Xi(e,eo(n,t,r)))}catch(e){if(e instanceof Lr)return NaN;if(e instanceof Br)return 0;throw e}}}const no=e=>"symbol"===e.type?e.value:null;function ro(e,t,n,r){const s=to(e,t,r);if(!Number.isFinite(s(n)))throw new Lr("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 Lr("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],f=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<=f&&(f=r,h=c[e][n])}if(Math.abs(c[e][e]-c[e-1][e-1])>=2*f)break}if(!Number.isFinite(h))throw new Lr("not differentiable here");return uo(h,f)}function so(e,t,n){if(t===-1/0&&n===1/0){const t=so(e,-1/0,0),n=so(e,0,1/0);return{value:t.value+n.value,error:t.error+n.error}}return n===1/0?io(n=>e(t+n/(1-n))/((1-n)*(1-n)),0,1):t===-1/0?io(t=>e(n-t/(1-t))/((1-t)*(1-t)),0,1):io(e,t,n)}function io(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 f=e(0===i?(t+n)/2:h);if(!Number.isFinite(f)){if(l<1e-6*r)return 0;throw new Lr("the integral diverges")}return Math.abs(i)>s-.5&&(u=Math.max(u,Math.abs(c*f))),c*f};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 Lr("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 Lr("the integral does not converge");return{value:a,error:h}}(e,t,n)}catch(e){if(!(e instanceof Lr)||"the integral does not converge"!==e.message||r>=10)throw e}const s=(t+n)/2,i=io(e,t,s,r+1),o=io(e,s,n,r+1);return{value:i.value+o.value,error:i.error+o.error}}function oo(e){const t=ao(e),n=ao(t=>e(.7548776662466927*t));if(t.value===n.value)return t;if(!Number.isFinite(t.value)||!Number.isFinite(n.value))throw new Lr("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 Lr("the limit could not be found");if(Math.abs(t.value-n.value)<=s)return t;throw new Lr("the limit does not exist")}function ao(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 Lr("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 Lr("the limit could not be found")}return i}function lo(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 uo(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 us(0);if(Math.abs(e)<1e-10)return e;const r=[[us(1),1e3],[cs,100],[ls(Kr,2),100],[hs,100],...[2n,3n,5n,6n,7n].map(e=>[ls(Kr,0,0,{n:2,r:e}),100])];for(const[t,s]of r){const r=e/xs(t),i=co(r,s);if(i&&Math.abs(Number(i.n)/Number(i.d)-r)*xs(t)<=n)return Ns(ls(i),t)}return e}function co(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?Jr(BigInt(r),BigInt(i)):null}function ho(e,t){if("boolean"==typeof e)return String(e);if(Hs(e))return fo(e,t);if(e&&"s"===e.kind)return JSON.stringify(e.text);if(Array.isArray(e)){if("pm"===e.group&&2===e.length&&gi(e[1],Fs(e[0])))return`±${mo(e[0],t)}`;if(Zi.has(e.group)&&fe(e))return`${e.group}(${e.map(e=>`[${e.map(e=>ho(e,t)).join(", ")}]`).join(", ")})`;const[n,r]={"()":"()","[]":"[]","{}":"{}"}[e.group]||"{}";return n+e.map(e=>ho(e,t)).join(", ")+r}return"number"==typeof e?go(e,t):t.decimal||null!==t.places?function(e,t){if(ps(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=Hr(n).toString().padStart(i+1,"0"),o=i?`${s.slice(0,-i)}.${s.slice(-i)}`:s;if(s.length<=t.maxDigits)return(r?"-":"")+vo(o)}}return ps(e)&&null!==t.places?ho(Oi(e,us(t.places)),{...t,places:null,decimal:!0}):go(xs(e),t)}(e,t):function(e,t){const{c:n}=e,r=Hr(n.n);if(r.toString().length>t.maxDigits||n.d.toString().length>t.maxDigits)return function(e,t){if(!ps(e))return go(xs(e),t);if(1n!==e.c.d){const n=xs(e);if(0!==n&&Number.isFinite(n))return go(n,t);const r=Hr(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=vo(`${a[0]}.${a.slice(1,t.digits)}`);return`${e.c.n<0n?"-":""}${u}*10^(${l})`}const n=Hr(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=vo(`${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)}function fo(e,t){const n=e=>e.vars.reduce((e,[,t])=>e+t,0),r=[...new Set([...e.terms.values()].flatMap(e=>e.vars.map(([e])=>e)))].sort(),s=(e,t)=>e.vars.find(([e])=>e===t)?.[1]??0,i=[...e.terms.values()].sort((e,t)=>n(t)-n(e)||r.reduce((n,r)=>n||s(t,r)-s(e,r),0)).map(e=>function(e,t){const n=Xs(e.vars);if(!n)return po(e.re,e.im,t);if(!ms(e.im))return`(${po(e.re,e.im,t)})*${n}`;const r=e.re,s=ho(r,t);if("1"===s)return n;if("-1"===s)return`-${n}`;if(ps(r)&&1n!==r.c.d&&!t.decimal&&null===t.places){const e=Hr(r.c.n);return`${r.c.n<0n?"-":""}${1n===e?n:`${e}*${n}`}/${r.c.d}`}return/^-?[\w.^]+(?:\([\w ,.]*\))?$/.test(s)?`${s}*${n}`:`(${s})*${n}`}(e,t));return i.reduce((e,t,n)=>0===n?t:t.startsWith("-")?`${e} - ${t.slice(1)}`:`${e} + ${t}`,"")}function po(e,t,n){if(ms(t))return ho(e,n);const r=!ms(t)&&di(t,us(0))<0,s=ho(r?Ts(t):t,n),i="1"===s?"i":/^[\d.]+$/.test(s)?`${s}*i`:`(${s})*i`;return ms(e)?r?`-${i}`:i:`${ho(e,n)} ${r?"-":"+"} ${i}`}const mo=(e,t)=>{const n=ho(e,t);return/^[\d.]+$|^[a-zπ]+$/i.test(n)?n:`(${n})`};function go(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 Ei(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`${vo(n)}*10^(${Number(r)})`}return String(Number(e.toPrecision(t.digits)))}const vo=e=>e.includes(".")?e.replace(/\.?0+$/,""):e;function bo(e,t={},n={}){0===Vr&&(Wr=0);const r="string"==typeof e?dr(e):z(e),s={};for(const[e,n]of Object.entries(t))s[e]=qs(n);Vr++;const i=Us;let o,a=!1;_(r,e=>{"symbol"!==e.type||"i"!==e.value||Object.prototype.hasOwnProperty.call(t,"i")||(a=!0)}),Us=n.complex??(a||Vr>1&&i);try{o=Xi(r,s)}finally{Vr--,Us=i}const l={decimal:!1,places:null,digits:12,maxDigits:50,...n};if(void 0===l.places&&(l.places=null),null!==l.places&&!(Number.isInteger(l.places)&&l.places>=0&&l.places<=Pr.places))throw new Rr(`places is a whole number from 0 to ${Pr.places}`);const u=e=>Array.isArray(e)?e.every(u):Hs(e)?[...e.terms.values()].every(e=>"number"!=typeof e.re&&"number"!=typeof e.im):"number"!=typeof e;return{value:Ms(o),text:ho(o,l),exact:u(o)}}function yo(e,t={}){let n=e.trim();const r={},s=/^(~|≈)(\d+)?\s*/.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}=bo(n,t,r);return e.startsWith('"')||/^\d+(\.\d+)?$/.test(e)?e:`(${e})`}catch(e){if(e instanceof Lr)return'"undefined"';if(e instanceof Rr)return`(${n})`;throw e}}hr=yo;for(const e of[Pr,vi,ji,Ti,Hi,Gi])Object.setPrototypeOf(e,null);Object.setPrototypeOf(Di,null);const wo=e=>"op"===e.type&&o(e.op)&&["vec","hat"].includes(ee(e.op)),xo={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",implies:"implies",iff:"if and only if",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",evaluatedFrom:"evaluated from",setOf:"the set of",suchThat:"such that",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",andSoOn:"dot dot dot",emptySet:"the empty set",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"]},$o={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",arcsec:"inverse secant",arccsc:"inverse cosecant",arccot:"inverse cotangent",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"},ko=Object.fromEntries(Object.entries(T).map(([e,t])=>[t,e]));function qo(e,t={}){return Ao(function(e,t={}){return Mo(e,t,!0)}(e,t))}function Mo(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 Oo({...xo,...t.words},{...$o,...t.names},t.say||{},n).speak(e))}function Ao(e){return e.map(e=>e.text).join(" ").replace(/\s+/g," ").replace(/ ,/g,",").replace(/,(\s*,)+/g,",").replace(/^,\s*/,"").replace(/,\s*$/,"").trim()}const So={"=":"equals","===":"equals","≠":"notEqual","≠=":"notEqual","<":"lessThan",">":"greaterThan","≤":"lessOrEqual","≥":"greaterOrEqual","≈":"approx","≡":"congruent","→":"tendsTo","∈":"isIn","∉":"isNotIn","∪":"union","∩":"intersect","±":"plusOrMinus","&":"and","|":"or","\\xor":"xor","\\nand":"nand","\\nor":"nor","\\implies":"implies","\\iff":"iff"},No={"ℝ":"reals","ℤ":"integers","ℕ":"naturals","ℚ":"rationals","ℂ":"complexes"};class Oo{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=>Ao(this.speak(e))):[e.value],e,e=>Ao(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("⋯"===e)return t.andSoOn;if(No[e])return t[No[e]];if(ko[e])return ko[e].toLowerCase();if(/^Δ.+$/.test(e))return`${t.delta} ${this.symbol(e.slice(1))}`;if(/^d[A-Za-z\u03B1-\u03C9]$/.test(e))return`d ${this.symbol(e[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(So[t])return[...this.speak(r),a(i[So[t]]),...this.speak(s)];if(o(t)){if(1===n.length&&"symbol"===r.type&&"vec"===ee(t))return[a(i.vector),...this.speak(r)];if(1===n.length&&"symbol"===r.type&&"hat"===ee(t))return[...this.speak(r),a(i.hat)];const e=this.symbol(ee(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 B(s)?[...this.leftSide(r),a(i.minus),...this.quantityIfSum(s.args[1])]:[...this.leftSide(r),a(i.plus),...this.speak(s)];case"-":return B(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):Ao(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:`${Ao(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 he(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 n.length?[a(i.theSet),...l()]:[a(i.emptySet)];case"setbuilder":return[a(i.setOf),..."op"===n[0].type&&"∈"===n[0].op?[...this.speak(n[0].args[0]),a("in"),...this.speak(n[0].args[1])]:this.speak(n[0]),a(i.suchThat),...this.speak(n[1])];case"evaluated":return[...this.speak(n[0]),a(`${i.comma} ${i.evaluatedFrom}`),...this.speak(n[2]),a(i.to),...this.speak(n[3])];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=he(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(B(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(wo))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)&&!B(e),o=this.grouped(t,null,i(t,"/")),a=this.isCall(t)?[s(r.comma)]:[],l=this.speak(n),u=i(n,"/")||this.audio&&i(n,"*")&&l.some(e=>e.id===n.id&&e.text===r.times),c=this.isCompound(n)||this.audio&&u;return[...o,...a,s(r.over),...c?[this.seg(n,r.quantity),...l,...this.closer(n,"endFraction")]:l]}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||B(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.split(" ")[0]:"",o=e[0]&&(e[0].text.startsWith(r.quantity)||t===r.toThe.split(" ").pop());return[...i,s(o?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}=se(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(j(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=j(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[xo,$o,So,No,ko])Object.setPrototypeOf(e,null);function Eo(e,t={}){return vr(e)?[]:function(e,t={}){return Mo(e,t,!1)}(gr(e),t)}function Io(e,t={}){return vr(e)?"":qo(gr(e),t)}const zo={"(":{fill:"M0.92,0 C0.1,0.2 0.1,0.8 0.92,1 L1,0.975 C0.48,0.75 0.48,0.25 1,0.025 Z"},")":{fill:"M0.08,0 C0.9,0.2 0.9,0.8 0.08,1 L0,0.975 C0.52,0.75 0.52,0.25 0,0.025 Z"},"{":{fill:"M1,0 C0.45,0 0.5,0.05 0.5,0.2 L0.5,0.38 C0.5,0.46 0.35,0.49 0.05,0.5 C0.35,0.51 0.5,0.54 0.5,0.62 L0.5,0.8 C0.5,0.95 0.45,1 1,1 L1,0.985 C0.68,0.985 0.64,0.95 0.64,0.8 L0.64,0.62 C0.64,0.53 0.55,0.505 0.3,0.5 C0.55,0.495 0.64,0.47 0.64,0.38 L0.64,0.2 C0.64,0.05 0.68,0.015 1,0.015 Z"},"}":{fill:"M0,0 C0.55,0 0.5,0.05 0.5,0.2 L0.5,0.38 C0.5,0.46 0.65,0.49 0.95,0.5 C0.65,0.51 0.5,0.54 0.5,0.62 L0.5,0.8 C0.5,0.95 0.55,1 0,1 L0,0.985 C0.32,0.985 0.36,0.95 0.36,0.8 L0.36,0.62 C0.36,0.53 0.45,0.505 0.7,0.5 C0.45,0.495 0.36,0.47 0.36,0.38 L0.36,0.2 C0.36,0.05 0.32,0.015 0,0.015 Z"},sqrt:{stroke:"M0,0.62 L0.18,0.55 L0.45,0.97 L0.98,0"},cancel:{stroke:"M0,1 L1,0"},int:{stroke:"M0.95,0.09 C0.9,0.01 0.72,0 0.66,0.12 C0.6,0.25 0.42,0.75 0.34,0.88 C0.28,0.99 0.1,0.99 0.05,0.91"},sum:{fill:"M0.04,0 L0.94,0 L0.98,0.24 L0.94,0.24 C0.9,0.1 0.8,0.07 0.62,0.07 L0.24,0.07 L0.58,0.5 L0.2,0.93 L0.64,0.93 C0.82,0.93 0.92,0.9 0.95,0.76 L0.99,0.76 L0.94,1 L0.02,1 L0.47,0.47 Z"},prod:{fill:"M0,0 L1,0 L1,0.04 L0.88,0.05 L0.88,0.95 L1,0.96 L1,1 L0.62,1 L0.62,0.96 L0.74,0.95 L0.74,0.06 L0.26,0.06 L0.26,0.95 L0.38,0.96 L0.38,1 L0,1 L0,0.96 L0.12,0.95 L0.12,0.05 L0,0.04 Z"}};function _o(e,t,n=""){const r=zo[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 jo=.8,To=.2,Co=.25,Zo=.7,Fo="−",Lo={"+":"add","-":"sub","*":"mul","/":"frac","^":"pow",_:"subscript",neg:"neg",pm:"pm","!":"factorial","=":"eq","===":"eq","≠":"neq","≠=":"neq","<":"lt",">":"gt","≤":"le","≥":"ge","≈":"approx","≡":"equiv","∈":"in","∉":"notin","∪":"union","∩":"intersect","→":"to","±":"pm","&":"and","|":"or","\\not":"not","\\xor":"xor","\\nand":"nand","\\nor":"nor","\\implies":"implies","\\iff":"iff","?:":"cases","()":"tuple","[]":"list","{}":"set","(]":"interval","[)":"interval","\\sumidx":"sum","\\prodidx":"prod",mod:"mod",pmod:"pmod",pmatrix:"matrix",bmatrix:"matrix",vmatrix:"matrix"},Ro={"=":"=","===":"=","≠":"≠","≠=":"≠","<":"<",">":">","≤":"≤","≥":"≥","∈":"∈","∉":"∉","→":"→","≈":"≈","≡":"≡","&":"∧","|":"∨","\\xor":"⊕","\\nand":"↑","\\nor":"↓","\\implies":"⇒","\\iff":"⇔"},Bo={"±":"±","∪":"∪","∩":"∩",mod:"mod"},Po=["sin","cos","tan","csc","sec","cot","sinh","cosh","tanh"],Wo={arcsin:"sin",arccos:"cos",arctan:"tan",arcsec:"sec",arccsc:"csc",arccot:"cot",arcsinh:"sinh",arccosh:"cosh",arctanh:"tanh"},Do=[...Po,...Object.keys(Wo),"ln","det"],Uo={atan2:"atan2",max:"max",min:"min",gcd:"gcd",mean:"mean",round:"round",fixed:"fixed",expm1:"expm1",random:"random"},Vo={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]},Ho=["int","lim","\\sumidx","\\prodidx"],Go={"\\partial":"∂","\\nabla":"∇","\\ell":"ℓ","\\infty":"∞","\\emptyset":"∅"},Qo={vec:"→",hat:"ˆ",widehat:"ˆ",tilde:"˜",dot:"˙",ddot:"¨"},Xo=/^[acegmnopqrsuvwxyzαγεημνοπρστυχω]$/,Jo=e=>"symbol"===e?.type&&Xo.test(T[e.value]??e.value),Yo=["boxed","overline","bar","underline","cancel",...Object.keys(Qo)],Ko={prefix:"mv",display:!0,fnParens:"auto",trigPowers:!0,inverseTrig:"arc",derivativeBrackets:"[",scriptFractions:"slash",cases:!0,label:!0,mathml:null,attributes:null,style:null},ea=e=>String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),ta=e=>+e.toFixed(3)+"em",na=(e,t=jo,n=To)=>({html:e,h:t,d:n});function ra(...e){const t=e.flat().filter(Boolean);return{html:t.map(e=>e.html).join(""),h:Math.max(jo,...t.map(e=>e.h)),d:Math.max(To,...t.map(e=>e.d))}}function sa(e,t={}){const n=new ia({...Ko,...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):Io(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="${ea(o)}"`}>${a}${i}</span>`,h:r.h,d:r.d}}class ia{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=na(this.el(e,ea(t)));return n.leaf={kind:e,content:ea(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="${ea(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}="${ea(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?[ea(s.class)]:[]).join(" "),a=n.leaf?n.leaf.content:n.html;return{html:`<span class="${o}"${i?` style="${ea(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){const t=/^(-?\d*\.)(\d*)\.\.$/.exec(e.value);if(t){const[,n,r]=t;let s=1;for(let e=1;2*e<=r.length;e++)if(r.slice(-e)===r.slice(-2*e,-e)){s=e;break}let i=r;for(;i.endsWith(r.slice(-s))&&i.length>=s;)i=i.slice(0,-s);const o=this.text("num",(n+i).replace(/^-/,Fo)),a=this.text("num",r.slice(-s));return this.wrap(e,["number"],ra(o,na(this.el("over",a.html),a.h+.14,a.d)))}return this.wrap(e,["number"],this.text("num",e.value.replace(/^-/,Fo)))}symbol(e){return T[e]&&(e=T[e]),Go[e]?this.text("ord",Go[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)?na(this.el("var",ea(e[0]))+this.el("prime",ea(e.slice(1)))):/^Δ[A-Za-z]$/.test(e)?na(this.el("ord","Δ")+this.el("var",e[1])):/^d[A-Za-zα-ω]$/.test(e)?na(this.el("ord","d")+this.el("var",e[1])):e.endsWith("⁻¹")?this.script(this.symbol(e.slice(0,-2)),this.text("num","−1"),{level:0}):/^\\[A-Za-z]+$/.test(e)?this.text("name",e.slice(1)):/^[A-Za-z]{2,}$/.test(e)?this.text("name",e):this.text("ord",e)}operation(e,t){const{op: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=Lo[n]??(/^[a-z0-9]+$/i.test(n)?n:"other"),c=t=>this.wrap(e,["op",`op-${l}`],t),h=(t,n)=>D(e,t,n)&&"/"!==t.op?this.fence(a(t)):a(t);if(Do.includes(n)||"log"===n)return c(this.named(e,t));if(Uo[n])return c(ra(this.word(Uo[n]),this.fence(this.list(r,t))));if(o(n))return c(this.custom(e,t));const f=he(e);if(f)return c(this.matrix(e,f,t));if("{}"===n&&!r.length)return c(this.text("op","∅"));if(Vo[n])return c(this.fence(this.list(r,t),...Vo[n]));if(("|"===n||"&"===n)&&r.length>=2&&r.every(la)){const e=e=>"|"!==e.op&&"&"!==e.op||e.op===n?a(e):this.fence(a(e));return c(ra(r.map((t,r)=>r?[this.text("conj","|"===n?"or":"and"),e(t)]:[e(t)]).flat()))}if(Ro[n]&&2===r.length)return c(ra(h(s,"left"),this.rel(Ro[n]),h(i,"right")));if(Bo[n]&&2===r.length)return c(ra(h(s,"left"),this.bin(Bo[n]),h(i,"right")));switch(n){case"+":if(B(i)){const e=i.args[1],t=D({op:"-"},e,"right")?this.fence(a(e)):a(e);return c(ra(h(s,"left"),this.bin(Fo),this.wrap(i,["op","op-mul"],t)))}return"number"===i.type&&i.value.startsWith("-")?c(ra(h(s,"left"),this.bin(Fo),this.wrap(i,["number"],this.text("num",i.value.slice(1))))):c(ra(h(s,"left"),this.bin("+"),this.signed(i,h(i,"right"))));case"-":return c(ra(h(s,"left"),this.bin(Fo),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=P(s)&&u(P(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(ra(this.text("sign",Fo),U(n,s)?this.fence(a(s)):a(s,{before:t.before})));case"pm":return c(ra(this.text("sign","±"),U(n,s)?this.fence(a(s)):a(s)));case"!":return c(ra(U(n,s)?this.fence(a(s)):a(s,{forceParens:!0}),this.text("ord","!")));case"\\not":return c(ra(this.text("sign","¬"),U(n,s)?this.fence(a(s)):a(s)));case"pmod":return c(ra(a(s),this.fence(ra(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(ra(this.word("ln"),this.fence(ra(this.word("ln"),this.fence(a(s))))));case"logloglog":return c(ra(this.word("ln"),this.fence(ra(this.word("ln"),this.fence(ra(this.word("ln"),this.fence(a(s))))))));case"perm":return c(this.script(this.script(na(""),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):ra(a(s),this.bin("?"),a(i),this.bin(":"),a(r[2])));case"sum":case"prod":{const e={op:"sum"===n?"+":"*"},t=(t,n)=>D(e,t,n?"right":"left")?this.fence(a(t)):a(t);return c(ra(r.map((e,r)=>r?[this.bin("sum"===n?"+":"·"),t(e,r)]:[t(e,r)]).flat()))}case"setbuilder":return c(this.fence(ra(a(s),this.bin("|"),a(i)),"{","}"));case"evaluated":{const e=e=>this.render(e,{...t,level:t.level+1});return c(this.script(this.fence(a(s),"[","]"),e(r[3]),t,e(r[2])))}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 ra(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(B(e))return ra(this.text("sign",Fo),U("neg",r)?this.fence(this.render(r,t)):this.render(r,t));const s=function(e){const[t,n]=e.args;return{left:D(e,t,"left")&&"/"!==t.op,right:D(e,n,"right")&&"/"!==n.op}}(e);Ho.includes(n.op)&&(s.left=!0);const i=!e.written&&V(n,r,s),a=function(e){for(;"op"===e.type;){if(Do.includes(e.op)||"log"===e.op||Uo[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 ra(l,i?na(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=Wo[r]&&"power"===this.o.inverseTrig?this.script(this.word(Wo[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&&oa(i),l=this.render(i,{...t,forceParens:!1,before:!1});return ra(o,a?ra(na(this.el("fnspace","")),l):this.fence(l))}custom(e,t){const n=ee(e.op),r=e.args;if(Yo.includes(n)&&1===r.length)return this.decorate(n,this.render(r[0],t),r[0]);return ra(/^[A-Za-z]′*(⁻¹)?$/.test(n)?this.symbol(n):this.word(n),na(this.el("callgap","")),this.fence(this.list(r,t)))}decorate(e,t,n){switch(e){case"boxed":return na(this.el("boxed",t.html),t.h+.22,t.d+.22);case"cancel":return na(this.el("cancel",t.html+_o("cancel",`${this.p}-cancel-line`)),t.h,t.d);case"underline":return na(this.el("underline",t.html),t.h,t.d+.12);case"overline":case"bar":return na(this.el("over"+(Jo(n)?" over-low":""),t.html),t.h+.14,t.d);default:{const r=Jo(n);return na(this.el("accent"+(r?" accent-low":""),this.el(`accent-mark accent-${e}`,Qo[e])+t.html),t.h+.3,t.d)}}}fraction(e,t){const[n,r]=e.args;if(t.level>0&&"slash"===this.o.scriptFractions&&oa(n,!0)&&oa(r,!0)){const e={...t,leftFactor:!1},s=(t,n)=>"op"!==t.type||oa(t)&&(!n||"*"!==t.op||B(t))?this.render(t,e):this.fence(this.render(t,e)),i=ra("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:${ta(r)}`),i=n?.06:0,o=Co+i/2+.1+Math.max(To,r*e.d),a=this.el("frac"+(n?"":" frac-nobar"),this.el("numer",s(e))+this.el("denom",s(t)),`vertical-align:${ta(o)}`);return na(a,o+Math.max(jo,r*e.h),Math.max(jo,r*t.h)+Math.max(To,r*t.d)+.1+i/2-Co)}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&&Po.includes(n.op)&&ca(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=D(e,n,"left")||"number"===n.type&&n.value.startsWith("-")||"/"===n.op||Do.includes(n.op)||Ho.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:Zo,o=s?ra(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:${ta(i)}`);if(t&&!r)return na(e.html+this.el("sup",t.html,`font-size:${ta(i)};vertical-align:${ta(a/i)}`),Math.max(o.h,a+i*t.h),Math.max(o.d,i*t.d-a));if(r&&!t)return na(o.html+this.el("sub",r.html,`font-size:${ta(i)};vertical-align:${ta(-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,f=this.el("subsup",u(t)+u(r),`vertical-align:${ta(a)};height:${ta(c+h)}`);return na(o.html+f,Math.max(o.h,c),Math.max(o.d,h))}radical(e,t=null){const n=Math.max(e.h,jo)+.1+.06,r=Math.max(e.d,To),s=n+r,i=.5+.06*(s-1),o=_o("sqrt",`${this.p}-hook`,`width:${ta(i)};left:${ta(-i)}`);let a="";if(t){const e=.8*Zo;a=this.el("rootindex",t.html,`font-size:${ta(e)};vertical-align:${ta((.55*s-r)/e)}`)}return na(this.el("sqrt",a+this.el("radicand",o+e.html,`margin-left:${ta(i+.05)}`)),n,r)}fence(e,t="(",n=")"){const r=Math.max(e.h,jo)+Math.max(e.d,To),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:_o(e,`${this.p}-delim ${this.p}-delim-${t}`,`width:${ta(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");if(!s){const t=na(this.el("fence fence-line",a.html+e.html+l.html),Math.max(e.h,jo),Math.max(e.d,To));return t.fenced=!0,t}const u=`padding:${ta(i)} ${ta(l.w)} ${ta(i)} ${ta(a.w)}`,c=na(this.el("fence",a.html+e.html+l.html,u),Math.max(e.h,jo)+i,Math.max(e.d,To)+i);return c.fenced=!0,c}derivative(e,t){const n=this.leibniz(e,t),{by:r,at:s}=se(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}=se(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=ra(a(),l()?this.script(this.render(s,c),l(),c):this.render(s,c)),f=e=>ra(l()?this.script(a(),l(),c):a(),e||[]),p=t.level>0||t.inFraction||!this.o.display?.8:1;if(i)return this.stack(f(this.render(r,c)),h,!0,p);const m=P(r)&&u(P(r))<100,[d,g]="("===this.o.derivativeBrackets?["(",")"]:["[","]"],v=m?this.fence(this.render(r,t),d,g):this.render(r,t);return ra(this.stack(f(),h,!0,p),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",j(n)||"x");let u,c=null,h=null;switch(e.length){case 1:u=l();break;case 2:K(r)?u=o(r):(u=l(),c=a(r));break;case 3:K(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 f=o(n),p=na(this.el("dx",this.el("d","d")+u.html),u.h,u.d);return ra(this.bigSign("int",f,c,h,t),f,p)}bigSign(e,t,n,r,s){const i=!this.o.display||s.level>0,o=Math.max(i?.6:.95,Math.max(t.h-Co,t.d+Co)+.12),a=_o(e,`${this.p}-bigsign ${this.p}-${e}sign`,`height:${ta(2*o)};width:${ta(i?.38:.5)};vertical-align:${ta(Co-o)}`);if(!n&&!r)return na(a,Co+o,o-Co);const l=Zo,u=r||na(""),c=n||na(""),h=Co+o-l*u.h;c.d;const f=this.el("limits",this.el("script",u.html,`font-size:${ta(l)}`)+this.el("script lower",c.html,`font-size:${ta(l)}`),`vertical-align:${ta(h)};height:${ta(2*o)}`);return na(a+f,Co+o,o-Co)}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 ra(this.word("lim"),na(this.el("fnspace","")),this.body(n,t));case 2:{const e=j(n),t="number"===r.type||"symbol"===r.type&&r.value.includes("∞");u=e&&t?ra(this.text("var",e),l(),a(r)):a(r);break}case 3:u=ra(a(r),l(),a(s));break;default:{const e=C(i).toLowerCase().startsWith("r")?"+":Fo;u=ra(a(r),l(),this.script(a(s),this.wrap(i,["symbol"],this.text("ord",e)),o))}}return ra(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):na(this.el("under",e.html+this.el("script",t.html,`font-size:${ta(.7)}`)),e.h,Math.max(e.d,To)+.05+.7*(t.h+t.d))}body(e,t){const n=P(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=_o(e,`${this.p}-bigsign`,`height:${ta(2*t)};width:${ta(.8)};vertical-align:${ta(Co-t)}`);return ra(this.script(na(r,Co+t,t-Co),l,n,a),u)}const c=.68,h=Zo,f=_o(e,`${this.p}-bigsign`,`height:${ta(1.36)};width:${ta("sum"===e?1:1.05)}`),p=l?1.01+h*l.d:Co-c,m=e=>this.el("script",e.html,`font-size:${ta(h)}`),d=this.el("bigop",(l?m(l):"")+f+(a?m(a):""),`vertical-align:${ta(p)}`);return ra(na(d,.93+(l?.08+h*(l.h+l.d):0),c-Co+(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(jo,...e.map(e=>e.h)),d:Math.max(To,...e.map(e=>e.d))})),i=s.reduce((e,t)=>e+t.h+t.d,0)+.3*(t.length-1),o=Co+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"],na(r)).html:r}).join(""),l=t[0].length,u=na(this.el("matrix",a,`grid-template-columns:repeat(${l},auto);vertical-align:${ta(o)}`),Co+i/2,i/2-Co),[c,h]=ce[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),ra(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=Co+i/2-s[0].h,a=n.map(([e,t])=>this.el("case-value",e.html)+this.el("case-cond",t.html)).join(""),l=na(this.el("cases",a,`vertical-align:${ta(o)}`),Co+i/2,i/2-Co);return this.fence(l,"{","")}}function oa(e,t=!1){return"number"===e.type?!e.value.startsWith("-")||t:"symbol"===e.type||"op"===e.type&&("abs"===e.op||he(e)?!t:!t||"neg"!==e.op&&"^"!==e.op?"*"===e.op&&!B(e)&&e.args.every(e=>"number"===e.type&&!e.value.startsWith("-")||ua(e)||"*"===e.op&&oa(e,t)):oa(e.args[0],!0)&&("neg"===e.op||oa(e.args[1],!0)))}const aa=["=","===","≠","≠=","<",">","≤","≥","≈","≡","∈","∉"],la=e=>"op"===e.type&&e.args.length>=2&&(2===e.args.length&&aa.includes(e.op)||("|"===e.op||"&"===e.op)&&e.args.every(la)),ua=e=>"symbol"===e.type&&(1===e.value.length||/^[α-ωΑ-Ω]$/.test(e.value)||Boolean(T[e.value])),ca=e=>"number"===e.type&&/^[1-9]\d*$/.test(e.value)&&Number(e.value)<10;for(const e of[Lo,Ro,Bo,Wo,Uo,Vo,Go,Qo])Object.setPrototypeOf(e,null);function ha(e){const{id:t,from:n,...r}=e;return r.args&&(r.args=r.args.map(ha)),r}const fa=e=>I(e).join(" ");function pa(e,t){const n=new Set;ma(e,t,n);const r=[];return _(e,e=>{n.has(e)&&r.push(e)}),r}function ma(e,t,n){if(null!=t)if(Array.isArray(t))t.forEach(t=>ma(e,t,n));else if("number"!=typeof t)if("function"!=typeof t){if("string"==typeof t){const r=fa(dr(t));return void _(e,e=>{fa(e)===r&&n.add(e)})}if(t.path){const r=da(e,t.path);return void(r&&n.add(r))}if(t.type){const r=fa(t);_(e,e=>{e!==t&&fa(e)!==r||n.add(e)})}}else _(e,(e,r)=>{t(e,r)&&n.add(e)});else _(e,e=>{e.id===t&&n.add(e)})}function da(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 ga(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 va(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 ba(e,t={}){const{blocks:n}=t;if("string"==typeof e)return dr(e,n?{blocks:e=>n(e,t.scope)}:{});if(Array.isArray(e))return E(e);if(e&&"object"==typeof e&&e.type){if(void 0!==e.id)return e;const t=structuredClone(e);return _(t,e=>{"op"!==e.type&&void 0!==e.value&&(e.value=String(e.value))}),va(t)}throw new Error("Inline Math needs an expression, standard postfix or a tree")}function ya(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(wa(r))for(const n of pa(e,t))a.set(n,`color:${r}`);const l=new Set(void 0===r?[]:pa(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 wa(e){return"string"==typeof e&&/^[#\w\s.,%()/+-]+$/.test(e)&&!/url\s*\(|expression/i.test(e)}function xa(e,t={}){return ba(e,{...t,blocks:t.blocks??yo})}function $a(e,t={}){return function(e,t={}){const n=ba(e,t);return sa(n,ya(n,t)).html}(e,{...t,blocks:t.blocks??yo})}function ka(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 ha(r(e,0))}function qa(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`},f=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:f.fontSize}),h(),a.body.appendChild(c),l.getSelection?.()?.removeAllRanges(),c.focus(),c.select();let p=!1;const m=()=>{p=!0,c.remove()};c.cancelEdit=()=>{p||(m(),s&&s())};const d=e=>{if(p)return!0;if(!e||c.value===t)return m(),s&&s(),!0;let i;try{i=n(c.value)}catch(e){return c.setAttribute("aria-invalid","true"),c.title=e.message,!1}return m(),r(i,c.value),!0};return c.addEventListener("keydown",e=>{e.stopPropagation(),"Enter"===e.key&&(e.preventDefault(),d(!0)),"Escape"===e.key&&(e.preventDefault(),d(!1))}),c.addEventListener("input",()=>{h(),c.removeAttribute("aria-invalid"),c.removeAttribute("title")}),c.addEventListener("blur",()=>{d(!0)||d(!1)}),c}class Ma{constructor(e,t,n={}){this.element=e,this.options=n,this.p=n.prefix||"mv",this.handlers=[],this.clicks=[],this.active=null,this.live=Aa(e,n.announce,this.p),this.set(t)}set(e,{animate:t=!1,duration:n=600,easing:r="ease-in-out"}={}){const s=xa(e,this.options),{html:i}=sa(s,ya(s,this.options));if(this.editor){const e=this.editor;this.editor=null,e.cancelEdit?.()}const o=Sa(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 Io(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 pa(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=pa(this.tree,r)[0];t({node:s,id:r,path:ga(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(pa(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=ga(this.tree,n.id)||[],s=this.elementOf(n)||this.root;let i="Edit";try{i=`Edit ${Io(n)}`}catch{}const o=()=>{t&&this.root.focus&&this.root.focus()};return this.editor=qa(s,this.editing.toText(n),{label:i,prefix:this.p,parse:e=>xa(e,this.options),commit:(e,n)=>{this.set(ka(this.tree,r,e),{animate:!0});const s=da(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||Aa(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:ga(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?Io(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=ga(this.tree,e.id);for(let e=t?t.length-1:-1;e>0;e--){const n=da(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 Eo(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=fa(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(fa(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(fa(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 Aa(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 Sa(e){return!!e&&("always"===e||!("function"==typeof matchMedia&&matchMedia("(prefers-reduced-motion: reduce)").matches))}const Na=Symbol.for("inlinemath.expressions"),Oa=new Set(["symbol","number"]);function Ea(e){return e?"symbol"===e.type?e.value:"op"===e.type&&"_"===e.op&&2===e.args.length&&"symbol"===e.args[0].type&&Oa.has(e.args[1].type)?`${e.args[0].value}_${e.args[1].value}`:null:null}function Ia(e){const{id:t,...n}=e;return n.args&&(n.args=n.args.map(Ia)),n}function za(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 _a=new Set;function ja(e,t){let n=!1;const r=new Set,s=(e,i=_a)=>{const o=Ea(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(ha(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?j(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?Ia(i):e,changed:n}}const Ta="[-+]?(?:\\d+\\.?\\d*|\\.\\d+)",Ca=new RegExp(`^(${Ta})\\s*\\.\\.\\s*(${Ta})(?:\\s+step\\s+(${Ta}))?(?:\\s*=\\s*(${Ta}))?$`);function Za(e){const t=/^\s*\[\[([\s\S]*)\]\]\s*$/.exec(e);if(!t||/\]\s*,\s*\[/.test(t[1]))return null;const n=t[1].trim(),r=Ca.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 Fa=Symbol("set on the page");class La{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(Fa));n.set(e,{name:e,text:t,key:`page:${t}`,input:null}),this.owners.delete(Fa),this.owners.set(Fa,n)}return this.notify(null,e),this}clear(e){return void 0===e?(this.owners.clear(),this.chosen.clear()):(this.owners.get(Fa)?.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 Ra(){return new La}const Ba=Ra(),Pa=new RegExp("(\\d+)","g");function Wa(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=Ka.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}=Da(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 Da(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 Ua=e=>String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),Va=/^\s*([A-Za-z\u0370-\u03ff](?:_\{?\w+\}?)?)\s*=\s*([^=<>≤≥]+)$/;function Ha(e,t,n,r){const{text:s,math:i}=Wa(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,f=[],p=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=xa(a(r),e)}catch{}t.set(n,s)}return t.get(n)}};let m=!0;const d=i.map((e,n)=>{const{source:r,display:s}=e;m&&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=bo(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=p({});for(const e of o.keys()){const r=n(e);if(r)try{t[e]=I(ja(r,t=>t===e?null:n(t)).tree)}catch{}}u[Na]=t})(),m=!1);const i=s?"mv-md-display":"mv-md-math",d=(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:Ea(xa(o))}catch{}return null!==l&&a?{hidden:n,lhs:o,name:l,rhs:a,input:Za(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="${Ua(r)}" aria-label="${Ua(r)}"`;if("dropdown"===n.kind)return`<select ${s}>${n.options.map(e=>`<option value="${Ua(e)}"${e===t?" selected":""}>${Ua(e)}</option>`).join("")}</select>`;return"slider"===n.kind?`<input type="range" ${s} min="${n.min}" max="${n.max}" step="${n.step}" value="${Ua(t)}"><output class="mv-md-output" data-mv-out="${Ua(r)}">${Ua(t)}</output>`:`<input type="text" ${s} value="${Ua(t)}" size="${Math.max(4,t.length+1)}" spellcheck="false" autocomplete="off">`}(l,a(l));u=s?e:`${$a(g.lhs,i)}<span class="mv-md-assign" aria-hidden="true">≔</span>${e}`,h.add(n)}else{const e=ja(xa(g.rhs,i),p(i)).tree;if(!s){const t=va({type:"op",op:"=",args:[ha(xa(g.lhs)),void 0===e.id?e:ha(e)]});f[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>")}($a(t,i),i.prefix)}}return o.delete(t),o.set(t,l),c.set(t,l),m=!0,s&&!r?"":d(u,r?" mv-md-input-def":"")}const{tree:v,changed:b}=ja(xa(r,i),p(i));b&&va(v),f[n]=v;const y=$a(v,i);return!b&&!1!==t.define&&function(e,t,n){const r=Va.exec(e);if(!r||/\{\{/.test(r[2]))return!1;const s=r[1].replace(/[{}]/g,"");if(n.has(s))return!1;try{const e=bo(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)&&(m=!0),d(y)}catch(t){return`<span class="mv-md-error" data-mv-md="${n}" title="${Ua(t.message)}"><code>${Ua(e.raw)}</code></span>`}});return{text:s,math:i,drawn:d,defs:c,inputs:h,trees:f}}const Ga=/^(https?:|mailto:|#|\/|\.{0,2}\/|[^:]*$)/i,Qa=e=>Ga.test(e.trim())?Ua(e.trim()):"#",Xa=/\uE002(\d+)\uE003/g;function Ja(e,t,n,r=[]){const s=e=>(r.push(e),`${r.length-1}`),i=e=>(e=>e.replace(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&"))(n(e).replace(Xa,(e,t)=>(r[Number(t)]??"").replace(/<[^>]*>/g,"")));let o=e;o=o.replace(/(`+)([\s\S]*?[^`])\1(?!`)/g,(e,t,r)=>s(`<code>${Ua(n(r.trim()))}</code>`)),o=o.replace(/\\([\\`*_{}[\]()#+\-.!|~$<>"'])/g,(e,t)=>s(Ua(t))),o=o.replace(/<((?:https?:\/\/|mailto:)[^\s>]+)>/g,(e,t)=>s(`<a href="${Qa(t)}">${Ua(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="${Qa(i(n))}" alt="${Ua(i(t))}"${r?` title="${Ua(i(r))}"`:""}>`)),o=o.replace(/\[([^\[\]]+)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,o,a,l)=>s(`<a href="${Qa(i(a))}"${l?` title="${Ua(i(l))}"`:""}>${Ja(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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),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(Xa,(e,t)=>r[Number(t)]??"");return o}const Ya=/^( {0,3})(#{1,6}\s|>|```|~~~|([-*+]|\d{1,9}[.)])\s|(\*[ \t]*){3,}$|(-[ \t]*){3,}$|(_[ \t]*){3,}$)/,Ka=/^( {0,3})([-*+]|\d{1,9}[.)])(\s+|$)/,el=/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/,tl=e=>Ya.test(e)&&!/^ {0,3}[-=]+\s*$/.test(e)&&!/^ {0,3}(?!1[.)])\d{1,9}[.)]\s/.test(e);function nl(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 rl(e,t,n,r=0){const s=[];let i=0;const o=e=>Ja(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-${Ua(l[2])}"`:"";s.push(`<pre><code${r}>${Ua(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(nl(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${rl(o,t,n,r+1)}\n</blockquote>`);continue}const c=Ka.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=Ka.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&&Ka.test(t)&&(u=!0);break}if(t.startsWith(" ".repeat(Math.min(n,4))))r.push(t.slice(Math.min(n,4)));else{if(Ka.test(t)||Ya.test(t))break;r.push(t)}i++}for(l.push(r);i<e.length&&!e[i].trim()&&void 0!==e[i+1]&&Ka.test(e[i+1]);)i++}const h=o?"ol":"ul",f=l.map(e=>{let s=rl(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${f.join("\n")}\n</${h}>`);continue}if(a.includes("|")&&void 0!==e[i+1]&&el.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>${Ua(n(t.join("\n")))}</code></pre>`);continue}const h=[];for(;i<e.length&&e[i].trim()&&(!h.length||!tl(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 sl(e,t={},n=e=>e){return rl(String(e).replace(/\r\n?/g,"\n").replace(/[\uE002\uE003]/g,"�").split("\n"),t,n)}function il({text:e,math:t,drawn:n},r){return(r.render?r.render(e):sl(e,r,e=>e.replace(Pa,(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(Pa,(e,t)=>n[Number(t)]??"").replace(/<p>\s*<\/p>\n?/g,"")}const ol=new WeakMap,al=new Set;function ll(){for(const e of al)e.connected()&&!e.element.isConnected&&e.stop(!0)}function ul(e){const t=e=>function(e){if(e.length>1e6)throw new Error("The output would be too long");return e}("op"===e.type?fl(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 cl={"+":"+","-":"-","*":"*","/":"/","^":"^",mod:"mod","±":"±","=":"=","===":"===","≠":"≠","≠=":"≠","<":"<",">":">","≤":"≤","≥":"≥","∈":"∈","∉":"∉","→":"→","≈":"≈","∪":"∪","∩":"∩","≡":"≡","&":"∧","|":"∨","\\xor":"⊕","\\nand":"↑","\\nor":"↓","\\implies":"⇒","\\iff":"⇔"},hl={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]};function fl(e,t){const{op:n,args:r}=e,[s,i]=r,a=(e,r)=>c(n,P(e),r)?`(${t(e)})`:t(e),l=()=>r.map(t).join(", "),u=e=>U(n,e)?`(${t(e)})`:t(e);if("*"===n&&B(e))return fl({...e,op:"neg",args:[i]},t);if("+"===n&&B(i))return fl({...e,op:"-",args:[s,i.args[1]]},t);if("-"===n&&B(i))return fl({...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(cl[n])return`${a(s,"left")} ${cl[n]} ${a(i,"right")}`;if(ce[n])return`${n}(${he(e).map(e=>`[${e.map(t).join(", ")}]`).join(", ")})`;if(hl[n])return hl[n][0]+l()+hl[n][1];if(o(n))return`${ee(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`${ae(s)?`(${t(s)})`:t(s)} ? ${t(i)} : ${t(r[2])}`;case"sum":return r.map((e,n)=>c("+",P(e),n?"right":"left")?`(${t(e)})`:t(e)).join(" + ");case"prod":return r.map((e,n)=>c("*",P(e),n?"right":"left")?`(${t(e)})`:t(e)).join(" * ");case"setbuilder":return`{${r.map(t).join(" : ")}}`;case"evaluated":return`evaluated(${r.map(t).join(", ")})`;case"der":{const{n:n,body:r,by:s,at:i,variable:o}=se(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&&K(r)?t(r):j(n)||"x",a=`${t(n)} d${o}`;return 1===e.length||2===e.length&&K(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)}, ${C(i).toLowerCase().startsWith("r")?"r":"l"})`:`lim(${e.map(t).join(", ")})`}(r,t);case"\\sumidx":return pl("∑",r,t);case"\\prodidx":return pl("∏",r,t)}return`${n}(${l()})`}function pl(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=j(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[cl,hl])Object.setPrototypeOf(e,null);function ml(e){return vr(e)?"":ul(gr(e))}const dl=new Map,gl=-1,vl="\\:",bl=e=>"string"==typeof e&&e.startsWith(vl)&&e.length>2;function yl(e){if(!e||!e.symbol)throw new Error("operator needs a symbol");if(!Number.isInteger(e.arity)||e.arity<0&&e.arity!==gl)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 dl.set(t.symbol,t),t}const wl=Object.freeze({symbol:vl,arity:gl,commutative:!1,fold:null,label:"function"});function xl(e){const t=dl.get(e);return t||(bl(e)?{...wl,symbol:e,label:e.slice(2)}:null)}function $l(e){return dl.has(e)||bl(e)}const kl=e=>Number.isFinite(e)&&Number.isInteger(e)?e:null,ql=e=>Number.isFinite(e)?e:null;!function(){yl({symbol:"+",arity:2,commutative:!0,label:"add",fold:(e,t)=>ql(e+t)}),yl({symbol:"-",arity:2,label:"subtract",fold:(e,t)=>ql(e-t)}),yl({symbol:"*",arity:2,commutative:!0,label:"multiply",fold:(e,t)=>ql(e*t)}),yl({symbol:"/",arity:2,label:"divide",fold:(e,t)=>0===t?null:kl(e/t)}),yl({symbol:"^",arity:2,label:"power",fold:(e,t)=>Number.isInteger(t)&&Math.abs(t)<=64?ql(e**t):null}),yl({symbol:"neg",arity:1,label:"negate",fold:e=>ql(-e)}),yl({symbol:"pm",arity:1,label:"plus or minus"}),yl({symbol:"±",arity:2,label:"plus or minus"}),yl({symbol:"mod",arity:2,label:"modulo",fold:(e,t)=>0===t?null:kl((e%t+t)%t)}),yl({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}),yl({symbol:"_",arity:2,label:"subscript"}),yl({symbol:"der",arity:2,label:"derivative"}),yl({symbol:"evaluated",arity:4,label:"evaluated from a to b"}),yl({symbol:"setbuilder",arity:2,label:"the set of … such that"}),yl({symbol:"int",arity:gl,label:"integral"}),yl({symbol:"lim",arity:gl,label:"limit"}),yl({symbol:"\\sumidx",arity:gl,label:"sum over an index"}),yl({symbol:"\\prodidx",arity:gl,label:"product over an index"}),yl({symbol:"abs",arity:1,label:"absolute value",fold:e=>ql(Math.abs(e))}),yl({symbol:"floor",arity:1,label:"floor",fold:e=>ql(Math.floor(e))}),yl({symbol:"ceil",arity:1,label:"ceiling",fold:e=>ql(Math.ceil(e))}),yl({symbol:"round",arity:2,label:"round",fold:(e,t)=>Number.isInteger(t)?ql(Math.round(e*10**t)/10**t):null}),yl({symbol:"fixed",arity:2,label:"fixed",fold:()=>null}),yl({symbol:"sqrt",arity:1,label:"square root",fold:e=>kl(Math.sqrt(e))}),yl({symbol:"root",arity:2,label:"nth root",fold:(e,t)=>kl(Math.round(t**(1/e))**e===t?Math.round(t**(1/e)):NaN)});for(const e of["sin","cos","tan","csc","sec","cot","sinh","cosh","tanh","arcsin","arccos","arctan","arcsec","arccsc","arccot","arcsinh","arccosh","arctanh","ln","loglog","logloglog","expm1"])yl({symbol:e,arity:1,label:e});yl({symbol:"log",arity:2,label:"log to a base"}),yl({symbol:"atan2",arity:2,label:"atan2"}),yl({symbol:"perm",arity:2,label:"permutations"}),yl({symbol:"comb",arity:2,label:"combinations"}),yl({symbol:"random",arity:0,label:"random"});for(const e of["max","min","gcd","mean","sum","prod"])yl({symbol:e,arity:gl,label:e});for(const e of["()","[]","{}","(]","[)"])yl({symbol:e,arity:gl,label:"group"});for(const e of["pmatrix","bmatrix","vmatrix"])yl({symbol:e,arity:gl,label:"matrix"});yl({symbol:"det",arity:1,label:"determinant"});for(const e of["=","===","≠","≠=","<",">","≤","≥","∈","∉","∪","∩","≈","≡","→","pmod","&","|","\\xor","\\nand","\\nor","\\implies","\\iff"])yl({symbol:e,arity:2,label:e});yl({symbol:"\\not",arity:1,label:"not"}),yl({symbol:"?:",arity:3,label:"if then else"})}();const Ml="num",Al="sym",Sl="op",Nl=Object.freeze([]);class Ol extends Error{constructor(e){super(e),this.name="ExprError"}}function El(e){if("number"!=typeof e||!Number.isFinite(e))throw new Ol(`not a finite number: ${e}`);const t=(n=e,Object.is(n,-0)?"0":String(n));var n;return Object.freeze({type:Ml,token:t,value:e,args:Nl,s:t})}function Il(e){if("string"!=typeof e||""===e)throw new Ol("symbol needs a non-empty token");return Object.freeze({type:Al,token:e,value:null,args:Nl,s:e})}function zl(e){const t=/^(-?)0*(\d+?)(?:\.(\d*?)0*)?$/.exec(String(e));if(!t)throw new Ol(`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:Ml,token:o,value:Number(o),args:Nl,s:o})}const _l=/^-?\d+(\.\d+)?$/;function jl(e){const t=String(e);if(_l.test(t))return zl(t);if(""!==t&&!/\s/.test(t)){const e=Number(t);if(Number.isFinite(e))return El(e)}return Il(t)}function Tl(e,t){const n=xl(e);if(!n)throw new Ol(`unknown operator "${e}"`);if(n.arity!==gl&&t.length!==n.arity)throw new Ol(`"${e}" takes ${n.arity} operand(s), got ${t.length}`);const r=Object.freeze(t.slice()),s=n.arity===gl?` ${r.length}`:"",i=`${r.length?r.map(e=>e.s).join(" "):""}${r.length,""}${s} ${e}`.trimStart();return Object.freeze({type:Sl,op:e,token:e,value:null,args:r,s:i})}const Cl=e=>e.type===Ml,Zl=e=>e.type===Sl;function Fl(e){return Ll(function(e){const t=String(e).trim();return""===t?[]:t.split(/\s+/)}(e))}function Ll(e){if(!Array.isArray(e))throw new Ol("fromPostfix needs an array of tokens");if(0===e.length)throw new Ol("empty expression");const t=[];for(let n=0;n<e.length;n++){const r=String(e[n]);if($l(r)){let e=xl(r).arity;if(e===gl){const s=t.pop();if(e=s&&s.type===Ml&&Number.isInteger(s.value)&&s.value>=0?s.value:-1,e<0)throw new Ol(`"${r}" at position ${n+1} takes any number of operands, so a count must come before it`)}if(t.length<e)throw new Ol(`"${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(Tl(r,s))}else t.push(jl(r))}if(1!==t.length){const n=[...new Set(e.filter(e=>!$l(e)))];throw new Ol(`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 Rl(e){if(e.type!==Sl)return 0;let t=0;for(const n of e.args)t=Math.max(t,Rl(n));return t+1}function Bl(e){if(e.type!==Sl)return 1;let t=1;for(const n of e.args)t+=Bl(n);return t}function Pl(e,t=[]){if(e.type!==Sl)t.push(e.token);else for(const n of e.args)Pl(n,t);return t}function Wl(e){return e.type===Ml||e.type!==Al&&e.args.every(Wl)}function Dl(e,t="pre",n=[],r=[]){"pre"===t&&r.push({node:e,path:n});for(let s=0;s<e.args.length;s++)Dl(e.args[s],t,n.concat(s),r);return"post"===t&&r.push({node:e,path:n}),r}function Ul(e,t){let n=e;for(const e of t){if(!n.args[e])throw new Ol(`bad path [${t.join(",")}]`);n=n.args[e]}return n}function Vl(e,t,n){if(0===t.length)return n;const[r,...s]=t,i=e.args.slice();return i[r]=Vl(i[r],s,n),Tl(e.op,i)}class Hl extends Error{constructor(e){super(e),this.name="CasError"}}const Gl=1e5,Ql=e=>e<0n?-e:e,Xl=e=>0n===e?0:Ql(e).toString(2).length;function Jl(e,t){for(e=Ql(e),t=Ql(t);t;)[e,t]=[t,e%t];return e}class Yl{constructor(e,t=1n){if(0n===t)throw new Hl("division by zero");t<0n&&(e=-e,t=-t);const n=Jl(e,t)||1n;if(this.n=e/n,this.d=t/n,Xl(this.n)>Gl||Xl(this.d)>Gl)throw new Hl("a number too large to keep exactly")}static of(e){return new Yl(BigInt(e))}add(e){return new Yl(this.n*e.d+e.n*this.d,this.d*e.d)}sub(e){return new Yl(this.n*e.d-e.n*this.d,this.d*e.d)}mul(e){return new Yl(this.n*e.n,this.d*e.d)}div(e){if(0n===e.n)throw new Hl("division by zero");return new Yl(this.n*e.d,this.d*e.n)}neg(){return new Yl(-this.n,this.d)}abs(){return this.n<0n?this.neg():this}inv(){return Yl.ONE.div(this)}pow(e){if((e=BigInt(e))<0n)return this.inv().pow(-e);if((0n===this.n||1n===Ql(this.n))&&1n===this.d)return 0n===e||-1n===this.n&&e%2n==0n?Yl.ONE:this;if(BigInt(Math.max(Xl(this.n),Xl(this.d)))*e>BigInt(Gl))throw new Hl("a power too large to work out exactly");return new Yl(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 Yl(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(Xl(this.n),Xl(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 Kl(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 Yl(BigInt((r||"0")+s),10n**BigInt(s.length));const a=Number(i);return a&&(o=o.mul(Yl.of(10).pow(a))),n?o.neg():o}function eu(e,t){if(e<2n)return e;if(t>=Xl(e))return 1n;const n=BigInt(t);let r=1n<<BigInt(Math.ceil(Xl(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}Yl.ZERO=new Yl(0n),Yl.ONE=new Yl(1n),Yl.MINUS_ONE=new Yl(-1n),Yl.HALF=new Yl(1n,2n);const tu=(()=>{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 nu(e,t){const n=BigInt(t);let r=1n,s=1n,i=e;for(const e of tu){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=eu(e,t);return n**BigInt(t)===e?n:null}(i,t);null!==e?r*=e:s*=i}return{outside:r,inside:s}}const ru=new Set(["pi","e","π"]),su={complex:!1};function iu(e,t){const n=su.complex;su.complex=Boolean(e);try{return t()}finally{su.complex=n}}const ou=e=>ru.has(e)||su.complex&&"i"===e,au=e=>su.complex&&"atom"===e.k&&"sym"===e.node.type&&"i"===e.node.token,lu=e=>({k:"num",q:e}),uu=lu(Yl.ONE),cu=lu(Yl.ZERO),hu=lu(Yl.HALF),fu=e=>"num"===e.k,pu=e=>({k:"atom",node:e}),mu=new WeakMap;function du(e){let t=mu.get(e);return void 0===t&&mu.set(e,t=Hu(e).s),t}function gu(e){if("num"===e.k)return 0;if("atom"===e.k)return"sym"===e.node.type&&ou(e.node.token)?0:1;if("add"===e.k)return Math.max(...e.terms.map(e=>gu(e.x)));let t=0;for(const n of e.fs){const e=gu(n.b);e&&(t+=e*(fu(n.e)?n.e.q.toNumber():1))}return t}function vu(e,t){return"num"===e.k?t&&!fu(t)?3:0:au(e)?1.5:"atom"===e.k&&"sym"===e.node.type?ou(e.node.token)?t&&!fu(t)?3:1:2:"atom"===e.k?3:4}const bu=(e,t)=>e<t?-1:e>t?1:0;function yu(e){const t=new Map,n=(e,n)=>{"atom"!==e.k||"sym"!==e.node.type||ou(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,fu(t.e)?t.e.q.toNumber():1);else n(e,1);return t}function wu(e,t){const n=gu(t.x)-gu(e.x);if(n)return n;const r=yu(e.x),s=yu(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 bu(du(e.x),du(t.x))}function xu(e,t){return e.isOne?t:e.isZero?cu:Mu([lu(e),t])}function $u(e){if("num"===e.k)return{coef:e.q,rest:null};if("mul"!==e.k||e.c.isOne)return{coef:Yl.ONE,rest:e};const t=1===e.fs.length&&fu(e.fs[0].e)&&e.fs[0].e.q.isOne?e.fs[0].b:{k:"mul",c:Yl.ONE,fs:e.fs};return{coef:e.c,rest:t}}function ku(e){let t=Yl.ZERO;const n=new Map,r=(e,t)=>{const r=du(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}=$u(n);r(e,t)}const s=[...n.values()].filter(e=>!e.coef.isZero);return s.length?t.isZero&&1===s.length?xu(s[0].coef,s[0].x):(s.sort(wu),{k:"add",c:t,terms:s}):lu(t)}function qu(e,t){if(!fu(t))return e.isOne?{coef:Yl.ONE,fs:[]}:{coef:Yl.ONE,fs:[{b:lu(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 Hl("division by zero");return{coef:Yl.ZERO,fs:[]}}if(e.isOne)return{coef:Yl.ONE,fs:[]};if(e.sign<0){if(n.d%2n==1n){const{coef:r,fs:s}=qu(e.neg(),t);return{coef:n.n%2n==0n?r:r.neg(),fs:s}}if(su.complex&&2n===n.d){const{coef:r,fs:s}=qu(e.neg(),t);return{coef:r,fs:[...s,{b:Nu,e:lu(new Yl(n.n))}]}}return{coef:Yl.ONE,fs:[{b:lu(e),e:t}]}}if(!e.isInteger){const r=qu(new Yl(e.n),t),s=qu(new Yl(e.d),lu(n.neg()));return{coef:r.coef.mul(s.coef),fs:[...r.fs,...s.fs]}}const r=n.floor(),s=n.sub(r);if(BigInt(Xl(e.n))*s.n>BigInt(Gl)||s.d>1000n)return{coef:Yl.ONE,fs:[{b:lu(e),e:t}]};let i=r.isZero?Yl.ONE:e.pow(r.n);const{outside:o,inside:a}=nu(e.n**s.n,Number(s.d));i=i.mul(new Yl(o));return{coef:i,fs:a>1n?[{b:lu(new Yl(a)),e:lu(new Yl(1n,s.d))}]:[]}}function Mu(e){let t=Yl.ONE;const n=new Map,r=(e,t)=>{const r=du(e),s=n.get(r);s?s.e=ku([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,uu);if(t.isZero)return cu;const s=[],i=new Map;for(const e of n.values())if(!fu(e.e)||!e.e.q.isZero){if("num"===e.b.k){if(fu(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=qu(e.b.q,e.e);t=t.mul(n.coef),s.push(...n.fs);continue}if("mul"===e.b.k&&fu(e.e)&&e.e.q.isInteger){const n=Au(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:uu});continue}s.push(e)}for(const{n:e,e:n}of i.values()){const r=qu(new Yl(e),n);t=t.mul(r.coef),s.push(...r.fs)}if(t.isZero)return cu;const o=new Map;for(const e of s){const t=du(e.b),n=o.get(t);n?n.e=ku([n.e,e.e]):o.set(t,{...e})}let a=[...o.values()].filter(e=>!(fu(e.e)&&e.e.q.isZero));if(su.complex){a=a.flatMap(e=>{if(!au(e.b)||!fu(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:uu}]:[]});const e=a.filter(e=>"add"===e.b.k&&fu(e.e)&&e.e.q.isInteger&&Eu(e.b)),n=a.some(e=>au(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)&&!au(t.b));let s=n?[Nu]:[uu];for(const t of e){const e=t.e.q.sign<0?_u(t.b):t.b;for(let n=0n;n<(t.e.q.sign<0?-t.e.q.n:t.e.q.n);n++)s=Iu(s,Ju(e))}return Mu([lu(t),ku(s),...r.map(e=>Su(e.b,e.e))])}}if(a.some(e=>"num"===e.b.k&&fu(e.e)&&e.e.q.compare(Yl.ONE)>=0))return Mu([lu(t),...a.map(e=>"num"===e.b.k?Au(e.b,e.e):{k:"mul",c:Yl.ONE,fs:[e]})]);if(!a.length)return lu(t);if(1===a.length&&!t.isOne&&"add"===a[0].b.k&&fu(a[0].e)&&a[0].e.q.isOne){const e=a[0].b;return ku([lu(t.mul(e.c)),...e.terms.map(e=>xu(t.mul(e.coef),e.x))])}return t.isOne&&1===a.length&&fu(a[0].e)&&a[0].e.q.isOne?a[0].b:(a=a.sort((e,t)=>vu(e.b,e.e)-vu(t.b,t.e)||bu(du(e.b),du(t.b))),{k:"mul",c:t,fs:a})}function Au(e,t){if(su.complex&&fu(t)&&t.q.isInteger){if(au(e))return Mu([{k:"mul",c:Yl.ONE,fs:[{b:e,e:t}]}]);if("add"===e.k&&Eu(e)&&!t.q.isOne)return Mu([{k:"mul",c:Yl.ONE,fs:[{b:e,e:t}]}])}if(fu(t)){if(t.q.isZero){if(fu(e)&&e.q.isZero)throw new Hl("0^0 is undefined");return uu}if(t.q.isOne)return e}if(fu(e)){const n=qu(e.q,t);if(!n.fs.length)return lu(n.coef);if(n.fs.some(e=>au(e.b)))return Mu([lu(n.coef),...n.fs.map(e=>({k:"mul",c:Yl.ONE,fs:[e]}))]);const r={k:"mul",c:n.coef,fs:n.fs};return n.coef.isOne&&1===n.fs.length&&fu(n.fs[0].e)&&n.fs[0].e.q.isOne?n.fs[0].b:r}if(su.complex&&fu(t)&&2n===t.q.d&&Eu(e)){const n=zu(e);if(n&&fu(n.im)&&!n.im.q.isZero){const e=e=>Au(e,lu(Yl.of(2))),r=Au(ku([e(n.re),e(n.im)]),hu),s=Au(Mu([ku([r,n.re]),lu(Yl.HALF)]),hu),i=Au(Mu([ku([r,Cu(n.re)]),lu(Yl.HALF)]),hu);return Au(ku([s,Mu([lu(Yl.of(n.im.q.sign)),i,Nu])]),lu(new Yl(t.q.n)))}}if("mul"===e.k){if(fu(t)&&t.q.isInteger)return Mu([lu(e.c.pow(t.q.n)),...e.fs.map(e=>Su(e.b,Mu([e.e,t])))]);if(!e.c.isOne&&e.c.sign>0)return Mu([Au(lu(e.c),t),Au({k:"mul",c:Yl.ONE,fs:e.fs},t)]);if(e.c.isOne&&1===e.fs.length){const[n]=e.fs;if(fu(n.e)&&fu(t)&&1n===n.e.q.n&&n.e.q.d%2n==1n)return Su(n.b,Mu([n.e,t]))}}return{k:"mul",c:Yl.ONE,fs:[{b:e,e:t}]}}function Su(e,t){return fu(t)&&t.q.isZero?uu:fu(e)?Au(e,t):fu(t)&&t.q.isOne?e:{k:"mul",c:Yl.ONE,fs:[{b:e,e:t}]}}const Nu=pu(Il("i")),Ou=e=>su.complex&&Hu(e).s.split(" ").includes("i");function Eu(e){return su.complex&&Ou(e)&&0===Xu(Hu(e)).size}function Iu(e,t){const n=[];for(const r of e)for(const e of t)n.push(Mu([r,e]));return Ju(ku(n))}function zu(e){const t=[],n=[];for(const r of Ju(e)){const{coef:e,rest:s}=$u(r),i=s?Yu(s):[],o=i.filter(e=>au(e)),a=i.filter(e=>!au(e));if(a.some(e=>Ou(e)))return null;(o.length?n:t).push(Mu([lu(e),...a]))}return{re:ku(t),im:ku(n)}}function _u(e){const t=zu(e);if(!t)return Au(e,lu(Yl.MINUS_ONE));const n=ku([Au(t.re,lu(Yl.of(2))),Au(t.im,lu(Yl.of(2)))]);return Mu([ku([t.re,Mu([lu(Yl.MINUS_ONE),t.im,Nu])]),Au(n,lu(Yl.MINUS_ONE))])}const ju={re:([e])=>zu(e)?.re??null,im:([e])=>zu(e)?.im??null,conj:([e])=>{const t=zu(e);return t?ku([t.re,Mu([lu(Yl.MINUS_ONE),t.im,Nu])]):null},arg:([e])=>{const t=zu(e);return t?Ru("atan2",[t.im,t.re]):null},abs:([e])=>{const t=zu(e);return!t||fu(t.im)&&t.im.q.isZero?null:Au(ku([Au(t.re,lu(Yl.of(2))),Au(t.im,lu(Yl.of(2)))]),hu)}},Tu={Re:"re",re:"re",Im:"im",im:"im",conj:"conj",overline:"conj",bar:"conj",arg:"arg"},Cu=e=>Mu([lu(Yl.MINUS_ONE),e]),Zu=(e,t)=>Mu([e,Au(t,lu(Yl.MINUS_ONE))]),Fu=3000n,Lu={abs:([e])=>fu(e)?lu(e.q.abs()):"mul"!==e.k||e.c.isOne?null:Mu([lu(e.c.abs()),Ru("abs",[$u(e).rest])]),floor:([e])=>fu(e)?lu(e.q.floor()):null,ceil:([e])=>fu(e)?lu(e.q.ceil()):null,"!":([e])=>{if(!fu(e)||!e.q.isInteger||e.q.sign<0||e.q.n>Fu)return null;let t=1n;for(let n=2n;n<=e.q.n;n++)t*=n;return lu(new Yl(t))},mod:([e,t])=>fu(e)&&fu(t)&&!t.q.isZero?lu(e.q.sub(t.q.mul(e.q.div(t.q).floor()))):null,max:e=>e.every(fu)&&e.length?e.reduce((e,t)=>t.q.compare(e.q)>0?t:e):null,min:e=>e.every(fu)&&e.length?e.reduce((e,t)=>t.q.compare(e.q)<0?t:e):null,gcd:e=>e.length&&e.every(e=>fu(e)&&e.q.isInteger)?lu(new Yl(e.reduce((e,t)=>Jl(e,t.q.n),0n))):null,log:([e,t])=>{if(!fu(e)||!fu(t)||e.q.sign<=0||t.q.sign<=0||e.q.isOne)return null;if(t.q.isOne)return cu;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 lu(new Yl(BigInt(s),BigInt(r)))}return null},comb:([e,t])=>fu(e)&&fu(t)&&e.q.isInteger&&t.q.isInteger&&e.q.sign>=0&&t.q.sign>=0&&e.q.n<=Fu?lu(function(e,t){if(t>e)return Yl.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 Yl(n)}(e.q.n,t.q.n)):null,perm:([e,t])=>{if(!(fu(e)&&fu(t)&&e.q.isInteger&&t.q.isInteger&&e.q.sign>=0&&t.q.sign>=0&&e.q.n<=Fu))return null;if(t.q.n>e.q.n)return cu;let n=1n;for(let r=0n;r<t.q.n;r++)n*=e.q.n-r;return lu(new Yl(n))}};function Ru(e,t){if(su.complex&&ju[e]){const n=ju[e](t);if(n)return n}const n=Lu[e];if(n){const e=n(t);if(e)return e}return pu(Tl(e,t.map(Hu)))}const Bu=new Map;function Pu(e){const t=su.complex?`ℂ ${e.s}`:e.s,n=Bu.get(t);if(n)return n;const r=function(e){if("num"===e.type){const t=Kl(e.token);if(!t)throw new Hl(`not an exact number: ${e.token}`);return lu(t)}if("sym"===e.type)return"π"===e.token?pu(Il("pi")):pu(e);const t=e.args.map(Pu);switch(e.op){case"+":return ku(t);case"-":return((e,t)=>ku([e,Cu(t)]))(t[0],t[1]);case"neg":return Cu(t[0]);case"*":return Mu(t);case"/":return Zu(t[0],t[1]);case"^":return Au(t[0],t[1]);case"sqrt":return Au(t[0],hu);case"root":return Au(t[1],Au(t[0],lu(Yl.MINUS_ONE)));default:{const n=e.op.startsWith("\\:")?e.op.slice(2):null;return n&&su.complex&&Tu[n]&&1===t.length?Ru(Tu[n],t):n&&$l(n)&&xl(n).arity===t.length?Ru(n,t):Ru(e.op,t)}}}(e);return Bu.size>2e4&&Bu.clear(),Bu.set(t,r),r}const Wu=e=>Hu(Pu(e)),Du=e=>zl(String(e));function Uu(e){return e.isInteger?Du(e.n):Tl("/",[Du(e.n),Du(e.d)])}const Vu=new WeakMap;function Hu(e){let t=Vu.get(e);return t||Vu.set(e,t=function(e){switch(e.k){case"num":return Uu(e.q);case"atom":return e.node;case"mul":return function(e,t){const n=[],r=[];for(const e of t)fu(e.e)&&e.e.q.sign<0?r.push(Gu(e.b,lu(e.e.q.neg()))):n.push(Gu(e.b,e.e));let s=1n!==e.n&&-1n!==e.n||!n.length?Qu([Du(e.n),...n]):Qu(n);-1n===e.n&&n.length&&(s=Tl("neg",[s]));1n!==e.d&&r.unshift(Du(e.d));return r.length?Tl("/",[s,Qu(r)]):s}(e.c,e.fs);case"add":return function(e){let t=null;const n=e=>su.complex&&Ou(e.x)&&0===Xu(Hu(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?Tl("-",[t,Uu(s.neg())]):Tl("+",[t,Uu(s)]):Uu(s))};let o=!1;for(const e of r)!o&&n(e)&&(i(),o=!0),t=t?e.coef.sign<0?Tl("-",[t,Hu(xu(e.coef.neg(),e.x))]):Tl("+",[t,Hu(xu(e.coef,e.x))]):Hu(xu(e.coef,e.x));o||i();return t}(e);default:throw new Error(`bad form ${e.k}`)}}(e)),t}function Gu(e,t){const n=Hu(e);if(fu(t)){const e=t.q;if(e.isOne)return n;if(1n===e.n&&2n===e.d)return Tl("sqrt",[n]);if(1n===e.n)return Tl("root",[Du(e.d),n])}return Tl("^",[n,Hu(t)])}const Qu=e=>e.reduce((e,t)=>e?Tl("*",[e,t]):t,null);function Xu(e,t=new Set){if("sym"===e.type)ou(e.token)||t.add(e.token);else if(Zl(e))for(const n of e.args)Xu(n,t);return t}function Ju(e){if("add"!==e.k)return[e];const t=e.terms.map(e=>xu(e.coef,e.x));return e.c.isZero||t.push(lu(e.c)),t}function Yu(e){if("num"===e.k)return[e];if("mul"!==e.k)return[e];const t=e.c.isOne?[]:[lu(e.c)];for(const n of e.fs)t.push(Su(n.b,n.e));return t}const Ku="_",ec=new WeakMap;function tc(e,t){return[...t,...xl(e.op)?.arity===gl?[String(e.args.length)]:[],e.op].join(" ")}function nc(e,t){let n=ec.get(e);n||ec.set(e,n=new Map);const r=n.get(t);if(r)return r;const s=function(e,t){const n={key:Ku,slots:[e]};if(e.type!==Sl||t<=0)return[n];const r=e.args.map(e=>nc(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:tc(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 rc(e){return e.type!==Sl?Ku:tc(e,e.args.map(rc))}function sc(e,t=[]){if(e.type!==Sl)t.push(e);else for(const n of e.args)sc(n,t);return t}const ic=new Map,oc=new Map;class ac extends Error{constructor(e){super(e),this.name="RequirementError"}}function lc(e,t,n=""){ic.set(e,{name:e,fn:t,doc:n,arity:Math.max(0,t.length-1)})}function uc(e,t,n=""){oc.set(e,{name:e,fn:t,doc:n})}function cc(e){return ic.get(e)||null}function hc(e){return oc.get(e)||null}const fc=e=>e.type===Ml;function pc(e,t){return e.type===Sl&&(e.op===t||e.args.some(e=>pc(e,t)))}lc("always",()=>!0,"matches anything"),lc("never",()=>!1,"matches nothing"),lc("isLeaf",e=>e.type!==Sl,"a bare operand, not an operation"),lc("isCompound",e=>e.type===Sl,"an operation, not a bare operand"),lc("isSymbol",e=>e.type===Al,"a non-numeric operand such as x"),lc("isOperation",(e,t)=>e.type===Sl&&e.op===t,"is this specific operation"),lc("notOperation",(e,t)=>!(e.type===Sl&&e.op===t),"is anything except this operation"),lc("isNumber",fc,"a numeric literal"),lc("isInteger",e=>fc(e)&&Number.isInteger(e.value),"a whole number"),lc("isPositive",e=>fc(e)&&e.value>0,"greater than zero"),lc("isNegative",e=>fc(e)&&e.value<0,"less than zero"),lc("isNonNegative",e=>fc(e)&&e.value>=0,"zero or greater"),lc("isZero",e=>fc(e)&&0===e.value,"exactly 0"),lc("isOne",e=>fc(e)&&1===e.value,"exactly 1"),lc("isNonZero",e=>fc(e)&&0!==e.value,"a number that is provably not 0"),lc("isNotZeroLiteral",e=>!(fc(e)&&0===e.value),"anything except a literal 0"),lc("isPositiveInteger",e=>fc(e)&&Number.isInteger(e.value)&&e.value>0,"a whole number above 0"),lc("isNegativeInteger",e=>fc(e)&&Number.isInteger(e.value)&&e.value<0,"a whole number below 0"),lc("isEven",e=>fc(e)&&Number.isInteger(e.value)&&e.value%2==0,"a whole even number"),lc("isOdd",e=>fc(e)&&Number.isInteger(e.value)&&1===Math.abs(e.value%2),"a whole odd number"),lc("greaterThan",(e,t)=>fc(e)&&e.value>Number(t),"above a given value"),lc("lessThan",(e,t)=>fc(e)&&e.value<Number(t),"below a given value"),lc("isValue",(e,t)=>fc(e)&&e.value===Number(t),"equals a given number"),lc("isNumeric",Wl,"contains no symbols: a constant (it need not fold to a number: 1 sin)"),lc("hasSymbol",e=>!Wl(e),"mentions a symbol somewhere, so it is not just a number"),lc("isVar",(e,t)=>e.type===Al&&e.token===String(t),"is exactly this symbol"),lc("contains",(e,t)=>Pl(e).includes(String(t)),"mentions this operand somewhere"),lc("isFree",(e,t)=>!Pl(e).includes(String(t)),"never mentions this operand"),lc("hasOperation",(e,t)=>pc(e,String(t)),"uses this operation somewhere inside"),lc("equals",(e,t)=>e.s===String(t),"is exactly this postfix expression");const mc=e=>e.type===Sl?null:e.token;function dc(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 ac(`bad requirement: ${JSON.stringify(e)}`)}uc("freeOf",(e,t)=>{const n=mc(t);return null!==n&&!Pl(e).includes(n)},"the first operand never mentions the second"),uc("dependsOn",(e,t)=>{const n=mc(t);return null!==n&&Pl(e).includes(n)},"the first operand does mention the second"),uc("sameAs",(...e)=>e.every(t=>t.s===e[0].s),"these operands are structurally identical"),uc("differs",(...e)=>new Set(e.map(e=>e.s)).size===e.length,"these operands are all different"),uc("sameValue",(...e)=>e.every(e=>fc(e))&&e.every(t=>t.value===e[0].value),"these operands are the same number");const gc="simplify";class vc extends Error{constructor(e,t){super(t?`rule "${t}": ${e}`:e),this.name="RuleError",this.ruleId=t}}const bc=/^[A-Za-z_][A-Za-z0-9_]*$/;function yc(e,t){if(Cl(e))return{literal:e.value};const n=e.token;if(n.startsWith("=")){const e=n.slice(1);if(""===e)throw new vc('"=" needs an operand after it',t);return{token:e}}if(!bc.test(n))throw new vc(`"${n}" is not a usable slot name; use letters, digits and _`,t);if($l(n))throw new vc(`slot name "${n}" collides with an operator`,t);return{name:n}}function wc(e){if(!Zl(e))return[e];const t=e.args.map(wc),n=xl(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(Tl(e.op,s)),n.commutative&&2===s.length&&s[0].s!==s[1].s&&r.push(Tl(e.op,[s[1],s[0]])),r.length>=64)break;return r}function xc(e,t=[]){return"op"===e.kind?e.args.forEach(e=>xc(e,t)):"const"===e.kind&&e.free&&t.push(e.node.token),t}function $c(e){if(!e||"object"!=typeof e)throw new vc("rule must be a mapping");const t=e.id||e.name;if(!t)throw new vc("rule needs an id");if(!e.pattern)throw new vc("rule needs a pattern",t);if(void 0===e.output||null===e.output)throw new vc("rule needs an output",t);let n;try{n=Fl(String(e.pattern))}catch(e){if(e instanceof Ol)throw new vc(`bad pattern: ${e.message}`,t);throw e}const r=sc(n).map(e=>yc(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 vc('"when" must map slot names to lists of requirements',n);for(const[e,i]of Object.entries(s)){if(!t.has(e))throw new vc(`"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}=dc(t),o=cc(s);if(!o)throw new vc(`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 vc('"require" must be a list of relations',n);for(const e of s){const{name:s,args:i}=dc(e),o=hc(s);if(!o)throw new vc(`unknown relation "${s}"`,n);if(i.length<2)throw new vc(`relation "${s}" needs at least two operands`,n);for(const e of i)if("string"==typeof e&&!t.has(e)&&bc.test(e))throw new vc(`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=Fl(e)}catch(t){throw new vc(`bad output "${e}": ${t.message}`,n)}const s=e=>Zl(e)?{kind:"op",op:e.op,args:e.args.map(s)}:Cl(e)?{kind:"const",node:e}:t.has(e.token)?{kind:"slot",name:e.token}:e.token.startsWith("=")?{kind:"const",node:Il(e.token.slice(1))}:{kind:"const",node:e,free:!0};return s(r)}(String(e.output),s,t),l=e.commutative?wc(n):[n],u=[],c=new Set;for(const e of l){const n=rc(e),r=sc(e).map(e=>yc(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):gc,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:Rl(n),bindings:u,freeSymbols:xc(a),source:e};for(const e of u)e.rule=h;return h}function kc(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!==gc&&(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 qc extends Error{constructor(e,t){super(null==t?e:`${e} (line ${t+1})`),this.name="YamlError",this.line=t}}class Mc{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 Ac=e=>"-"===e||e.startsWith("- ");function Sc(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:Nc(t),rest:e.slice(r+1).trim()}}}return null}function Nc(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 Oc(e){const t=new Mc(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=Ic(t,n.indent),s=t.peek();if(s&&"..."!==s.text&&"---"!==s.text)throw new qc(`unexpected content "${s.text}"`,s.n);return r}const Ec=/^[|>][-+]?\d*$/;function Ic(e,t){const n=e.peek();return!n||n.indent<t?null:Ac(n.text)?zc(e,n.indent):Sc(n.text)?function(e,t){const n={};for(;;){const r=e.peek();if(!r||r.indent!==t)break;const s=Sc(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]=Ic(e,r.indent):r&&r.indent===t&&Ac(r.text)?n[i]=zc(e,t):n[i]=null}else Ec.test(o)?n[i]=_c(e,o,t):n[i]=jc(o,r.n)}return n}(e,n.indent):(e.next(),Ec.test(n.text)?_c(e,n.text,n.indent-1):jc(n.text,n.n))}function zc(e,t){const n=[];for(;;){const r=e.peek();if(!r||r.indent!==t||!Ac(r.text))break;if(e.next(),"-"===r.text){const r=e.peek();n.push(r&&r.indent>t?Ic(e,r.indent):null);continue}if(Ec.test(r.text.slice(2).trim())){n.push(_c(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(Ic(e,i))}return n}function _c(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 jc(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=Cc(n);if(Tc(n),n.i<n.text.length)throw new qc(`unexpected "${n.text.slice(n.i)}" in flow value`,t);return r}(n,t):'"'===n[0]||"'"===n[0]?Nc(n):/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(n)?Number(n):n)}const Tc=e=>{for(;e.i<e.text.length&&/\s/.test(e.text[e.i]);)e.i++};function Cc(e){Tc(e);const t=e.text[e.i];return"["===t?function(e){e.i++;const t=[];for(;;){if(Tc(e),e.i>=e.text.length)throw new qc("unterminated [",e.line);if("]"===e.text[e.i])return e.i++,t;if(t.push(Cc(e)),Tc(e),","===e.text[e.i])e.i++;else if("]"!==e.text[e.i])throw new qc(`expected , or ] near "${e.text.slice(e.i)}"`,e.line)}}(e):"{"===t?function(e){e.i++;const t={};for(;;){if(Tc(e),e.i>=e.text.length)throw new qc("unterminated {",e.line);if("}"===e.text[e.i])return e.i++,t;const n=String(Cc(e));if(Tc(e),":"!==e.text[e.i])throw new qc(`expected : after "${n}"`,e.line);if(e.i++,t[n]=Cc(e),Tc(e),","===e.text[e.i])e.i++;else if("}"!==e.text[e.i])throw new qc(`expected , or } near "${e.text.slice(e.i)}"`,e.line)}}(e):jc(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 qc("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 Zc=/^(true|false|null|yes|no|on|off|~)$/i;function Fc(e){if(null==e)return"null";if("boolean"==typeof e)return e?"true":"false";if("number"==typeof e){if(!Number.isFinite(e))throw new qc(`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)||Zc.test(e)||/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(e))}(t)?JSON.stringify(t):t}const Lc=e=>null==e||"object"!=typeof e;function Rc(e){return Array.isArray(e)?`[${e.map(Rc).join(", ")}]`:e&&"object"==typeof e?`{${Object.entries(e).map(([e,t])=>`${Fc(e)}: ${Rc(t)}`).join(", ")}}`:Fc(e)}function Bc(e){return Array.isArray(e)?!!e.every(e=>Lc(e)||Array.isArray(e)&&e.every(Lc))&&Rc(e).length<=72:!(!e||"object"!=typeof e)&&(Object.values(e).every(e=>Lc(e)||Array.isArray(e)&&e.every(Lc))&&Rc(e).length<=72)}function Pc(e){const t=[];return Wc(e,0,t),t.length?t.join("\n")+"\n":""}function Wc(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)Dc(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)Uc(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+Fc(e))}(e,r,n)}}function Dc(e,t,n){const r=" ".repeat(t);if(null!==e&&"object"==typeof e&&!Bc(e)){const s=[];if(Wc(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+"- "+Fc(e));else n.push(r+"- "+Rc(e))}function Uc(e,t,n,r){const s=" ".repeat(n),i=Fc(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 Bc(t)?void r.push(`${s}${i}: ${Rc(t)}`):(r.push(`${s}${i}:`),void Wc(t,Array.isArray(t)?n:n+2,r));r.push(`${s}${i}: ${Fc(t)}`)}}class Vc{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:$c(e);if(this.rules.some(e=>e.id===t.id))throw new vc(`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 Vc(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===gc?-1:t===gc?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=Oc(e);return Vc.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 vc('expected a list of rules, or a mapping with a "rules" list');const s=new Vc;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 vc(`${i.length} rule(s) failed to compile:\n ${i.join("\n ")}`);return s.errors=i,s}toSpecs(){return this.rules.map(kc)}toYaml(){const e=this.toSpecs();return this.name?Pc({name:this.name,rules:e}):Pc(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 Hc(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(!Cl(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 Gc(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 Qc(e,t){return t.rule.priority-e.rule.priority||t.rule.depth-e.rule.depth}function Xc(e,t){const n=[];if(0===t.maxDepth)return n;for(const{key:r,slots:s}of function(e,t){const n=nc(e,t),r=[];for(const e of n)e.key!==Ku&&r.push(e);return r}(e,t.maxDepth)){const e=t.candidates(r);if(e)for(const t of e){const e=Hc(t,s);e&&(Gc(t.rule,e)&&n.push({rule:t.rule,binding:t,key:r,bound:e}))}}return n.sort(Qc)}function Jc(e,t,{order:n="post"}={}){const r=[];for(const{node:s,path:i}of Dl(e,n))for(const e of Xc(s,t))r.push({...e,node:s,path:i});return r}function Yc(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 Tl(e.op,e.args.map(e=>Yc(e,t)));default:throw new Error(`bad output template: ${JSON.stringify(e)}`)}}function Kc(e){if(!Zl(e))return e;const t=e.args.map(Kc),n=t.some((t,n)=>t!==e.args[n])?Tl(e.op,t):e,r=xl(n.op);if(!r||!r.fold||!n.args.every(Cl))return n;if(th.has(n.op)){const e=function(e,t){const[n,r]=t.map(rh);if(!n||t.length>1&&!r)return;let s;switch(e){case"neg":s={n:-n.n,scale:n.scale};break;case"+":{const[e,t,i]=sh(n,r);s={n:e+t,scale:i};break}case"-":{const[e,t,i]=sh(n,r);s={n:e-t,scale:i};break}case"*":s={n:n.n*r.n,scale:n.scale+r.scale};break;case"^":{if(0!==r.scale||r.n>64n||r.n<-64n)return null;const e=r.n<0n?-r.n:r.n;if((n.n<0n?-n.n:n.n).toString().length*Number(e)>nh)return null;const t={n:n.n**e,scale:n.scale*Number(e)};if(s=r.n<0n?function({n:e,scale:t}){if(0n===e)return null;let n=e<0n?-e:e,r=0,s=0;for(;n%2n==0n;)n/=2n,r++;for(;n%5n==0n;)n/=5n,s++;if(1n!==n)return null;const i=Math.max(r,s),o=10n**BigInt(t)*2n**BigInt(i-r)*5n**BigInt(i-s);return{n:e<0n?-o:o,scale:i}}(t):t,!s)return null;break}default:return}const i=function({n:e,scale:t}){const n=e<0n;let r=(n?-e:e).toString();t>0&&(r=r.padStart(t+1,"0"),r=`${r.slice(0,-t)}.${r.slice(-t)}`.replace(/\.?0+$/,""));return"0"===r?"0":(n?"-":"")+r}(s);return i.length>nh?null:i}(n.op,n.args.map(e=>e.token));if(void 0!==e)return null===e?n:zl(e)}const s=r.fold(...n.args.map(e=>e.value));return null!=s&&Number.isFinite(s)?El(s):n}function eh(e,t){const n=function(e){const t=Yc(e.rule.outputTemplate,e.bound);return e.rule.fold?Kc(t):t}(t);return{expr:Vl(e,t.path,n),before:t.node,after:n,rule:t.rule,path:t.path,explanation:(r=t.rule,s=t.bound,i=n,r.explain?r.explain.replace(/\{(\w+)\}/g,(e,t)=>{if("result"===t)return i?i.s:e;const n=s[t];return n?n.s:e}):"")};var r,s,i}const th=new Set(["+","-","*","neg","^"]),nh=2e3;function rh(e){const t=/^(-?)(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/i.exec(e);if(!t)return;const n=t[3]??"";let r=BigInt(t[2]+n),s=n.length-Number(t[4]??0);return s<0&&(r*=10n**BigInt(-s),s=0),{n:t[1]?-r:r,scale:s}}const sh=(e,t)=>{const n=Math.max(e.scale,t.scale);return[e.n*10n**BigInt(n-e.scale),t.n*10n**BigInt(n-t.scale),n]};const ih=4e5,oh=()=>new Hl("a number too large to approximate"),ah=e=>e<0n?-e:e;class lh{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 Hl("division by zero");return e*this.S/t}sqrt(e){if(e<0n)throw new Hl("the square root of a negative number is not real");return eu(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 Hl("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(ih))throw oh();if(t<-BigInt(ih))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 Hl("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(ah(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(ah(e)>this.S)throw new Hl("arcsin of a number beyond ±1 is not real");return ah(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 uh(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 Hl("the argument of 0 is undefined");return t>0n?e.pi/2n:-e.pi/2n}const ch={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 Hl("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=ch.abs(e,t);if(0n===n)throw new Hl("the log of 0 is undefined");return[e.ln(n),uh(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=ch.mul(e,s,i)),i=ch.mul(e,i,i),n>>=1n;return r.n<0n?ch.div(e,[e.S,0n],s):s}return ch.exp(e,ch.mul(e,n,ch.ln(e,t)))},sinh:(e,t)=>(e.exp(t)-e.exp(-t))/2n,cosh:(e,t)=>(e.exp(t)+e.exp(-t))/2n},hh={sin:(e,[t,n])=>[e.mul(e.sin(t),ch.cosh(e,n)),e.mul(e.cos(t),ch.sinh(e,n))],cos:(e,[t,n])=>[e.mul(e.cos(t),ch.cosh(e,n)),-e.mul(e.sin(t),ch.sinh(e,n))],tan:(e,t)=>ch.div(e,hh.sin(e,t),hh.cos(e,t)),ln:(e,t)=>ch.ln(e,t),sqrt:(e,t)=>ch.exp(e,ch.mul(e,[e.S/2n,0n],ch.ln(e,t))),sinh:(e,[t,n])=>[e.mul(ch.sinh(e,t),e.cos(n)),e.mul(ch.cosh(e,t),e.sin(n))],cosh:(e,[t,n])=>[e.mul(ch.cosh(e,t),e.cos(n)),e.mul(ch.sinh(e,t),e.sin(n))]},fh=e=>({q:e}),ph=([e,t])=>0n===t?{f:e}:{z:[e,t]};function mh(e,t,n){const r=e=>((e,t)=>t.z??[dh(e,t),0n])(n,t[e]);switch(e.op){case"+":return ph(ch.add(r(0),r(1)));case"-":return ph(ch.sub(r(0),r(1)));case"neg":return ph([-r(0)[0],-r(0)[1]]);case"*":return ph(ch.mul(n,r(0),r(1)));case"/":return ph(ch.div(n,r(0),r(1)));case"^":return ph(ch.pow(n,r(0),r(1),t[1].q));case"sqrt":return ph(hh.sqrt(n,r(0)));case"root":return ph(ch.pow(n,r(1),ch.div(n,[n.S,0n],r(0)),t[0].q?.inv()));case"abs":return{f:ch.abs(n,r(0))};case"arg":return{f:uh(n,r(0)[1],r(0)[0])};case"re":return{f:r(0)[0]};case"im":return{f:r(0)[1]};case"conj":return ph([r(0)[0],-r(0)[1]]);case"log":return ph(ch.div(n,ch.ln(n,r(1)),ch.ln(n,r(0))));default:{const s=hh[e.op];if(!s||1!==t.length)throw new Hl(`no complex value for ${e.op}`);return ph(s(n,r(0)))}}}function dh(e,t){return t.q?e.fromQ(t.q):t.f}const gh={sin:(e,t)=>e.sin(t),cos:(e,t)=>e.cos(t),tan:(e,t)=>e.div(e.sin(t),e.cos(t)),sec:(e,t)=>e.div(e.S,e.cos(t)),csc:(e,t)=>e.div(e.S,e.sin(t)),cot:(e,t)=>e.div(e.cos(t),e.sin(t)),arcsin:(e,t)=>e.asin(t),arccos:(e,t)=>e.pi/2n-e.asin(t),arctan:(e,t)=>e.atan(t),arcsec:(e,t)=>{if(ah(t)<e.S)throw new Hl("arcsec of a number between -1 and 1 is not real");return e.pi/2n-e.asin(e.div(e.S,t))},arccsc:(e,t)=>{if(ah(t)<e.S)throw new Hl("arccsc of a number between -1 and 1 is not real");return e.asin(e.div(e.S,t))},arccot:(e,t)=>e.pi/2n-e.atan(t),sinh:(e,t)=>(e.exp(t)-e.exp(-t))/2n,cosh:(e,t)=>(e.exp(t)+e.exp(-t))/2n,tanh:(e,t)=>{const n=e.exp(t),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 Hl("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(ah(t)>=e.S)throw new Hl("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 vh(e,t,n){if("num"===e.type)return fh(Kl(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&&su.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?Kl(String(t)):null;if(!r)throw new Hl(`the value of ${e.token} is not a number`);return fh(r)}throw new Hl(`${e.token} has no value`)}su.complex&&e.op.startsWith("\\:")&&Tu[e.op.slice(2)]&&(e=Tl(Tu[e.op.slice(2)],e.args));const r=e.args.map(e=>vh(e,t,n));if(r.some(e=>e.z)||["re","im","conj","arg"].includes(e.op)||function(e,t){if(!su.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 mh(e,r,t);const s=r.every(e=>e.q),i=e=>dh(t,r[e]);switch(e.op){case"+":return s?fh(r[0].q.add(r[1].q)):{f:i(0)+i(1)};case"-":return s?fh(r[0].q.sub(r[1].q)):{f:i(0)-i(1)};case"neg":return r[0].q?fh(r[0].q.neg()):{f:-r[0].f};case"*":return s?fh(r[0].q.mul(r[1].q)):{f:t.mul(i(0),i(1))};case"/":return s?fh(r[0].q.div(r[1].q)):{f:t.div(i(0),i(1))};case"^":return yh(t,r[0],r[1]);case"sqrt":return yh(t,r[0],fh(Yl.HALF));case"root":return yh(t,r[1],r[0].q?fh(r[0].q.inv()):{f:t.div(t.S,r[0].f)});case"abs":return r[0].q?fh(r[0].q.abs()):{f:ah(r[0].f)};case"floor":return fh(r[0].q?r[0].q.floor():new Yl(bh(r[0].f,t.S)));case"ceil":return fh(r[0].q?r[0].q.ceil():new Yl(-bh(-r[0].f,t.S)));case"log":return{f:t.div(t.ln(i(1)),t.ln(i(0)))};case"atan2":return{f:uh(t,i(0),i(1))};case"max":case"min":if(!r.length)throw new Hl(`${e.op} of nothing`);return s?fh(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?fh(r.reduce((e,t)=>e.add(t.q),Yl.ZERO)):{f:r.reduce((e,t,n)=>e+i(n),0n)};case"prod":return s?fh(r.reduce((e,t)=>e.mul(t.q),Yl.ONE)):{f:r.reduce((e,n,r)=>t.mul(e,i(r)),t.S)};case"mean":if(!r.length)throw new Hl("mean of nothing");return s?fh(r.reduce((e,t)=>e.add(t.q),Yl.ZERO).div(new Yl(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 Hl("mod 0 is undefined");return fh(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 Hl("mod 0 is undefined");return{f:i(0)-t.mul(e,bh(t.div(i(0),e),t.S)*t.S)}}case"round":{if(!r[1].q?.isInteger)throw new Hl("round needs a whole number of places");const e=10n**ah(r[1].q.n),n=r[0].q??new Yl(i(0),t.S),s=r[1].q.sign>=0,o=(s?n.mul(new Yl(e)):n.div(new Yl(e))).add(Yl.HALF).floor();return fh(s?o.div(new Yl(e)):o.mul(new Yl(e)))}case"!":{if(!r[0].q?.isInteger||r[0].q.sign<0)throw new Hl("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)&&Xl(e)>ih)throw oh();return fh(new Yl(e))}default:{const n=gh[e.op];if(!n||1!==r.length)throw new Hl(`no numeric value for ${e.op}`);return{f:n(t,i(0))}}}}const bh=(e,t)=>{const n=e/t;return e<0n&&n*t!==e?n-1n:n};function yh(e,t,n){if(n.q&&n.q.isInteger){if(t.q)return fh(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),Xl(i)>ih+4*e.P||Xl(o)>8e5){if(s)return{f:0n};throw oh()}r>>=1n}return{f:s?e.div(e.S,i):i}}const r=dh(e,t);if(0n===r){if(n.q?n.q.sign>0:n.f>0n)return fh(Yl.ZERO);throw new Hl("0 to a power that is not positive is undefined")}if(r<0n){if(n.q&&n.q.d%2n==1n){const t=yh(e,{f:-r},n).f;return{f:n.q.n%2n==0n?t:-t}}throw new Hl("a negative number to a fractional power is not real")}if(n.q&&1n===ah(n.q.n)&&n.q.d<=64n){const t=eu(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(dh(e,n),e.ln(r)))}}function wh(e,t,n){const r=e<0n?"-":"",s=ah(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 xh({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 $h(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=ah(e.n)*10n**s/e.d;if(0n===i)return 1;for(;i%10n==0n;)i/=10n;return i.toString().length}function kh(e){let t=e.d;for(;t%2n==0n;)t/=2n;for(;t%5n==0n;)t/=5n;return 1n===t}function qh(e){const t=/^(-?[\d.]+)e(-?\d+)$/.exec(e);return t?Tl("*",[zl(t[1]),Tl("^",[zl("10"),zl(t[2])])]):zl(e)}function Mh(e,{digits:t=15,scope:n}={}){if(!Number.isInteger(t)||t<1||t>1e5)throw new Hl("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 lh(r),a=vh(e,o,n);if(a.z){const e=Sh(a.z,o,t);if(e.retry&&i<3){r+=e.retry;continue}return void 0===e.real?e:Ah(e.real,o,t,null)}if(a.q&&a.q.isInteger&&ah(a.q.n).toString().length<=t)return{text:a.q.n.toString(),node:zl(a.q.n.toString()),number:Number(a.q.n),re:Number(a.q.n),im:0,exact:!0};const l=dh(o,a);if(0n===l&&(!a.q||!a.q.isZero)&&i<3){s=null,r*=4;continue}const u=wh(l,o,t);if(s&&u.point<-10&&s.point-u.point>=(r-s.P)/2)return{text:"0",node:zl("0"),number:0,re:0,im:0,exact:!1};if(!(u.point<-10&&i<3)||s&&s.point===u.point)return Ah(l,o,t,a.q);s={point:u.point,P:r},r+=10-u.point}throw new Hl("could not approximate")}function Ah(e,t,n,r){const s=xh(wh(e,t,n));return{text:s,node:qh(s),number:Number(s),re:Number(s),im:0,exact:Boolean(r)&&kh(r)&&$h(r)<=n}}function Sh([e,t],n,r){const s=10n**BigInt(Math.max(0,n.P-r-12)),i=e=>ah(e)>s;if(!i(t))return{real:e};const o=wh(t,n,r);if(o.point<-10&&i(t))return{retry:10-o.point};const a=xh(o),l="1"===a?"i":"-1"===a?"-i":`${a}i`,u="1"===a?Il("i"):Tl("*",[qh(a.replace(/^-/,"")),Il("i")]);if(!i(e))return{text:l,node:a.startsWith("-")?Tl("neg",[u]):u,number:NaN,re:0,im:Number(a),exact:!1};const c=xh(wh(e,n,r)),h=a.startsWith("-"),f="1"===a.replace(/^-/,"")?Il("i"):Tl("*",[qh(a.replace(/^-/,"")),Il("i")]);return{text:`${c} ${h?"-":"+"} ${l.replace(/^-/,"")}`,node:Tl(h?"-":"+",[qh(c),f]),number:NaN,re:Number(c),im:Number(a),exact:!1}}function Nh(e,t={}){const n=e=>(e=>0===Xu(e).size)(e)?"num"===e.type&&/^-?\d+$/.test(e.token)?e:Mh(e,t).node:Zl(e)?Tl(e.op,e.args.map(n)):e;return n(e)}const Oh={variable:null},Eh=(e,t)=>null!==t&&Xu(e).has(t);function Ih(e){if("num"===e.type)return Kl(e.token);if(Zl(e)&&"/"===e.op&&e.args.every(e=>"num"===e.type)){const t=Kl(e.args[0].token),n=Kl(e.args[1].token);return t&&n&&!n.isZero?t.div(n):null}return null}const zh=e=>0===Xu(e).size;function _h(e,t,n){const r=function(e){const t=Pu(e);return"num"===t.k?t.q.isZero?t.q:null:"atom"===t.k&&"sym"===t.node.type&&"pi"===t.node.token?Kl("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(Kl(s).div(Kl(i))))}function jh(e){if(!zh(e))return NaN;try{const{number:t}=Mh(e,{digits:30});return Math.sign(t)}catch{return NaN}}function Th(){cc("hasVariable")||(lc("hasVariable",e=>Eh(e,Oh.variable),"mentions the variable being solved for"),lc("freeOfVariable",e=>null!==Oh.variable&&!Eh(e,Oh.variable),"does not mention the variable being solved for"),lc("isRational",e=>null!==Ih(e),"an exact number: 3, -2, 1/2"),lc("isWhole",e=>Ih(e)?.isInteger??!1,"a whole number (any size)"),lc("isEvenWhole",e=>{const t=Ih(e);return Boolean(t?.isInteger&&t.n%2n==0n)},"an even whole number"),lc("isOddWhole",e=>{const t=Ih(e);return Boolean(t?.isInteger&&t.n%2n!=0n)},"an odd whole number"),lc("isPositiveRational",e=>(Ih(e)?.sign??0)>0,"an exact number above 0"),lc("isNegativeRational",e=>(Ih(e)?.sign??0)<0,"an exact number below 0"),lc("isConstant",zh,"has no unknowns (numbers, π and e only)"),lc("notOne",e=>{const t=Ih(e);return!t||!t.isOne},"anything except the number 1"),lc("notMinusOne",e=>{const t=Ih(e);return!t||!t.equals(Kl("-1"))},"anything except the number -1"),lc("hasMinusSign",e=>function(e){const t=Pu(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"),lc("piMultipleAtLeast",(e,t)=>_h(e,t,e=>e>=0),"a multiple of π, at least k·π"),lc("piMultipleAbove",(e,t)=>_h(e,t,e=>e>0),"a multiple of π, above k·π"),lc("piMultipleBelow",(e,t)=>_h(e,t,e=>e<0),"a multiple of π, below k·π"),lc("piMultipleAtMost",(e,t)=>_h(e,t,e=>e<=0),"a multiple of π, at most k·π"),lc("isPositiveConstant",e=>jh(e)>0,"no unknowns, and above 0 (e, π, √2, 3)"),lc("isNegativeConstant",e=>jh(e)<0,"no unknowns, and below 0"),lc("hasImaginaryPart",e=>{if(!su.complex)return!1;const t=zu(Pu(e));return Boolean(t)&&!("num"===t.im.k&&t.im.q.isZero)},"complex mode: has a nonzero imaginary part (unknowns count as real)"),lc("isSymbolNode",e=>"sym"===e.type&&!ru.has(e.token),"a single unknown such as x"))}function Ch(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=Fl(e),n=e=>"num"===e.type||("sym"===e.type?e.token.startsWith("="):e.args.every(n)),r=e=>"sym"===e.type?Il(e.token.slice(1)):"num"===e.type?e:Tl(e.op,e.args.map(r)),s=e=>"sym"===e.type?Il(`=${e.token}`):"num"===e.type?e:Tl(e.op,e.args.map(s)),i=e=>"op"!==e.type?e:n(e)?s(Wu(r(e))):Tl(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 Vc.fromSpecs(n,{strict:!0})}function Zh(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 Fh=e=>Zl(e)&&("+"===e.op||"-"===e.op),Lh=e=>Zl(e)&&("*"===e.op||"/"===e.op);function*Rh(e,t,{order:n="pre"}={}){for(const r of Jc(e,t,{order:n})){const t=Yc(r.rule.outputTemplate,r.bound);yield{rule:r.rule,bound:r.bound,path:r.path,before:r.node,after:t,next:()=>Wu(Vl(e,r.path,t))}}for(const{node:r,path:s}of Dl(e,n)){const n=Fh(r);if(!n&&!Lh(r))continue;const i=n?Ju(Pu(r)):Yu(Pu(r));if(i.length<3)continue;const o=n?ku:Mu;for(let n=0;n<i.length;n++)for(let r=n+1;r<i.length;r++){const a=Hu(o([i[n],i[r]]));for(const l of Xc(a,t)){const t=Yc(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:()=>Wu(Vl(e,s,Hu(o([Pu(t),...u]))))}}}}}function Bh(e,t,{format:n,order:r="pre",maxSteps:s=200,variable:i=null}={}){const o=Oh.variable;Oh.variable=i;try{let i=Wu(e);const o=new Set([i.s]),a=[];for(let e=0;e<s;e++){let e=null;for(const n of Rh(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:Zh(s.rule,s.bound,Wu(s.after),n)}),i=l,o.add(i.s)}return{node:i,steps:a}}finally{Oh.variable=o}}const Ph=(e,t)=>e.length>=t.length&&t.every((t,n)=>e[n]===t),Wh=(e,t)=>{for(const n of e)if(t(n))return n;return null};function Dh(e,t,{diff:n}){let r=null;for(;;){const s=Wh(Jc(e,n,{order:"pre"}),e=>"d-variable"===e.rule.id&&e.path.length>t.length&&Ph(e.path,t));if(!s)break;r=Ul(e,s.path).args[1],e=eh(e,s).expr}const s=t.length?t.slice(0,-1):t,i=Gh(Ul(e,s));return i.s!==Ul(e,s).s&&(e=s.length?Vl(e,s,i):i),{expr:e,variable:r}}function Uh(e){if(!Zl(e))return e;const t=e.args.map(Uh),n=e.op.startsWith("\\:")?e.op.slice(2):null;return n&&$l(n)&&xl(n).arity===t.length?Tl(n,t):t.every((t,n)=>t===e.args[n])?e:Tl(e.op,t)}const Vh=e=>"op"!==e.type&&"1"===e.s,Hh=e=>"op"!==e.type&&"0"===e.s;function Gh(e){if(!Zl(e))return e;const t=e.args.map(Gh),[n,r]=t;if("*"===e.op&&2===t.length){if(Vh(r))return n;if(Vh(n))return r}if("^"===e.op&&2===t.length&&Vh(r))return n;if("+"===e.op&&2===t.length){if(Hh(r))return n;if(Hh(n))return r}return"-"===e.op&&2===t.length&&Hh(r)?n:t.every((t,n)=>t===e.args[n])?e:Tl(e.op,t)}function Qh(e,t,{fold:n=null,format:r,maxSteps:s=200,order:i="pre"}={}){let o=e;const a=new Set([o.s]),l=[];for(let e=0;e<s;e++){let e=null;for(const r of Jc(o,t,{order:i})){const t=eh(o,r);let s=t.expr,i=null;if(n&&({expr:s,variable:i}=Dh(s,r.path,n)),s.s!==o.s&&!a.has(s.s)){e={m:r,a:t,expr:s,variable:i};break}}if(!e)break;const{m:s,a:u,expr:c,variable:h}=e;let f=s.path;for(;;)try{Ul(c,f);break}catch{f=f.slice(0,-1)}const p=Ul(c,f);let m=Zh(s.rule,s.bound,Wu(p),r);h&&m&&!m.endsWith("is 1.")&&(m=m.endsWith(`the derivative of ${r(h)}.`)?`${m.slice(0,-1)}, which is 1.`:`${m} The derivative of ${r(h)} is 1.`),l.push({id:s.rule.id,name:s.rule.name,tags:s.rule.tags,from:o.s,to:c.s,path:f,before:u.before.s,after:p.s,explanation:m}),o=c,a.add(o.s)}return{node:o,steps:l}}const Xh=new Set(["int","der","lim"]),Jh=e=>Zl(e)&&("+"===e.op||"-"===e.op),Yh=e=>Zl(e)&&"*"===e.op;function Kh(e,t=1,n=[]){return Zl(e)&&"+"===e.op?(Kh(e.args[0],t,n),Kh(e.args[1],t,n),n):Zl(e)&&"-"===e.op&&2===e.args.length?(Kh(e.args[0],t,n),Kh(e.args[1],-t,n),n):Zl(e)&&"neg"===e.op?(Kh(e.args[0],-t,n),n):(n.push({sign:t,node:e}),n)}const ef=(e,t=[])=>Yh(e)?(ef(e.args[0],t),ef(e.args[1],t),t):(t.push(e),t),tf=e=>e.reduce((e,t)=>null===e?t.sign<0?Tl("neg",[t.node]):t.node:Tl(t.sign<0?"-":"+",[e,t.node]),null),nf=e=>{try{return du(Pu(e))}catch{return e.s}},rf=e=>nf(e.sign<0?Tl("neg",[e.node]):e.node);function sf(e,t,n,r=n){const s=e.map((e,t)=>({x:e,i:t,k:n(e)})),i=[];let o=null;for(const e of t){const t=s.findIndex(t=>t.k===r(e));t>=0?(i.push({x:s[t].x,from:e}),s.splice(t,1)):null===o&&(o=i.length,i.push(null))}const a=s.map(e=>({x:e.x,from:null}));return null===o?[...i,...a]:[...i.slice(0,o),...a,...i.slice(o+1)]}function of(e,t,{tidy:n=!1}={}){if(!t||e.s===t.s)return t&&e.s===t.s?t:e;if(Jh(e)&&Jh(t)){const r=sf(Kh(e),Kh(t),rf),s=Kh(t).filter(e=>!r.some(t=>t.from===e));return tf(r.map(({x:e,from:t})=>({sign:e.sign,node:of(e.node,(t??(1===s.length?s[0]:null))?.node,{tidy:n})})))}if(Jh(e)&&Zl(t)&&Xh.has(t.op)&&Jh(t.args[0])){const n=e=>Zl(e.node)&&e.node.op===t.op?rf({sign:e.sign,node:e.node.args[0]}):rf(e),r=sf(Kh(e),Kh(t.args[0]),n,rf);return tf(r.map(({x:e})=>e))}if(Yh(e)&&Yh(t)){if(n)return e;const r=sf(ef(e),ef(t),nf);return r.map(({x:e,from:t})=>of(e,t)).reduce((e,t)=>null===e?t:Tl("*",[e,t]),null)}if(Zl(e)&&Zl(t)&&e.op===t.op&&e.args.length===t.args.length){const r=e.args.map((e,r)=>of(e,t.args[r],{tidy:n}));return r.every((t,n)=>t===e.args[n])?e:Tl(e.op,r)}return e}const af=new Set(["normal","normal.collect","normal.expand-collect","simplify.cancel","simplify.expand","cancel","expand","together"]),lf=e=>af.has(e.id)||(e.tags??[]).includes("tidy");function uf(e,t){if(!e.length)return e;let n=t??Fl(e[0].from);return e.map(e=>{let t,r=n??Fl(e.from);try{nf(Fl(e.from))!==nf(n)&&(r=Fl(e.from)),t=e.to===e.from?r:of(Fl(e.to),r,{tidy:lf(e)})}catch(t){if(t instanceof ReferenceError||t instanceof TypeError)throw t;return n=null,e}if(t.s===r.s&&e.to!==e.from&&lf(e))return null;n=t;let s=e.path;return e.before&&e.before!==e.from&&(s=function(e,t){const n=nf(Fl(t)),r=(e,s)=>{if(e.s===t||nf(e)===n)return s;if(!Zl(e))return null;for(let t=0;t<e.args.length;t++){const n=r(e.args[t],s.concat(t));if(n)return n}return null};return r(e,[])}(r,e.before)??null),{...e,from:r.s,to:t.s,path:s}}).filter(Boolean)}const cf={full:[],normal:["hidden","detail"],brief:["hidden","detail","minor","tidy","arithmetic","value"]},hf=(e,t)=>"all"===t||"*"===t||Array.isArray(t)&&t.some(t=>t===e.id||e.tags?.includes(t));function ff(e,t,{parse:n,replaceAt:r}){const s=(e,t,n=[])=>{if(e.s===t)return n;if("op"!==e.type)return null;for(let r=0;r<e.args.length;r++){const i=s(e.args[r],t,n.concat(r));if(i)return i}return null},i=(e,t)=>t.reduce((e,t)=>e.args[t],e);let o=t;const a=[];for(const t of e){let e=s(o,t.from);if(!e){try{o=n(t.from)}catch{a.push(t);continue}e=[]}const l=o;if("solve.reject"===t.id){const t=e.slice(0,-1);e.length&&"|"===i(o,t).op&&(o=r(o,t,i(o,t).args[1-e[e.length-1]]))}else if(t.to!==t.from){let s;try{s=n(t.to)}catch{a.push(t);continue}o=e.length?r(o,e,s):s}a.push({...t,from:l.s,to:o.s,path:e.length?[...e,...t.path??[]]:t.path})}return a}const pf=lu(Yl.ONE),mf=(e,t)=>"atom"===e.k&&"sym"===e.node.type&&e.node.token===t;function df(e){switch(e.k){case"num":default:return e;case"atom":return"op"===e.node.type?Ru(e.node.op,e.node.args.map(e=>df(Pu(e)))):e;case"add":return ku(Ju(e).map(df));case"mul":{let t=[lu(e.c)];for(const n of e.fs){const e=df(n.b);if("add"===e.k&&fu(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=gf(t,Ju(e));else t=gf(t,[Su(e,n.e)])}return ku(t)}}}function gf(e,t){const n=[];for(const r of e)for(const e of t)n.push(Mu([r,e]));return Ju(ku(n))}function vf(e,t){const n=new Map;for(const r of Ju(df(e))){const{coef:e,rest:s}=$u(r);let i=0;const o=[lu(e)];for(const e of s?Yu(s):[]){const{b:n,e:r}="mul"===e.k&&1===e.fs.length&&e.c.isOne?e.fs[0]:{b:e,e:pf};if(mf(n,t)){if(!fu(r)||!r.q.isInteger||r.q.sign<0)return null;i+=Number(r.q.n)}else{if(bf(n,t)||bf(r,t))return null;o.push(e)}}n.set(i,ku([n.get(i)??lu(Yl.ZERO),Mu(o)]))}for(const[e,t]of n)fu(t)&&t.q.isZero&&n.delete(e);return n}const bf=(e,t)=>Xu(Hu(e)).has(t);function yf(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)??lu(Yl.ZERO);if(!fu(t))return null;n.push(t.q)}return n}function wf(e,t){const n=Pu(Il(t));return ku(e.map((e,t)=>Mu([lu(e),Au(n,lu(Yl.of(t)))])))}const xf=e=>{const t=e.slice();for(;t.length>1&&t[t.length-1].isZero;)t.pop();return t},$f=(e,t)=>e.reduceRight((e,n)=>e.mul(t).add(n),Yl.ZERO);function kf(e,t){const n=e.length-1,r=new Array(n);let s=Yl.ZERO;for(let i=n;i>=1;i--)s=e[i].add(s.mul(t)),r[i-1]=s;return r}function qf(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 Mf(e){let t=xf(e);const n=[];for(;t.length>1&&t[0].isZero;)n.push(Yl.ZERO),t=t.slice(1);if(t.length<=1)return{roots:n,rest:t};const r=t.reduce((e,t)=>e*t.d/Jl(e,t.d),1n),s=t.map(e=>e.n*r/e.d),i=qf(s[0]),o=qf(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 Yl(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&&$f(t,e).isZero;)n.push(e),t=kf(t,e);return{roots:n.sort((e,t)=>e.compare(t)),rest:t}}function Af(e,t){const n=xf(t);let r=xf(e);const s=n[n.length-1];if(s.isZero)throw new Hl("division by the zero polynomial");const i=new Array(Math.max(1,r.length-n.length+1)).fill(Yl.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=xf(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:xf(i),r:r}}function Sf(e){if("num"===e.k)return{coef:e.q,factors:[],notes:[]};if("atom"===e.k)return{coef:Yl.ONE,factors:[{base:e,exp:pf}],notes:[]};if("mul"===e.k){let t=e.c;const n=[],r=[];for(const s of e.fs)if("add"===s.b.k&&fu(s.e)&&s.e.q.isInteger){const e=Sf(s.b);t=t.mul(e.coef.pow(s.e.q.n));for(const t of e.factors)n.push({base:t.base,exp:Mu([t.exp,s.e])});r.push(...e.notes)}else n.push({base:s.b,exp:s.e});return Nf(t,n,r)}return Ef(e)}function Nf(e,t,n){const r=new Map;for(const e of t){const t=du(e.base),n=r.get(t);n?n.exp=ku([n.exp,e.exp]):r.set(t,{...e})}return{coef:e,factors:[...r.values()].filter(e=>!(fu(e.exp)&&e.exp.q.isZero)),notes:n}}const Of=e=>$u(Ju(e)[0]).coef.sign;function Ef(e){const t=Ju(e),n=[],r=t.map(e=>{const{coef:t,rest:n}=$u(e);return{coef:t,fs:n?Yu(n).map(If):[]}}),s=r.reduce((e,t)=>({n:Jl(e.n,t.coef.n),d:e.d*t.coef.d/Jl(e.d,t.coef.d)}),{n:0n,d:1n});let i=new Yl(s.n||1n,s.d);Of(e)<0&&(i=i.neg());const o=[];for(const e of r[0].fs){if(!fu(e.e)){const t=du(e.b),n=du(e.e);r.slice(1).every(e=>e.fs.some(e=>du(e.b)===t&&du(e.e)===n))&&o.push({base:e.b,exp:e.e});continue}if(e.e.q.sign<=0)continue;let t=e.e.q;const n=du(e.b);let s=!0;for(const e of r.slice(1)){const r=e.fs.find(e=>du(e.b)===n&&fu(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:lu(t)})}let a=e;if(!i.isOne||o.length){const e=Mu([lu(i),...o.map(e=>Su(e.base,e.exp))]);a=ku(t.map(t=>Mu([t,Au(e,lu(Yl.MINUS_ONE))]))),n.push({id:"factor.common",values:{common:e}})}const l="add"===a.k&&du(a)!==du(e),u="add"!==a.k?Sf(a):l?Ef(a):function(e,t){const n=[...zf(e)];for(const r of n){const s=yf(vf(e,r));if(!s||s.length<3)continue;if(1!==n.length)break;const{roots:i,rest:o}=Mf(s);if(!i.length)break;const a=[];let l=o[o.length-1]??Yl.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=wf([new Yl(-e.n),new Yl(e.d)],r);a.push({base:n,exp:pf}),l=l.div(new Yl(e.d)),t.push({id:"factor.root",values:{root:lu(e),factor:n}})}if(u.length>1){const e=u.reduce((e,t)=>e*t.d/Jl(e,t.d),1n),t=u.map(t=>t.mul(new Yl(e))),n=t.reduce((e,t)=>Jl(e,t.n),0n)||1n;l=l.mul(new Yl(n,e)),a.push({base:wf(t.map(e=>e.div(new Yl(n))),r),exp:pf})}return Nf(l,a,[])}const r=Ju(e);if(2===r.length){const[e,n]=r;for(const r of[2,3]){const s=_f(e,r),i=_f(Cu(n),r),o=3===r?_f(n,r):null;if(s&&i&&2===r){t.push({id:"factor.squares",values:{a:s,b:i}});const e=Sf(ku([s,Cu(i)])),n=Sf(ku([s,i]));return Nf(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=ku(n<0?[s,Cu(e)]:[s,e]),a=ku([Au(s,lu(Yl.of(2))),n<0?Mu([s,e]):Cu(Mu([s,e])),Au(e,lu(Yl.of(2)))]),l=Sf(r);return Nf(l.coef,[...l.factors,{base:a,exp:pf}],l.notes)}}}return{coef:Yl.ONE,factors:[{base:e,exp:pf}],notes:[]}}(a,n);if(l&&n.length){const e=u.notes.findIndex(e=>"factor.common"===e.id);e>=0&&(n[0].values.common=Mu([n[0].values.common,u.notes.splice(e,1)[0].values.common]))}return Nf(i.mul(u.coef),[...o,...u.factors],[...n,...u.notes.filter(e=>!n.includes(e))])}const If=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length?{b:e.fs[0].b,e:e.fs[0].e}:{b:e,e:pf},zf=e=>Xu(Hu(e));function _f(e,t){const{coef:n,rest:r}=$u(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 Yl(r,s):null}(n,t);if(!s)return null;const i=[lu(s)];for(const e of r?Yu(r).map(If):[]){if(!fu(e.e))return null;const n=e.e.q.div(Yl.of(t));if(!n.isInteger)return null;i.push(Su(e.b,lu(n)))}return Mu(i)}function jf({coef:e,factors:t}){const n=[],r=[];for(const e of t){const t=fu(e.exp)&&e.exp.q.sign<0,s=t?lu(e.exp.q.neg()):e.exp,i=Hu(Su(e.base,s));(t?r:n).push(i)}const s=e=>e.reduce((e,t)=>e?Tl("*",[e,t]):t,null),i=e.n<0n?-e.n:e.n;let o=n.length?s(1n===i?n:[Hu(lu(new Yl(i))),...n]):Hu(lu(new Yl(i)));return e.n<0n&&(o=Tl("neg",[o])),1n!==e.d&&r.unshift(Hu(lu(new Yl(e.d)))),r.length?Tl("/",[o,s(r)]):o}function Tf(e){if("mul"!==e.k||!e.fs.some(e=>"add"===e.b.k&&fu(e.e)&&e.e.q.isInteger))return function(e){if("mul"!==e.k)return{num:e,den:pf};const t=[lu(new Yl(e.c.n))],n=[lu(new Yl(e.c.d))];for(const r of e.fs)fu(r.e)&&r.e.q.sign<0?n.push(Su(r.b,lu(r.e.q.neg()))):t.push(Su(r.b,r.e));return{num:Mu(t),den:Mu(n)}}(e);const t=[lu(new Yl(e.c.n))],n=[lu(new Yl(e.c.d))];for(const r of e.fs){const e=fu(r.e)&&r.e.q.sign<0,s=e?lu(r.e.q.neg()):r.e,i="add"===r.b.k&&fu(r.e)&&r.e.q.isInteger?Cf(r.b):null;!i||fu(i.den)&&i.den.q.isOne?(e?n:t).push(Su(r.b,s)):((e?n:t).push(Su(i.num,s)),(e?t:n).push(Su(i.den,s)))}return{num:Mu(t),den:Mu(n)}}function Cf(e){if("add"!==e.k)return Tf(e);const t=Ju(e).map(Tf),n=new Map;let r=1n;for(const e of t){const{coef:t,rest:s}=$u(e.den);r=r*t.n/Jl(r,t.n);for(const e of s?Yu(s).map(If):[]){const t=du(e.b),r=n.get(t);(!r||fu(e.e)&&fu(r.e)&&e.e.q.compare(r.e.q)>0)&&n.set(t,e)}}const s=Mu([lu(new Yl(r)),...[...n.values()].map(e=>Su(e.b,e.e))]);if(fu(s)&&s.q.isOne)return{num:e,den:pf};const i=df(ku(t.map(e=>Mu([e.num,s,Au(e.den,lu(Yl.MINUS_ONE))]))));return{num:i,den:s}}function Zf(e){const{num:t,den:n}=Cf(e);if(fu(n)&&n.q.isOne)return null;const r=Sf(n),s=e=>{const t=new Set(e.factors.map(e=>du(e.base))),n=r.factors.filter(e=>t.has(du(e.base))),s=[...e.factors,...r.factors.map(e=>({base:e.base,exp:Cu(e.exp)}))];return{...Nf(e.coef.div(r.coef),s,[...e.notes,...r.notes]),canceled:n.map(e=>e.base)}},i=s(Sf(t)),o="add"===t.k?df(t):t;if(du(o)===du(t))return i;const a=s(Sf(o));return Bl(jf(a))<Bl(jf(i))?a:i}const Ff=(e,t)=>Tl("=",[e,t]),Lf=Wu(Tl("+",[Il("x"),Tl("neg",[Il("x")])])),Rf=e=>Zl(e)&&"="===e.op;function Bf(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=Rf(t)?t:Ff(t,Lf),a=Ff(Wu(o.args[0]),Wu(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,Gf(e,a,n,r,i,l,u,0);const h=[],f=new Set,p=t=>Xu(t).size&&e.simplify?e.simplify(t,{steps:!1}).result:Bh(t,e.set.view("simplify"),{format:e.format}).node,m=new Map;for(const e of l){const t=c.has(e)?e:p(e),r=t.s;if(f.has(r))continue;f.add(r);const s=c.has(e)?null:Uf(o,n,t);s?i("solve.reject","Check the answer",["check"],Ff(Il(n),t),Ff(Il(n),t),{value:t,reason:s}):(l.periodOf?.has(e)&&m.set(t,l.periodOf.get(e)),h.push(t))}if(h.sort(Wf),r.interval){const t=function(e,t,n,[r,s],i,o,a){const l=Wu(e.node(r)),u=Wu(e.node(s)),c=Df(l),h=Df(u);if(!c||!h||Math.abs(c.im)>1e-12||Math.abs(h.im)>1e-12)throw new Hl("the interval is two numbers, lo and hi");if(c.re>h.re)throw new Hl("the interval starts after it ends");const f=e=>e>=c.re-1e-9&&e<=h.re+1e-9,p=[],m=new Set,d=e=>{m.has(e.s)||(m.add(e.s),p.push(e))};let g=null;for(const e of t){const t=Df(e);if(!t||Math.abs(t.im)>1e-12)continue;const r=n.get(e);if(void 0===r){f(t.re)&&d(e);continue}if(null===r){g=[o],f(t.re)&&d(e);continue}const s=Df(r).re,l=Math.ceil((c.re-t.re)/s-1e-9),u=Math.floor((h.re-t.re)/s+1e-9);if(u-l+1>Pf)throw new Hl(`more than ${Pf} answers in that interval`);for(let t=l;t<=u;t++){const n=0===t?e:i(Hu(ku([Pu(e),Mu([lu(Yl.of(t)),Pu(r)])])));Uf(o,a,n)||d(n)}}return p.sort(Wf),{values:p,lo:l,hi:u,uneven:g}}(e,h,m,r.interval,e=>p(e),o,n);return t.uneven&&u.push(...t.uneven),{solutions:t.values,base:h,unsolved:u,steps:s,always:u.some(e=>e.always),periodic:!1,period:null,interval:[t.lo,t.hi]}}const d=l.periods??[],g=h.length&&d.length&&d.every(e=>e&&e.s===d[0].s)?d[0]:null;return{solutions:h,unsolved:u,steps:s,always:u.some(e=>e.always),periodic:d.length>0&&h.length>0,period:g}}const Pf=200;function Wf(e,t){const n=Df(e),r=Df(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 Df(e){if(Xu(e).size)return null;try{const{re:t,im:n}=Mh(e,{digits:20});return{re:t,im:n}}catch{return null}}function Uf(e,t,n){const[r,s]=e.args,i=new Set([...Xu(r),...Xu(s),...Xu(n)]);if(i.delete(t),i.size)return null;const o=e=>Vf(e,t,n);try{const e=Mh(o(r),{digits:40}),t=Mh(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 Vf(e,t,n){return"sym"===e.type?e.token===t?n:e:Zl(e)?Tl(e.op,e.args.map(e=>Vf(e,t,n))):e}const Hf=24;function Gf(e,t,n,r,s,i,o,a){if(a>Hf)return ip(e,t,n,r,s,i,o);const l=function(e){const t=[],n=e=>{if(Zl(e)&&"|"===e.op)return void e.args.forEach(n);if(!Rf(e))return void t.push(e);const r=e.args[1],s=Dl(r,"pre").find(({node:e})=>Zl(e)&&"pm"===e.op);if(!s)return void t.push(e);const i=s.node.args[0],o=Wu(Vl(r,s.path,i)),a=Wu(Vl(r,s.path,Tl("neg",[i])));n(Ff(e.args[0],o)),a.s!==o.s&&n(Ff(e.args[0],a))};return n(e),t}(t);if(l.length>1){s("solve.split","Two cases",["split","minor"],t,l.reduce((e,t)=>e?Tl("|",[e,t]):t,null));for(const t of l)Gf(e,t,n,r,s,i,o,a+1);return}if(1===l.length&&l[0].s!==t.s)return Gf(e,l[0],n,r,s,i,o,a+1);const[u,c]=t.args;if("sym"===u.type&&u.token===n&&!bf(Pu(c),n))return void i.push(c);const h=ku([Pu(u),Cu(Pu(c))]);if(!bf(h,n))return fu(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 f=Ju(h).filter(e=>bf(e,n)),p=Ju(h).filter(e=>!bf(e,n)),m=ku(f),d=Cu(ku(p));if(su.complex){const l=vf(h,n);if(l&&[...l.values()].every(e=>!bf(e,n))&&Math.max(...l.keys())>=2){const u=Ff(Hu(h),Lf);return u.s!==t.s&&s("solve.one-side","Everything on one side",["move","minor"],t,u,{v:n}),ep(e,h,l,n,r,s,i,o,a,u)}}if(1===f.length)return Qf(e,t,m,d,n,r,s,i,o,a);const g=Ff(Hu(h),Lf),v=vf(h,n);if(v&&[...v.values()].every(e=>!bf(e,n))&&Math.max(...v.keys())>=2)return g.s!==t.s&&s("solve.one-side","Everything on one side",["move","minor"],t,g,{v:n}),ep(e,h,v,n,r,s,i,o,a,g);if(v&&1===Math.max(...v.keys())&&[...v.values()].every(e=>!bf(e,n))){const l=v.get(1),u=Mu([l,Pu(Il(n))]),c=Cu(v.get(0)??lu(Yl.ZERO)),h=Ff(Hu(u),Hu(c));return s("solve.collect","Collect the terms",["move","minor"],t,h,{v:n,a:Hu(l)}),Qf(e,h,u,c,n,r,s,i,o,a)}const b=Sf(h),y=b.factors.filter(e=>(bf(e.base,n)||bf(e.exp,n))&&!(fu(e.exp)&&e.exp.q.sign<0));if(y.length>=2||1===y.length&&b.factors.length>1){const l=Ff(jf(b),Lf);g.s!==t.s&&s("solve.one-side","Everything on one side",["move","minor"],t,g,{v:n}),l.s!==g.s&&s("solve.factor","Factor",["factor"],g,l,{});const u=y.filter(e=>Xf(Su(e.base,e.exp)));if(u.length){const t=y.filter(e=>!u.includes(e)),c=Ff(t.length?jf({coef:Yl.ONE,factors:t}):Hu(lu(Yl.ONE)),Lf);return s("solve.never-zero","A factor that is never zero",["move"],l,c,{f:Hu(Mu(u.map(e=>Su(e.base,e.exp))))}),t.length?1===t.length?Gf(e,Ff(Hu(t[0].base),Lf),n,r,s,i,o,a+1):Gf(e,c,n,r,s,i,o,a+1):void s("solve.never","No solution",["check"],c,c,{v:n})}const c=y.map(e=>Ff(Hu(e.base),Lf));c.length>1&&s("solve.zero-product","A product is zero when a factor is",["split"],l,c.reduce((e,t)=>e?Tl("|",[e,t]):t,null),{});for(const t of c)Gf(e,t,n,r,s,i,o,a+1);return}const w=Cf(h);if(bf(w.den,n)){const l=Ff(Hu(w.num),Lf);return s("solve.clear-denominator","Clear the denominator",["move"],t,l,{den:Hu(w.den)}),Gf(e,l,n,r,s,i,o,a+1)}const x=f.filter(e=>!Kf(e,n));if(1===x.length&&/\b(sqrt|root|abs)\b/.test(Hu(x[0]).s))return Qf(e,t,x[0],Cu(ku(Ju(h).filter(e=>e!==x[0]))),n,r,s,i,o,a);const $=function(e,t){let n=null,r=null,s=null;for(const i of Ju(e)){const e=Yu(i).map(Hu),o=e.filter(e=>bf(Pu(e),t));if(1!==o.length||!Zl(o[0])||!["sin","cos"].includes(o[0].op))return null;const a=o[0].args[0];if(s&&a.s!==s.s)return null;s=a;const l=Mu(e.filter(e=>e!==o[0]).map(Pu));"sin"===o[0].op?n=n?ku([n,l]):l:r=r?ku([r,l]):l}return!n||!r||fu(n)&&n.q.isZero?null:{a:n,b:r,u:s}}(h,n);if($){const l=Ff(Tl("tan",[$.u]),Hu(Cu(Zu($.b,$.a))));return g.s!==t.s&&s("solve.one-side","Everything on one side",["move","minor"],t,g,{v:n}),s("solve.sin-cos","Divide by the cosine",["trig"],g,l,{u:$.u}),Gf(e,l,n,r,s,i,o,a+1)}const k=function(e,t){const n=Hu(e),r={sin:new Set,cos:new Set};let s=null,i=!0;const o=(e,n)=>{if(Zl(e)){if(("sin"===e.op||"cos"===e.op)&&Xu(e).has(t)){s&&e.args[0].s!==s.s&&(i=!1),s=e.args[0];const t=n&&"^"===n.op&&n.args[0]===e?Hu(Pu(n.args[1])):null;return void r[e.op].add(t&&fu(Pu(t))&&Pu(t).q.isInteger&&Pu(t).q.n%2n==0n?"even":"odd")}["tan","sec","csc","cot"].includes(e.op)&&Xu(e).has(t)&&(i=!1);for(const t of e.args)o(t,e)}};if(o(n,null),!(i&&s&&r.sin.size&&r.cos.size))return null;const a=r.cos.has("odd")?r.sin.has("odd")?null:"sin":"cos";if(!a)return null;const l="cos"===a?"sin":"cos",u=e=>{if(!Zl(e))return e;if("^"===e.op&&Zl(e.args[0])&&e.args[0].op===a&&e.args[0].args[0].s===s.s){const t=Pu(e.args[1]).q.div(Yl.of(2));return Tl("^",[Tl("-",[Hu(lu(Yl.ONE)),Tl("^",[Tl(l,[s]),Hu(lu(Yl.of(2)))])]),Hu(lu(t))])}return Tl(e.op,e.args.map(u))};return{E:df(Pu(u(n))),u:s,from:a,to:l}}(h,n);if(k)return g.s!==t.s&&s("solve.one-side","Everything on one side",["move","minor"],t,g,{v:n}),s("solve.pythagorean","Use sin² + cos² = 1",["trig"],g,Ff(Hu(k.E),Lf),{u:k.u,from:Il(k.from),to:Il(k.to),fromName:Il("sin"===k.from?"sine":"cosine"),toName:Il("sin"===k.to?"sine":"cosine")}),Gf(e,Ff(Hu(k.E),Lf),n,r,s,i,o,a+1);const q=function(e,t){const n=Hu(e),r=new Map;for(const{node:e}of Dl(n,"pre"))if(Zl(e)&&Xu(e).has(t))if("^"!==e.op||Xu(e.args[0]).has(t))(["ln","sqrt","abs"].includes(e.op)&&e.args[0].s===t||["sin","cos","tan"].includes(e.op)&&Xu(e.args[0]).has(t))&&r.set(e.s,e);else{const n=Pu(e.args[1]),{coef:s,rest:i}=$u(n);if(i&&s.isInteger&&Hu(i).s===t){const n=Hu(Au(Pu(e.args[0]),Pu(Il(t))));r.set(n.s,n)}}const s="u"===t?"w":"u";for(const e of r.values()){const r=sp(n,e,t,s);if(!r||Xu(r).has(t))continue;const i=Pu(r),o=vf(i,s);if(o&&Math.max(...o.keys())>=1)return{kernel:Pu(e),poly:i,symbol:s}}return null}(h,n);if(q){const t=q.symbol;s("solve.substitute","Substitute",["substitute"],g,Ff(Hu(q.poly),Lf),{u:Il(t),kernel:Hu(q.kernel)});const l=[];Gf(e,Ff(Hu(q.poly),Lf),t,r,s,l,o,a+1);for(const u of l){const l=Ff(Hu(q.kernel),u);s("solve.back","Substitute back",["substitute"],Ff(Il(t),u),l,{u:Il(t),kernel:Hu(q.kernel)}),Gf(e,l,n,r,s,i,o,a+1)}return}return ip(e,g,n,r,s,i,o)}function Qf(e,t,n,r,s,i,o,a,l,u){let c=Ff(Hu(n),Hu(r));c.s!==t.s&&o("solve.move","Move the terms",["move","minor"],t,c,{v:s});const{coef:h,rest:f}=$u(n),p=f?Yu(f):[],m=Mu([lu(h),...p.filter(e=>!bf(e,s))]);if(!fu(m)||!m.q.isOne){const e=Mu(p.filter(e=>bf(e,s))),t=Ff(Hu(e),Hu(Zu(r,m))),n=fu(m)&&!m.q.isInteger&&(1n===m.q.n||-1n===m.q.n);o(n?"solve.multiply":"solve.divide",n?"Multiply both sides":"Divide both sides",["move","minor"],c,t,{by:Hu(n?lu(m.q.inv()):m),v:s}),c=t}if("sym"===c.args[0].type&&c.args[0].token===s)return void a.push(c.args[1]);const d=Pu(c.args[1]);if(fu(d)&&d.q.isZero){const t=Pu(c.args[0]),n=Yu(t).filter(e=>bf(e,s)&&!Jf(e)&&!Xf(e)),r=Yu(t).filter(e=>bf(e,s)&&!Jf(e)&&Xf(e));if(r.length&&n.length){const t=Ff(Hu(Mu(n)),Lf);return o("solve.never-zero","A factor that is never zero",["move"],c,t,{f:Hu(Mu(r))}),Gf(e,t,s,i,o,a,l,u+1)}if(r.length&&!Yu(t).some(e=>bf(e,s)&&Jf(e)))return void o("solve.never","No solution",["check"],c,c,{v:s});if(!n.length&&Yu(t).some(e=>bf(e,s)))return void o("solve.never","No solution",["check"],c,c,{});if(n.length>1||n.length<Yu(t).filter(e=>bf(e,s)).length){const t=n.map(e=>Ff(Hu(Yf(e)),Lf));o("solve.zero-product","A product is zero when a factor is",["split"],c,t.reduce((e,t)=>e?Tl("|",[e,t]):t,null),{});for(const n of t)Gf(e,n,s,i,o,a,l,u+1);return}}const g=Bh(c,e.set.view("isolate"),{format:e.format,maxSteps:1,variable:s});if(g.steps.length){const t=function(e,t,n,r){const s=(e.tags??[]).find(e=>"period-2pi"===e||"period-pi"===e);if(!s)return;r.periods??=[];const i=t.args[0].args?.[0];let o=null;try{const e=i?vf(df(Pu(i)),n):null,t=e&&[...e.keys()].every(e=>0===e||1===e)?e.get(1):null;t&&!bf(t,n)&&fu(t)&&!t.q.isZero&&(o=Hu(Mu([lu(new Yl("period-2pi"===s?2n:1n,1n).div(t.q.abs())),Pu(Il("pi"))])))}catch{}return r.periods.push(o),o}(g.steps[0],c,s,a);!function(e,t){for(const n of t)e.raw(n)}(o,g.steps);const n=a.length;if(Gf(e,g.node,s,i,o,a,l,u+1),void 0!==t){a.periodOf??=new Map;for(const e of a.slice(n))a.periodOf.has(e)||a.periodOf.set(e,t)}return}const v=Yu(Pu(c.args[0])).filter(e=>bf(e,s)&&Jf(e));if(v.length&&(!fu(d)||!d.q.isZero)){const t=Au(Mu(v),lu(Yl.MINUS_ONE)),n=Ff(Hu(Mu([Pu(c.args[0]),t])),Hu(df(Mu([d,t]))));return o("solve.clear-denominator","Clear the denominator",["move"],c,n,{den:Hu(t)}),Gf(e,n,s,i,o,a,l,u+1)}const b=Pu(c.args[0]),y=df(b),w=du(y)!==du(b)?vf(y,s):null;if(w&&[...w.values()].every(e=>!bf(e,s))&&Ju(y).length>1){const t=Ff(Hu(y),c.args[1]);return o("solve.expand","Multiply out",["expand"],c,t,{v:s}),Gf(e,t,s,i,o,a,l,u+1)}return ip(e,c,s,i,o,a,l)}function Xf(e){const t=Hu(e);if(!Zl(t)||"^"!==t.op)return!1;const n=Pu(t.args[0]);return"sym"===n.type&&("e"===n.token||"=e"===n.token)||fu(n)&&n.q.sign>0||"e"===Hu(n).s}const Jf=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&fu(e.fs[0].e)&&e.fs[0].e.q.sign<0,Yf=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&fu(e.fs[0].e)&&e.fs[0].e.q.sign>0?e.fs[0].b:e,Kf=(e,t)=>{const n=vf(e,t);return Boolean(n)&&[...n.values()].every(e=>!bf(e,t))};function ep(e,t,n,r,s,i,o,a,l,u){const c=Math.max(...n.keys()),h=yf(n);if(su.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=Au(lu(t.abs()),lu(new Yl(1n,BigInt(c)))),s=[];for(let r=0;r<c;r++){const i=Mu([lu(new Yl(BigInt((t.sign<0?1:0)+2*r),BigInt(c))),Pu(Il("pi"))]),o=Tl("*",[Hu(n),Tl("+",[Tl("cos",[Hu(i)]),Tl("*",[Il("i"),Tl("sin",[Hu(i)])])])]);s.push(Bh(o,e.set.view("simplify"),{format:e.format}).node)}return i("solve.roots","All n roots",["complex"],u,s.map(e=>Ff(Il(r),e)).reduce((e,t)=>e?Tl("|",[e,t]):t),{v:r,n:String(c),last:String(c-1),r:Hu(lu(t))}),void o.push(...s)}if(np(n)===c/2&&c>=4)return rp(e,n,c/2,r,s,i,o,a,l,u);if(h){const{roots:n}=Mf(h);if(n.length){const n=Sf(t),c=Ff(jf(n),Lf);if(n.factors.length>1||n.factors.some(e=>!(fu(e.exp)&&e.exp.q.isOne))){i("solve.factor","Factor",["factor"],u,c,{});const t=n.factors.filter(e=>bf(e.base,r)).map(e=>Ff(Hu(e.base),Lf));t.length>1&&i("solve.zero-product","A product is zero when a factor is",["split"],c,t.reduce((e,t)=>e?Tl("|",[e,t]):t,null),{});for(const n of t)Gf(e,n,r,s,i,o,a,l+1);return}}}const f=np(n);if(f>=2&&c>2&&c/f<=4)return rp(e,n,f,r,s,i,o,a,l,u);if(2===c){const e=n.get(2),t=n.get(1)??lu(Yl.ZERO),s=n.get(0)??lu(Yl.ZERO),a=ku([Au(t,lu(Yl.of(2))),Mu([lu(Yl.of(-4)),e,s])]);if(fu(a)&&a.q.sign<0&&!su.complex)return void i("solve.no-real","No real solutions",["quadratic"],u,u,{D:Hu(a)});const l=Mu([lu(Yl.of(2)),e]),c=Au(a,lu(Yl.HALF)),h=Hu(Zu(ku([Cu(t),c]),l)),f=Hu(Zu(ku([Cu(t),Cu(c)]),l)),p=h.s===f.s?Ff(Il(r),h):Tl("|",[Ff(Il(r),h),Ff(Il(r),f)]);return i(su.complex&&fu(a)&&a.q.sign<0?"solve.quadratic-complex":"solve.quadratic","The quadratic formula",["quadratic"],u,p,{a:Hu(e),b:Hu(t),c:Hu(s),D:Hu(a),root:Hu(c),v:r}),o.push(h),void(f.s!==h.s&&o.push(f))}return ip(e,u,r,s,i,o,a)}const tp=(e,t)=>t?tp(t,e%t):e,np=e=>[...e.keys()].filter(e=>e>0).reduce((e,t)=>tp(e,t),0);function rp(e,t,n,r,s,i,o,a,l,u){const c="u"===r?"w":"u",h=Au(Pu(Il(r)),lu(Yl.of(n))),f=ku([...t.entries()].map(([e,t])=>Mu([t,Au(Pu(Il(c)),lu(Yl.of(e/n)))])));i("solve.substitute","Substitute",["substitute"],u,Ff(Hu(f),Lf),{u:Il(c),kernel:Hu(h)});const p=[];Gf(e,Ff(Hu(f),Lf),c,s,i,p,a,l+1);for(const t of p){const n=Ff(Hu(h),t);i("solve.back","Substitute back",["substitute"],Ff(Il(c),t),n,{u:Il(c),kernel:Hu(h)}),Gf(e,n,r,s,i,o,a,l+1)}}function sp(e,t,n,r){if(e.s===t.s)return Il(r);if(!Zl(e))return e;if("^"===e.op&&"^"===t.op&&e.args[0].s===t.args[0].s){const t=Pu(e.args[1]),{coef:s,rest:i}=$u(t);if(i&&Hu(i).s===n&&s.isInteger)return Tl("^",[Il(r),Hu(lu(s))])}return Tl(e.op,e.args.map(e=>sp(e,t,n,r)))}function ip(e,t,n,r,s,i,o){if(r.approximate){const e="number"==typeof r.approximate?r.approximate:15,o=Pu(Tl("-",[t.args[0],t.args[1]])),a=su.complex?yf(vf(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=op(e);if(0===t)return n;const r=Tl("*",[op(Math.abs(t)),Il("i")]);return 0===e?t<0?Tl("neg",[r]):r:Tl(t<0?"-":"+",[n,r])})}(a.map(e=>e.toNumber()),Math.min(e,14)):function(e,t,n){const r=Pu(Tl("-",[e.args[0],e.args[1]])),s=Hu(r),i=e=>{try{return Mh(Vf(s,t,ap(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(ap(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(ap(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=>Ff(Il(n),e)).reduce((e,t)=>e?Tl("|",[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 op=e=>zl(String(e).includes("e")?e.toFixed(20):String(e)),ap=e=>zl(Number.isInteger(e)?String(e):e.toFixed(17)),lp=["first","second","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth"];const up=()=>zl("1"),cp={"<":e=>e<0,">":e=>e>0,"≤":e=>e<=0,"≥":e=>e>=0},hp=new Set(["sin","cos","tan","csc","sec","cot"]);function fp(e,t,n,r={}){const s=[],i=[],o=[];let a=t;for(;Zl(a.args[0])&&cp[a.args[0].op];)o.unshift({op:a.op,right:a.args[1]}),a=a.args[0];const l=[a.args[0],a.args[1],...o.map(e=>e.right)];[a.op,...o.map(e=>e.op)].forEach((e,t)=>i.push({h:Wu(Tl("-",[l[t],l[t+1]])),op:e}));const u=new Set(i.flatMap(e=>[...Xu(e.h)]));if(u.delete(n),u.size)throw new Hl(`an inequality in ${n} with other unknowns (${[...u].join(", ")}) can't be charted`);const c=r.interval?r.interval.map(t=>Wu(e.node(t))):null;if(!c&&i.some(e=>Dl(e.h,"pre").some(({node:e})=>Zl(e)&&hp.has(e.op)&&Xu(e).has(n))))return{pieces:null,steps:s,unsolved:!0};const h=[];for(const{h:e}of i){h.push(e);for(const{node:t}of Dl(e,"pre"))Zl(t)&&Xu(t).has(n)&&("/"===t.op&&h.push(t.args[1]),"sqrt"!==t.op&&"ln"!==t.op||h.push(t.args[0]),"root"===t.op&&h.push(t.args[1]),"log"===t.op&&h.push(t.args[1],t.args[0],Tl("-",[t.args[0],up()])),["arcsin","arccos","arctanh","arcsec","arccsc"].includes(t.op)&&h.push(Tl("-",[t.args[0],up()]),Tl("+",[t.args[0],up()])),"arccosh"===t.op&&h.push(Tl("-",[t.args[0],up()])),"^"===t.op&&fu(Pu(t.args[1]))&&Pu(t.args[1]).q.sign<0&&h.push(t.args[0]),"^"===t.op&&fu(Pu(t.args[1]))&&!Pu(t.args[1]).q.isInteger&&h.push(t.args[0]))}const f=new Map;for(const t of h){const r=Bf(e,Ff(t,Lf),n,{...c?{interval:c}:{}});if(r.unsolved.length&&!r.always)return{pieces:null,steps:s,unsolved:!0};if(!r.always)for(const e of r.solutions){const t=Df(e);!t||Math.abs(t.im)>1e-12||f.set(e.s,{node:e,x:t.re})}}let p=[...f.values()].sort((e,t)=>e.x-t.x).filter((e,t,n)=>0===t||Math.abs(e.x-n[t-1].x)>1e-12),m=null;if(c){const[e,t]=c.map(e=>({node:e,x:Df(e)?.re}));if(!Number.isFinite(e.x)||!Number.isFinite(t.x)||e.x>t.x)throw new Hl("the interval is two numbers, lo then hi");m={lo:e,hi:t},p=p.filter(n=>n.x>e.x+1e-12&&n.x<t.x-1e-12)}const d=e=>i.every(({h:t,op:r})=>{try{const s=Mh(Vf(t,n,zl(function(e){return Math.abs(e)>=1e21?BigInt(Math.round(e)).toString():e.toFixed(Math.min(100,Math.max(0,17-Math.floor(Math.log10(Math.abs(e)||1)))))}(e))),{digits:20});return!(!Number.isFinite(s.re)||Math.abs(s.im)>1e-12)&&cp[r](Math.abs(s.re)<1e-30?0:s.re)}catch{return!1}}),g=e=>i.every(({h:t,op:r})=>{try{const s=Mh(Wu(Vf(t,n,e.node)),{digits:30});return!(!Number.isFinite(s.re)||Math.abs(s.im)>1e-12)&&cp[r](Math.abs(s.re)<1e-15?0:s.re)}catch{return!1}});if(m)return function(e,t,n,r,s,{lo:i,hi:o},a,l){const u=[i,...s,o],c=u.map(l),h=u.slice(1).map((e,t)=>a((u[t].x+e.x)/2)),f=[];let p=null;for(let e=0;e<u.length;e++){const t=u[e];if(c[e]&&!p?p={lo:t.node,loClosed:!0}:!c[e]&&p&&(f.push({...p,hi:t.node,hiClosed:!1}),p=null),e===u.length-1)break;h[e]?p??={lo:t.node,loClosed:!1}:p&&(f.push({...p,hi:t.node,hiClosed:c[e]}),p=null)}p&&f.push({...p,hi:o.node,hiClosed:c[u.length-1]});for(const e of f)e.lo.s===e.hi.s&&(e.loClosed=!0,e.hiClosed=!0);const m=s.length?s.map(t=>e.format(t.node)).join(", "):"none";return r.push(e.step("solve.sign-chart","A sign chart",["inequality"],t,t,{points:Il(m),v:n})),{pieces:f,steps:r,interval:[i.node,o.node]}}(e,t,n,s,p,m,d,g);const v=p.map(e=>e.x),b=[];if(v.length){b.push(v[0]-Math.max(1,Math.abs(v[0])));for(let e=0;e+1<v.length;e++)b.push((v[e]+v[e+1])/2);b.push(v[v.length-1]+Math.max(1,Math.abs(v[v.length-1])))}else b.push(0);const y=b.map(d),w=p.map(g),x=[];let $=null;const k=(e,t)=>{x.push({...$,hi:e,hiClosed:t}),$=null};for(let e=0;e<=p.length;e++){const t=0===e?null:p[e-1].node;if(y[e]?$??={lo:t,loClosed:!1}:$&&k(t,e>0&&w[e-1]),e===p.length)break;const n=p[e];if(w[e]){if($)continue;y[e+1]?$={lo:n.node,loClosed:!0}:x.push({lo:n.node,hi:n.node,loClosed:!0,hiClosed:!0})}else $&&k(n.node,!1)}$&&k(null,!1);const q=p.length?p.map(t=>e.format(t.node)).join(", "):"none";return s.push(e.step("solve.sign-chart","A sign chart",["inequality"],t,t,{points:Il(q),v:n})),{pieces:x,steps:s}}const pp={tan:"cos",sec:"cos",csc:"sin",cot:"sin"};class mp extends Error{}const dp=e=>({fin:e}),gp={bnd:!0},vp=e=>({inf:e}),bp=Il("∞");function yp(e){try{const t=Mh(e,{digits:15});return Math.abs(t.im??0)>1e-12?NaN:t.re??t.number}catch{return NaN}}function wp(e){if(!su.complex)return Number.isFinite(yp(e));try{const t=Mh(e,{digits:15});return Number.isFinite(t.re??t.number)&&Number.isFinite(t.im??0)}catch{return!1}}function xp(e,t,n){if(!Number.isFinite(n))return!1;try{const r=Mh(Vf(e,t,zl(kp(n))),{digits:15});return Math.abs(r.im??0)>1e-12}catch(e){return/not real/.test(e.message)}}function $p(e,t,n){return Number.isFinite(n)?yp(Vf(e,t,zl(kp(n)))):NaN}function kp(e){const t=Math.min(40,Math.max(0,16-Math.floor(Math.log10(Math.abs(e)||1))));return e.toFixed(t)}function qp(e,t,n,r){const s=Mp(n,r).map(n=>$p(e,t,n)).filter(Number.isFinite);if(s.length<3)return NaN;const[i,o,a]=s.slice(-3),l=Math.max(1,Math.abs(a));return Math.abs(a-o)<1e-4*l&&Math.abs(o-i)<.01*l?a:NaN}function Mp(e,t){if(e.inf)return[100,1e3,1e4,1e5,1e6].map(t=>t*e.inf);const n=yp(e.fin);return[.001,1e-4,1e-5,1e-6,1e-7].map(e=>n+t*e*Math.max(1,Math.abs(n)))}function Ap(e,t,n,r){const s=Mp(n,r).map(n=>$p(e,t,n)).filter(Number.isFinite);if(!s.length)return 0;const i=Math.sign(s[s.length-1]);return s.slice(-3).every(e=>Math.sign(e)===i)?i:0}function Sp(e,t,n,r,s=0){const i=[];if(!s&&!r.inf){const[e,s]=[qp(t,n,r,-1),qp(t,n,r,1)];if(Number.isFinite(e)&&Number.isFinite(s)&&Math.abs(e-s)>.001*Math.max(1,Math.abs(e),Math.abs(s)))throw new mp(`from the left it goes to ${+e.toPrecision(6)}, from the right to ${+s.toPrecision(6)}`)}if(!r.inf&&!su.complex)for(const e of s?[s]:[-1,1])if(Mp(r,e).every(e=>xp(t,n,e)))throw new mp(`it has no real values ${e<0?"to the left":"to the right"} of ${+yp(r.fin).toPrecision(6)}`);const o=new Op(e,n,r,s,i);let a;try{if(a=o.of(Wu(function(e,t){const{v:n,a:r,side:s}=e,i=r.inf?r.inf:s;if(!i)return t;let o=t;const a=t=>{if(!Zl(t))return t;const s=t.args.map(a),l=s.some((e,n)=>e!==t.args[n])?Tl(t.op,s):t;if("abs"!==l.op||!Xu(l.args[0]).has(n))return l;const u=Ap(l.args[0],n,r,i);if(!u)return l;const c=u>0?l.args[0]:Wu(Tl("neg",[l.args[0]])),h=Wu(Np(o,l,c));return e.step("limit.abs","Absolute value",o,h,{inside:l.args[0],abs:l,to:c,sign:u>0?"positive":"negative",where:r.inf?"that far out":"on this side"}),o=h,c};return a(t),o}(o,t)),0),a.bnd)throw new mp("it keeps swinging between bounds")}catch(e){if(e instanceof mp){const e=(r.inf?[r.inf]:s?[s]:[-1,1]).map(e=>qp(t,n,r,e));if(e.every(Number.isFinite)&&e.every(t=>Math.abs(t-e[0])<1e-6*Math.max(1,Math.abs(t))))throw new Hl(`numbers near the point settle on ${+e[0].toPrecision(6)}: not answered`)}throw e}return function(e,t,n,r,s){const i=r?[r]:n.inf?[-1]:[-1,1];for(const r of i){const i=Mp(n,r).map(n=>$p(e,t,n)).filter(Number.isFinite);if(i.length<3)continue;const o=i[i.length-1];if(s.inf){if(Math.sign(o)!==s.inf||Math.abs(o)<Math.abs(i[0]))throw new Hl(`numbers near the point don't go to ${s.inf>0?"∞":"-∞"}: not answered`)}else{const e=yp(s.fin);if(!Number.isFinite(e))continue;const t=i.map(t=>Math.abs(t-e)),n=Math.abs(i[i.length-1]-i[i.length-2]),r=t.every((e,n)=>0===n||e<t[n-1])&&t[t.length-1]<.5*t[0]&&t[t.length-1]<10*n;if(t[t.length-1]>.01*Math.max(1,Math.abs(e))&&!r)throw new Hl(`numbers near the point go to ${o.toPrecision(6)}, not ${e.toPrecision(6)}: not answered`)}}}(t,n,r,s,a),{value:a,steps:i}}function Np(e,t,n){return e.s===t.s?n:Zl(e)?Tl(e.op,e.args.map(e=>Np(e,t,n))):e}class Op{constructor(e,t,n,r,s){Object.assign(this,{cas:e,v:t,a:n,side:r,steps:s}),this.point=n.inf?n.inf>0?bp:Il("-∞"):n.fin}step(e,t,n,r,s={}){this.steps.push(this.cas.step(e,t,["limit"],n,r,{v:Il(this.v),a:this.point,...s}))}of(e,t){if(t>8)throw new Hl("this limit went too deep");const{v:n,a:r}=this;if(!Xu(e).has(n))return dp(e);if("sym"===e.type)return r.inf?vp(r.inf):dp(r.fin);if(r.inf){const s=yf(vf(Pu(e),n));if(s&&s.length>1){const i=s.length-1,o=s[i].sign*(i%2&&r.inf<0?-1:1);return 0===t&&this.step("limit.leading","The leading term",e,Wu(Tl("*",[Hu(lu(s[i])),Tl("^",[Il(n),zl(String(i))])])),{f:e,lead:Wu(Tl("*",[Hu(lu(s[i])),Tl("^",[Il(n),zl(String(i))])]))}),vp(o)}}if(!r.inf&&0===t){const t=Vf(e,n,r.fin);let s=null;if(wp(t)&&!this.pole(t)&&!Ep(t))try{s=Wu(t)}catch{}if(s&&wp(s)){const t=this.cas.simplify(s,{steps:!1}).result;return this.step("limit.substitute","Put the point in",e,t,{f:e}),dp(t)}}if(!Zl(e))return dp(e);switch(e.op){case"+":case"-":return this.sum(e,t);case"neg":return zp(this.of(e.args[0],t+1));case"*":return this.product(e,t);case"/":return this.quotient(e,e.args[0],e.args[1],t);case"^":return this.power(e,t);default:return this.func(e,t)}}signOf(e){const t=Math.sign(yp(e));if(!t)throw new Hl(`the sign of ${this.cas.format(e)} is not known`);return t}pole(e){return Ip(e).some(e=>Zl(e)&&pp[e.op]&&this.isExactZero(Tl(pp[e.op],[e.args[0]])))}isExactZero(e){try{const t=this.cas.simplify(Wu(e),{steps:!1}).result;return Cl(t)&&0===Number(t.value)}catch{return!1}}sum(e,t){const[n,r]=e.args;let s,i;try{s=this.of(n,t+1),i=this.of(r,t+1)}catch(n){if(!(n instanceof mp))throw n;const r=Cf(Pu(e)),s=Wu(Tl("/",[Hu(r.num),Hu(r.den)]));if(s.s===e.s)throw n;return this.step("limit.combine","One fraction",e,s,{f:e}),this.of(s,t+1)}const o="-"===e.op?zp(i):i;if(s.bnd||o.bnd)return s.inf||o.inf?s.inf?s:o:gp;if(s.fin&&o.fin)return dp(Wu(Tl("+",[s.fin,o.fin])));if(s.inf&&o.inf&&s.inf!==o.inf){const s="-"===e.op?r:Tl("neg",[r]);if([n,r].some(e=>Zl(e)&&"sqrt"===e.op)||Zl(r)&&"neg"===r.op&&Zl(r.args[0])&&"sqrt"===r.args[0].op){const r=Wu(Tl("/",[Tl("-",[Tl("^",[n,zl("2")]),Tl("^",[s,zl("2")])]),Tl("+",[n,s])]));return this.step("limit.conjugate","∞ − ∞: the conjugate",e,r,{f:e}),this.of(r,t+1)}const i=Cf(Pu(e)),o=Wu(Tl("/",[Hu(i.num),Hu(i.den)]));if(o.s===e.s)throw new Hl("∞ − ∞ that does not become one fraction");return this.step("limit.combine","∞ − ∞: one fraction",e,o,{f:e}),this.of(o,t+1)}return s.inf?s:o}product(e,t){const[n,r]=e.args,s=this.of(n,t+1),i=this.of(r,t+1),o=e=>e.fin&&Math.abs(yp(e.fin))<1e-300;if(s.bnd||i.bnd){const t=s.bnd?i:s;if(o(t))return this.step("limit.squeeze","The squeeze theorem",e,zl("0"),{f:e,bounded:s.bnd?n:r}),dp(zl("0"));if(t.inf)throw new mp("a growing factor times one that keeps swinging");return gp}if(s.fin&&i.fin)return dp(Wu(Tl("*",[s.fin,i.fin])));if(o(s)&&i.inf||s.inf&&o(i)){const[i,a]=o(s)?[n,r]:[r,n],l=e=>e.s.split(" ").length,[u,c]=[Wu(Tl("/",[zl("1"),i])),Wu(Tl("/",[zl("1"),a]))],h=l(u)<=l(c)?Tl("/",[a,u]):Tl("/",[i,c]);return this.step("limit.zero-times-infinity","0·∞: a quotient",e,h,{f:e}),this.quotient(h,h.args[0],h.args[1],t+1)}const a=e=>e.inf?e.inf:this.signOf(e.fin);return vp(a(s)*a(i))}quotient(e,t,n,r){const{v:s,a:i}=this;if(i.inf){const t=this.rational(e,r);if(t)return t}const o=this.of(t,r+1),a=this.of(n,r+1),l=e=>e.fin&&Math.abs(yp(e.fin))<1e-300;if(o.bnd&&a.inf)return this.step("limit.squeeze","The squeeze theorem",e,zl("0"),{f:e,bounded:t}),dp(zl("0"));if(o.bnd&&a.fin&&!l(a))return gp;if(a.bnd)throw new Hl("a quotient over something that keeps swinging is not worked out here");if(o.inf&&a.inf&&i.inf){const s=this.dividePower(e,t,n,r);if(s)return s}if(a.fin&&!l(a))return o.fin?dp(this.cas.simplify(Wu(Tl("/",[o.fin,a.fin])),{steps:!1}).result):vp(o.inf*this.signOf(a.fin));if(a.inf&&o.fin)return dp(zl("0"));if(l(a)&&!l(o))return this.blowUp(e);const u=l(o)?"0/0":"∞/∞",c=this.rational(e,r);if(c)return c;const h=Wu(this.cas.differentiate(t,s)),f=Wu(this.cas.differentiate(n,s)),p=Wu(Tl("/",[h,f]));return this.step("limit.lhopital","L'Hôpital's rule",e,p,{f:e,form:Il(u)}),this.of(p,r+1)}dividePower(e,t,n,r){const{v:s,a:i}=this;if(!Ip(e).some(e=>Zl(e)&&(["sqrt","root","sin","cos"].includes(e.op)||"^"===e.op&&!Xu(e.args[1]).size&&!Number.isInteger(yp(e.args[1]))))||this.divided?.has(e.s))return null;const[o,a]=[1e4*i.inf,1e6*i.inf],l=Math.log(Math.abs($p(n,s,a)/$p(n,s,o)))/Math.log(100),u=Math.round(2*l)/2;if(!Number.isFinite(l)||Math.abs(l-u)>.05||u<=0||i.inf<0&&!Number.isInteger(u))return null;const c=Tl("^",[Il(s),zl(String(u))]),h=e=>{if(Zl(e)&&("+"===e.op||"-"===e.op))return Tl(e.op,e.args.map(h));if(Zl(e)&&"neg"===e.op)return Tl("neg",[h(e.args[0])]);if(Zl(e)&&"sqrt"===e.op){const t=Tl("sqrt",[Wu(Tl("/",[e.args[0],Tl("^",[Il(s),zl(String(2*u))])]))]);return i.inf<0&&u%2?Tl("neg",[t]):t}return Wu(Tl("/",[e,c]))},f=Tl("/",[Wu(h(t)),Wu(h(n))]);return(this.divided??=new Set).add(e.s),this.step("limit.divide-power","Divide by the highest power",e,f,{f:e,power:c}),this.quotient(f,f.args[0],f.args[1],r+1)}rational(e,t){const{v:n,a:r}=this,{num:s,den:i}=Cf(Pu(e)),o=yf(vf(s,n)),a=yf(vf(i,n));if(!o||!a||a.length<2)return null;if(r.inf){const[t,s]=[o.length-1,a.length-1],i=Wu(Tl("/",[Tl("*",[Hu(lu(o[t])),Tl("^",[Il(n),zl(String(t))])]),Tl("*",[Hu(lu(a[s])),Tl("^",[Il(n),zl(String(s))])])]));if(i.s!==e.s&&this.step("limit.leading","The leading terms",e,i,{f:e,lead:i}),t<s)return dp(zl("0"));if(t===s)return dp(Hu(lu(o[t].div(a[s]))));const l=o[t].div(a[s]).sign*((t-s)%2&&r.inf<0?-1:1);return vp(l)}const l=this.cas.cancel(e,{steps:!1}).result;if(l.s===e.s)return null;this.step("limit.cancel","Cancel the common factor",e,l,{f:e});const u=Vf(l,n,r.fin);return Number.isFinite(yp(u))?dp(this.cas.simplify(Wu(u),{steps:!1}).result):this.blowUp(l)}blowUp(e){const{v:t,a:n,side:r}=this,s=(r?[r]:[-1,1]).map(r=>Ap(e,t,n,r));if(s.includes(0))throw new Hl("the sign near the point could not be told");if(2===s.length&&s[0]!==s[1])throw this.step("limit.one-sided","The two sides differ",e,e,{f:e,left:s[0]>0?bp:Il("-∞"),right:s[1]>0?bp:Il("-∞")}),new mp(`from the left it goes to ${s[0]>0?"∞":"-∞"}, from the right to ${s[1]>0?"∞":"-∞"}`);return vp(s[0])}power(e,t){const{v:n}=this,[r,s]=e.args,i=this.of(r,t+1);let o;const a=this.steps.length;try{o=this.of(s,t+1)}catch(n){if(!(n instanceof mp)||!i.fin||Math.abs(yp(i.fin)-1)>1e-12)throw n;return this.steps.length=a,this.expLog(e,r,s,"1^∞",t)}if(i.bnd||o.bnd)throw new Hl("a power of something that keeps swinging is not worked out here");const l=e=>e.fin?yp(e.fin):e.inf*(1/0),u=l(i),c=l(o);if(i.fin&&o.fin){if(Math.abs(u)<1e-300&&c<0)return this.blowUp(e);if(!(Math.abs(u)<1e-300&&Math.abs(c)<1e-300))return dp(this.cas.simplify(Wu(Tl("^",[i.fin,o.fin])),{steps:!1}).result)}const h=!Xu(r).has(n),f=!Xu(s).has(n),p=i.fin&&Math.abs(u)<1e-300,m=i.fin&&Math.abs(u-1)<1e-12;if(i.fin&&o.inf&&(!m||h)){if(m)return dp(zl("1"));if(p){if(o.inf<0){if(h)throw new mp("0 to a negative power has no value");return vp(1)}return dp(zl("0"))}if(u>1)return o.inf>0?vp(1):dp(zl("0"));if(u>0)return o.inf>0?dp(zl("0")):vp(1);throw new mp("a negative number to a growing power swings between signs")}if(i.inf<0&&!f)throw new Hl("a power of something going to -∞ is not worked out here");if(i.inf&&(f||o.fin&&Math.abs(c)>1e-300||o.inf)){if(c>0)return vp(i.inf>0?1:f&&Number.isInteger(c)&&c%2?-1:1);if(c<0)return dp(zl("0"))}if(f&&p&&c>0)return dp(zl("0"));const d=m?"1^∞":p?"0^0":i.inf&&o.fin?"∞^0":null;if(!d)throw new Hl("a power of this shape is not worked out here");return this.expLog(e,r,s,d,t)}expLog(e,t,n,r,s){const i=Wu(Tl("*",[n,Tl("ln",[t])]));this.step("limit.exp-log","Take logs",e,Tl("^",[Il("e"),i]),{f:e,form:Il(r)});const o=this.of(i,s+1);if(o.bnd)throw new Hl("a power of something that keeps swinging is not worked out here");return o.inf?o.inf>0?vp(1):dp(zl("0")):dp(this.cas.simplify(Wu(Tl("^",[Il("e"),o.fin])),{steps:!1}).result)}func(e,t){const n=e.op,r=e.args;if(1!==r.length){if("log"===n&&!Xu(r[0]).has(this.v)){const e=this.of(r[1],t+1);if(e.fin){const t=Wu(Tl("log",[r[0],e.fin]));if(Number.isFinite(yp(t)))return dp(this.cas.simplify(t,{steps:!1}).result)}return this.of(Wu(Tl("/",[Tl("ln",[r[1]]),Tl("ln",[r[0]])])),t+1)}throw new Hl(`a limit of ${n} is not worked out here`)}let s;try{s=this.of(r[0],t+1)}catch(e){if(e instanceof mp&&("sin"===n||"cos"===n))return gp;throw e}if(s.bnd){if("sin"===n||"cos"===n||"arctan"===n||"abs"===n)return gp;throw new Hl(`${n} of something that keeps swinging is not worked out here`)}if(s.fin){if(pp[n]&&this.isExactZero(Tl(pp[n],[s.fin])))return this.blowUp(e);const t=Wu(Tl(n,[s.fin]));if(wp(t))return dp(this.cas.simplify(t,{steps:!1}).result);if("ln"===n&&Math.abs(yp(s.fin))<1e-300)return vp(-1);if(["tan","sec","csc","cot"].includes(n))return this.blowUp(e);throw new Hl(`${n} has no value at the limit of its argument`)}const i=s.inf;switch(n){case"sqrt":case"ln":case"cosh":if(i<0&&"cosh"!==n)throw new mp(`${n} has no value as its argument goes to -∞`);return vp(1);case"abs":return vp(1);case"sinh":return vp(i);case"tanh":return dp(zl(String(i)));case"arctan":return dp(Wu(Tl("/",[i>0?Il("pi"):Tl("neg",[Il("pi")]),zl("2")])));case"arccot":return dp(i>0?zl("0"):Il("pi"));case"arcsec":case"arccsc":return dp("arcsec"===n?Wu(Tl("/",[Il("pi"),zl("2")])):zl("0"));case"sin":case"cos":return gp;case"tan":case"sec":case"csc":case"cot":throw new mp(`${n} keeps swinging as its argument grows`);default:throw new Hl(`a limit of ${n} at ∞ is not worked out here`)}}}const Ep=e=>Ip(e).some(e=>Zl(e)&&("/"===e.op&&Math.abs(yp(e.args[1]))<1e-300||"^"===e.op&&yp(e.args[1])<0&&Math.abs(yp(e.args[0]))<1e-300)),Ip=(e,t=[])=>(t.push(e),Zl(e)&&e.args.forEach(e=>Ip(e,t)),t),zp=e=>e.bnd?e:e.inf?vp(-e.inf):dp(Wu(Tl("neg",[e.fin])));function _p(e){if(!Zl(e)||"lim"!==e.op)return null;const[t,n,r,s]=e.args;if(Zl(n)&&"→"===n.op)return{f:t,v:n.args[0].token,to:n.args[1],side:0};if("sym"===n?.type&&r){const e="r"===s?.token?1:"l"===s?.token?-1:0;return{f:t,v:n.token,to:r,side:e}}return null}function jp(e){return"sym"!==e.type||"∞"!==e.token&&"oo"!==e.token&&"infinity"!==e.token?"sym"===e.type&&"-∞"===e.token||Zl(e)&&"neg"===e.op&&"sym"===e.args[0].type&&"∞"===e.args[0].token?vp(-1):dp(Wu(e)):vp(1)}const Tp=e=>e.inf?e.inf>0?bp:Il("-∞"):e.fin,Cp=new Set(["sin","cos","tan","sec","csc","cot"]),Zp=()=>zl("2");function Fp(e,t){if(!Lp(t))return[];let n,r;try{const e=Bp(t);n=new Map;r=Cf(Pu(Pp(e,n)))}catch{return[]}const s=[],i=Rp(t);for(const t of["sin","cos","none"])try{const o=[df(r.num),df(r.den)],a="none"===t?o[0]:Wp(r.num,n,t),l="none"===t?o[1]:Wp(r.den,n,t);if(!a||!l)continue;const u=Hu(a).s!==Hu(o[0]).s||Hu(l).s!==Hu(o[1]).s,c=[{p:Vp(a,l),how:u?"pythagorean":i?"expand-double":"sin-cos"}],h=[Dp(a,n),Dp(l,n)];h[0]&&h[1]&&c.push({p:Vp(h[0],h[1]),how:"double-angle"});for(const t of c)s.push({node:Gp(e,Hp(t.p,n)),how:t.how})}catch{}return s}const Lp=e=>Zl(e)&&(Cp.has(e.op)||e.args.some(Lp)),Rp=e=>Zl(e)&&(("sin"===e.op||"cos"===e.op)&&Zl(e.args[0])&&"*"===e.args[0].op&&Cl(e.args[0].args[0])&&2===Number(e.args[0].args[0].value)||e.args.some(Rp));function Bp(e){if(!Zl(e))return e;const t=e.args.map(Bp),[n]=t,r=e=>Tl("sin",[e]),s=e=>Tl("cos",[e]),i=e=>Zl(e)&&"*"===e.op&&Cl(e.args[0])&&2===Number(e.args[0].value)?2===e.args.length?e.args[1]:Tl("*",e.args.slice(1)):null;switch(e.op){case"tan":return Tl("/",[r(n),s(n)]);case"sec":return Tl("/",[zl("1"),s(n)]);case"csc":return Tl("/",[zl("1"),r(n)]);case"cot":return Tl("/",[s(n),r(n)]);case"sin":{const e=i(n);return e?Tl("*",[Tl("*",[Zp(),r(e)]),s(e)]):r(n)}case"cos":{const e=i(n);return e?Tl("-",[Tl("^",[s(e),Zp()]),Tl("^",[r(e),Zp()])]):s(n)}default:return Tl(e.op,t)}}function Pp(e,t){if(!Zl(e))return e;if(("sin"===e.op||"cos"===e.op)&&!Lp(e.args[0])){const n=e.args[0];t.has(n.s)||t.set(n.s,{u:n,s:`$s${t.size}`,c:`$c${t.size}`});const r=t.get(n.s);return Il("sin"===e.op?r.s:r.c)}return Tl(e.op,e.args.map(e=>Pp(e,t)))}function Wp(e,t,n){let r=df(e);for(const{s:e,c:s}of t.values()){const[t,i]="sin"===n?[e,s]:[s,e],o=vf(r,t);if(!o)return null;const a=[];for(const[e,n]of o){const r=Math.floor(e/2),s=[n];e%2&&s.push(Pu(Il(t))),r&&s.push(Pu(Tl("^",[Tl("-",[zl("1"),Tl("^",[Il(i),Zp()])]),zl(String(r))]))),a.push(Mu(s))}if(r=df(ku(a)),Ju(r).length>200)return null}return r}function Dp(e,t){let n=df(e);for(const{u:e,s:r,c:s}of t.values()){const t=Tl("sin",[Tl("*",[Zp(),e])]),i=Tl("cos",[Tl("*",[Zp(),e])]),o=[];for(const e of Ju(n)){const n=Hu(e),a=Up(n,r),l=Up(n,s);if(a+l===0){o.push(e);continue}if(a+l!==2)return null;const u=Vf(Vf(n,r,zl("1")),s,zl("1")),c=Tl("/",1===a?[t,Zp()]:2===a?[Tl("-",[zl("1"),i]),Zp()]:[Tl("+",[zl("1"),i]),Zp()]);o.push(Pu(Tl("*",[u,c])))}n=df(ku(o))}return n}function Up(e,t){const n=vf(Pu(e),t);return n?Math.max(0,...n.keys()):0}function Vp(e,t){const n=Pu(Tl("/",[Hu(e),Hu(t)])),r=Zf(n);return r?jf(r):Hu(n)}function Hp(e,t){let n=e;for(const{u:e,s:r,c:s}of t.values())n=Vf(Vf(n,r,Tl("sin",[e])),s,Tl("cos",[e]));return Wu(n)}function Gp(e,t){const n=e=>{if(!Zl(e))return e;const t=e.args.map(n);if("/"===e.op&&Cl(t[0])){const e=t[1],[n,r]=Zl(e)&&"^"===e.op&&Cl(e.args[1])?[e.args[0],e.args[1]]:[e,null],s=Zl(n)&&{cos:"sec",sin:"csc"}[n.op];if(s){const e=Tl(s,n.args),i=r?Tl("^",[e,r]):e;return 1===Number(t[0].value)?i:Tl("*",[t[0],i])}}return Tl(e.op,t)},r=Bh(Wu(n(t)),e.set.view("simplify"),{format:e.format}).node;try{const{num:e,den:t}=Cf(Pu(r)),n=Wu(Tl("/",[Hu(e),Hu(t)]));return n.s.split(" ").length<r.s.split(" ").length?n:r}catch{return r}}const Qp=(e,t)=>Tl("int",[e,"string"==typeof t?Il(t):t]);function Xp(e,t,n,r=0){if(r>6)throw new Hl("integration went too deep");const s=[],i=e.set.view("integrate"),o=Bh(t,e.set.view("simplify"),{format:e.format});s.push(...Jp(o.steps,e=>Wu(Qp(e,n))));let a=Wu(Qp(o.node,n));for(let t=0;t<40;t++){const t=Bh(a,i,{format:e.format});s.push(...t.steps),a=t.node;const n=Dl(a,"pre").find(({node:e})=>{return Zl(t=e)&&"int"===t.op&&2===t.args.length;var t});if(!n)return{node:a,steps:s};const o=Yp(e,n.node,r);if(!o)throw new Hl(`no rule for ∫ ${e.format(n.node.args[0])} d${n.node.args[1].token}`);const l=a;s.push(...Jp(o.steps,e=>Wu(Vl(l,n.path,e)))),a=Wu(Vl(a,n.path,o.node))}throw new Hl("integration did not finish")}function Jp(e,t){return e.map(e=>{const n=t(Fl(e.from)).s,r=t(Fl(e.to)).s;return n===e.from&&r===e.to?e:{...e,from:n,to:r,path:null}})}function Yp(e,t,n){const[r,s]=t.args,i=s.token,o=Pu(r),a=function(e,t){const{num:n,den:r}=Cf(e),s=Sf(n),i=Sf(r),o=s.coef.div(i.coef);if(o.isOne||!bf(e,t))return null;const a=Mu([...s.factors.map(e=>Su(e.base,e.exp)),...i.factors.map(e=>Su(e.base,Cu(e.exp)))]);return{c:o,rest:a}}(o,i);if(a){const n=Tl("*",[Hu(lu(a.c)),Qp(Hu(a.rest),s)]);return{node:n,steps:[e.step("integrate.constant","Take the number out",["split","minor"],t,n,{c:Hu(lu(a.c))})]}}const l=Zf(o),u=l&&jf(l);if(u&&Bl(u)<Bl(r)&&Xu(u).has(i)){const n=Qp(u,s);return{node:n,steps:[e.step("integrate.cancel","One fraction",["cancel"],t,n,{})]}}const c=im(e,t,o,i,!0);if(c)return c;const h=df(o);if(Hu(h).s!==r.s&&"add"===h.k){const n=Qp(Hu(h),s);return{node:n,steps:[e.step("integrate.expand","Multiply out",["expand"],t,n,{})]}}const f=function(e,t){const n=new Map;for(const{node:r}of Dl(e,"pre")){if(!Zl(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||!Xu(r).has(t))continue;const e=vf(Pu(r),t);if(!e||1!==Math.max(...e.keys()))continue;const s=e.get(1);bf(s,t)||fu(s)&&s.q.isZero||n.set(r.s,{node:r,a:s})}}for(const r of n.values()){if(!Xu(um(e,r.node,Il("§"))).has(t))return r}return null}(r,i);if(f){const s="u"===i?"t":"u",o=um(r,f.node,Il(s));if(!Xu(o).has(i)){const r=Xp(e,Wu(o),s,n+1),a=Wu(Vf(r.node,s,f.node)),l=Hu(Zu(Pu(a),f.a)),u=e=>Hu(Zu(Pu(e),f.a));return{node:l,steps:[e.step("integrate.substitute","Substitute",["substitute"],t,u(Wu(Qp(Wu(o),s))),{u:Il(s),inside:f.node,a:Hu(f.a),v:i,du:Kp(e,f.a,i)}),...Jp(r.steps,u),e.step("integrate.back","Substitute back",["substitute"],u(r.node),l,{u:Il(s),inside:f.node})]}}}const p=im(e,t,o,i);if(p)return p;const m=sm(e,t,i);if(m)return m;const d=function(e,t,n,r){if(r>=3)return null;const[s,i]=t.args,o="u"===n?"t":"u",a=new Set;for(const{node:i}of Dl(s,"pre")){if(i===s||!Zl(i)||i.s===s.s||a.has(i.s)||!Xu(i).has(n)||["der","int"].includes(i.op))continue;let l,u,c;a.add(i.s);try{l=Wu(e.differentiate(i,n))}catch{continue}if(Cl(l)&&0===Number(l.value))continue;try{u=um(Wu(Tl("/",[s,l])),i,Il(o))}catch{continue}if(Xu(u).has(n))continue;try{c=Xp(e,Wu(u),o,r+1)}catch{continue}const h=Wu(Vf(c.node,o,i));return{node:h,steps:[e.step("integrate.u-substitution","Substitute",["substitute"],t,Wu(Qp(u,o)),{u:Il(o),inside:i,du:l,v:n}),...c.steps,e.step("integrate.back","Substitute back",["substitute"],c.node,h,{u:Il(o),inside:i})]}}return null}(e,t,i,n);return d||function(e,t,n,r,s){if(s>=6)return null;const i=Yu(n),o=i.filter(e=>cm(e,r)||!bf(e,r)),a=i.filter(e=>!o.includes(e));if(1!==a.length)return null;const l=Mu(o),u=a[0],c=Hu(u),h=Zl(c)?c.op:"",f=["ln","arctan","arcsin","arccos","arcsec","arccsc","arccot"];if(!bf(l,r)&&!f.includes(h))return null;let p,m,d;f.includes(h)?(p=u,m=l):(p=l,m=u);try{d=Xp(e,Hu(m),r,s+1)}catch{return null}const g=Pu(e.differentiate(Hu(p),r)),v=Mu([p,Pu(d.node)]),b=Qp(Hu(Mu([g,Pu(d.node)])),Il(r)),y=Wu(Tl("-",[Hu(v),b]));return{node:y,steps:[e.step("integrate.parts","Integration by parts",["parts"],t,y,{u:Hu(p),dv:Hu(m),V:d.node,du:Hu(g),v:r})]}}(e,t,o,i,n)}const Kp=(e,t,n)=>fu(t)&&t.q.isOne?`d${n}`:fu(t)&&t.q.neg().isOne?`-d${n}`:`${e.format(Hu(t))} d${n}`,em=e=>Hu(lu(e)),tm=e=>zl(String(e));function nm(e,t){if(!e||!Xu(e).has(t))return null;const n=vf(Pu(e),t);if(!n||1!==Math.max(...n.keys()))return null;const r=n.get(1);return!fu(r)||r.q.isZero?null:{a:r.q,node:e}}function rm(e){return Zl(e)&&"^"===e.op&&Cl(e.args[1])&&Number.isInteger(Number(e.args[1].value))?{base:e.args[0],n:Number(e.args[1].value)}:{base:e,n:1}}function sm(e,t,n){const[r,s]=t.args,i=Yu(Pu(r)).map(Hu).map(rm),o=(e,...t)=>Zl(e.base)&&t.includes(e.base.op),a=(r,s,i,o={})=>({node:i,steps:[e.step(r,s,["rewrite"],t,i,{v:n,...o})]});if(2===i.length&&i.every(e=>1===e.n)){const e=i.find(e=>Zl(e.base)&&"^"===e.base.op&&"sym"===e.base.args[0].type&&"e"===e.base.args[0].token),t=i.find(e=>o(e,"sin","cos")),r=e&&nm(e.base.args[1],n),s=t&&nm(t.base.args[0],n);if(r&&s){const[n,i]=[r.a,s.a],o=n.mul(n).add(i.mul(i)),[l,u]=[Tl("sin",[s.node]),Tl("cos",[s.node])],c="sin"===t.base.op?Tl("-",[Tl("*",[em(n),l]),Tl("*",[em(i),u])]):Tl("+",[Tl("*",[em(n),u]),Tl("*",[em(i),l])]);return a("integrate.parts-twice","By parts twice",Wu(Tl("/",[Tl("*",[e.base,c]),em(o)])),{e:e.base,t:t.base})}}if(2===i.length&&i.every(e=>1===e.n&&o(e,"sin","cos")&&nm(e.base.args[0],n))&&i[0].base.args[0].s!==i[1].base.args[0].s){const[e,t]="sin"===i[0].base.op?i:[i[1],i[0]],[n,r]=[e.base.args[0],t.base.args[0]],o=(e,t)=>Tl(e,[Tl(t,[n,r])]);let l;l="sin"===e.base.op&&"cos"===t.base.op?Tl("+",[o("sin","+"),o("sin","-")]):"cos"===e.base.op?Tl("+",[o("cos","-"),o("cos","+")]):Tl("-",[o("cos","-"),o("cos","+")]);return a("integrate.product-to-sum","Product to sum",Wu(Qp(Tl("/",[l,tm(2)]),s)))}const l=i.find(e=>o(e,"sin")),u=i.find(e=>o(e,"cos")),c=!l||!u||l.base.args[0].s===u.base.args[0].s;if((l||u)&&c&&i.every(e=>e===l||e===u)&&[l,u].every(e=>!e||e.n>=0))for(const[t,r]of[[u,"sin"],[l,"cos"]]){if(!t||t.n<3||t.n%2==0)continue;const o=t.base.args[0],l=(t.n-1)/2,u=i.filter(e=>e!==t).map(e=>Tl("^",[e.base,tm(e.n)])),c=[...u,Tl("^",[Tl("-",[tm(1),Tl("^",[Tl(r,[o]),tm(2)])]),tm(l)]),Tl(t.base.op,[o])].reduce((e,t)=>Tl("*",[e,t])),h=Wu(Qp(c,s)),f=a("integrate.odd-power","An odd power",h,{f:t.base,other:Tl(r,[o])});if("sym"!==o.type||o.token!==n)return f;const p="u"===n?"t":"u",m=u.length?i.find(e=>e!==t).n:0;if(2*l+m>100)throw new Hl(`a power this high (${t.n+m}) is not integrated here`);const d="sin"===t.base.op?-1:1,g=Tl(r,[o]),v=Tl("*",[Tl("^",[Tl("-",[tm(1),Tl("^",[Il(p),tm(2)])]),tm(l)]),Tl("^",[Il(p),tm(m)])]),b=Wu(Qp(d<0?Tl("neg",[v]):v,Il(p))),y=vf(df(Pu(v)),p);if(!y)return f;const w=[...y].map(([e,t])=>Tl("*",[Hu(t),Tl("/",[Tl("^",[g,tm(e+1)]),tm(e+1)])])).reduce((e,t)=>Tl("+",[e,t])),x=Wu(d<0?Tl("neg",[w]):w);return{node:x,steps:[...f.steps,e.step("integrate.u-substitution","Substitute",["substitute"],h,b,{u:Il(p),inside:g,du:d<0?Tl("neg",[t.base]):t.base,v:n}),e.step("integrate.back","Back to "+n,["substitute"],b,x,{u:Il(p),inside:g})]}}if(1===i.length&&i[0].n>=3&&o(i[0],"sec","csc")&&"sym"===i[0].base.args[0].type&&i[0].base.args[0].token===n){const{base:e,n:t}=i[0],n=e.args[0],r="sec"===e.op?Tl("tan",[n]):Tl("cot",[n]),o=Tl("/",[Tl("*",[Tl("^",[e,tm(t-2)]),r]),tm(t-1)]),l=Tl("*",[Tl("/",[tm(t-2),tm(t-1)]),Qp(Tl("^",[e,tm(t-2)]),s)]);return a("integrate.reduction","Reduction formula",Wu(Tl("+",["sec"===e.op?o:Tl("neg",[o]),l])),{f:e,n:tm(t)})}const h=e=>{if(!Zl(e)||"sqrt"!==e.op)return null;const t=vf(Pu(e.args[0]),n);if(!t||2!==t.size||!t.has(2)||!t.has(0))return null;const[r,s]=[t.get(2),t.get(0)];return!fu(r)||!fu(s)||r.q.sign>=0||s.q.sign<=0?null:{k:r.q.neg(),c:s.q,root:e}},f=Il(n),p=e=>Tl("sqrt",[em(e)]),m=h(r),d=Zl(r)&&"/"===r.op&&Cl(r.args[0])&&1===r.args[0].value?h(r.args[1]):null;if(m||d){const{k:e,c:t,root:n}=m??d,r=Tl("arcsin",[Tl("*",[f,p(e.div(t))])]);return a("integrate.trig-substitution","A trig substitution",Wu(m?Tl("+",[Tl("/",[Tl("*",[f,n]),tm(2)]),Tl("*",[Tl("/",[em(t),Tl("*",[tm(2),p(e)])]),r])]):Tl("/",[r,p(e)])),{x:f,a:Wu(p(t.div(e)))})}return null}function im(e,t,n,r,s=!1){const{num:i,den:o}=Cf(n);if(!bf(o,r))return null;const a=yf(vf(i,r)),l=yf(vf(o,r));if(!a||!l||l.length<2)return null;const u=Pu(Il(r)),c=e=>wf(e,r);if(a.length>=l.length){const{q:n,r:s}=Af(a,l),i=Qp(Hu(ku([c(n),Zu(c(s),c(l))])),Il(r));return{node:i,steps:[e.step("integrate.divide","Divide the polynomials",["divide"],t,i,{})]}}if(s)return null;const{roots:h,rest:f}=Mf(l),p=new Set(h.map(String)).size===h.length,m=3===f.length&&f[1].mul(f[1]).sub(Yl.of(4).mul(f[0]).mul(f[2])).sign<0;if(!p||1!==f.length&&!m||!h.length&&!m)return null;const d=(e=>e.length<=1?[Yl.ZERO]:e.slice(1).map((e,t)=>e.mul(Yl.of(t+1))))(l),g=h.map(e=>$f(a,e).div($f(d,e))),v=h.map((e,t)=>Zu(lu(g[t]),ku([u,lu(e.neg())])));if(!m){const n=Qp(Hu(ku(v)),Il(r));return{node:n,steps:[e.step("integrate.partial-fractions","Partial fractions",["partial-fractions"],t,n,{})]}}let b=a;h.forEach((e,t)=>{b=lm(b,am(Af(l,[e.neg(),Yl.of(1)]).q,g[t]))});const y=h.reduce((e,t)=>om(e,[t.neg(),Yl.of(1)]),[Yl.of(1)]),{q:w}=Af(b,y),[x,$]=[w[0]??Yl.ZERO,w[1]??Yl.ZERO],[k,q,M]=Af(l,y).q,A=Yl.of(4).mul(M).mul(k).sub(q.mul(q)),S=wf([k,q,M],r),N=$.div(Yl.of(2).mul(M)),O=x.sub($.mul(q).div(Yl.of(2).mul(M))),E=Tl("sqrt",[em(A)]),I=Tl("*",[em(N),Tl("ln",[Tl("abs",[Hu(S)])])]),z=Tl("*",[Tl("/",[Tl("*",[tm(2),em(O)]),E]),Tl("arctan",[Tl("/",[Hu(wf([q,M.mul(Yl.of(2))],r)),E])])]),_=v.length?Qp(Hu(ku(v)),Il(r)):tm(0),j=Wu(Tl("+",[Tl("+",[_,I]),z]));return{node:j,steps:[e.step("integrate.complete-square","Complete the square",["partial-fractions"],t,j,{Q:Hu(S)})]}}const om=(e,t)=>{const n=Array.from({length:e.length+t.length-1},()=>Yl.ZERO);return e.forEach((e,r)=>t.forEach((t,s)=>{n[r+s]=n[r+s].add(e.mul(t))})),n},am=(e,t)=>e.map(e=>e.mul(t)),lm=(e,t)=>Array.from({length:Math.max(e.length,t.length)},(n,r)=>(e[r]??Yl.ZERO).sub(t[r]??Yl.ZERO));function um(e,t,n){return e.s===t.s?n:Zl(e)?Tl(e.op,e.args.map(e=>um(e,t,n))):e}const cm=(e,t)=>{const n=vf(e,t);return Boolean(n)&&[...n.values()].every(e=>!bf(e,t))&&Math.max(...n.keys())>=1};function hm(e,t,n,r,s,i){if([r,s].some(e=>jp(e).inf))return function(e,t,n,r,s,i){const o=[r,s].map(e=>jp(e)),a=e=>e.inf?e.inf*(1/0):Mh(e.fin,{digits:20}).number,[l,u]=o.map(a).sort((e,t)=>e-t);for(const t of i?fm(i,n):[]){let r=[];try{r=e.solve(Tl("=",[t,zl("0")]),n,{steps:!1}).solutions}catch{continue}for(const t of r){const r=Mh(t,{digits:20});if(Number.isFinite(r.number)&&!r.im&&r.number>l&&r.number<u)throw new Hl(`the integrand has no value at ${n} = ${e.format(t)}, between the limits: split the integral there`)}}const c=(r,s,i)=>{if(!s.inf)try{const e=Wu(Vf(t,n,r));if(Number.isFinite(Mh(e,{digits:15}).number))return e}catch{}const o=e.limit(t,n,r,{steps:!1,side:s.inf?void 0:i});if(!o.exists)throw new Hl(`the integral diverges: as ${n} → ${e.format(r)}, ${e.format(t)} has no limit (${o.reason})`);if(o.infinite)throw new Hl(`the integral diverges: as ${n} → ${e.format(r)}, ${e.format(t)} goes to ${o.text}`);return o.result},h=a(o[0])<a(o[1]),[f,p]=[c(r,o[0],h?"right":"left"),c(s,o[1],h?"left":"right")],m=Wu(Tl("-",[p,f])),d=Tl("-",[p,f]);return{value:m,shown:d,step:e.step("integrate.improper","Limits at the ends",["evaluate"],t,d,{a:r,b:s,F:t,v:n})}}(e,t,n,r,s,i);if(i&&!Xu(r).size&&!Xu(s).size){const o=Mh(r,{digits:20}).number,a=Mh(s,{digits:20}).number,l=[...Xu(i)].filter(e=>e!==n);if(!l.length){const[r,s]=o<=a?[o,a]:[a,o];for(const o of fm(i,n)){let i=[];try{i=e.solve(Tl("=",[o,zl("0")]),n,{steps:!1}).solutions}catch{continue}for(const o of i){const i=Mh(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 Hl(`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=Mh(Wu(Vf(t,n,o)),{digits:15}).number}catch{}if(!Number.isFinite(a))throw new Hl(`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=Mh(Vf(i,n,zl(t.toFixed(15))),{digits:15}).number;if(!Number.isFinite(e))throw new Hl("not finite")}catch(e){throw new Hl(`the integrand has no value at ${n} = ${t.toPrecision(6)}, between the limits, so F(b) - F(a) would be wrong`)}}}const o=e=>Wu(Vf(t,n,e)),a=Wu(Tl("-",[o(s),o(r)])),l=Tl("-",[o(s),o(r)]);return{value:a,shown:l,step:e.step("integrate.evaluate","Between the limits",["evaluate"],t,l,{a:r,b:s,F:t,v:n})}}function fm(e,t){const n=[],r={tan:"cos",sec:"cos",csc:"sin",cot:"sin"};return Dl(e,"pre").forEach(({node:e})=>{if(!Zl(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&&Zl(e.args[1])&&"neg"===e.args[1].op?s=e.args[0]:r[e.op]&&(s=Tl(r[e.op],[e.args[0]])),s&&Xu(s).has(t)&&!n.some(e=>e.s===s.s)&&n.push(s)}),n}const pm={"=":1,"≠":1,"<":1,">":1,"≤":1,"≥":1,"+":2,"-":2,"±":2,"*":3,"/":3,neg:4,pm:4,"^":5},mm={pi:"π","≤":"≤","≥":"≥"};function dm(e){return wm(e).text}function gm(e,t,n=!1){return e.prec<t||n&&e.prec===t?`(${e.text})`:e.text}const vm=e=>"op"===e.type?e.op:null,bm=e=>e.text.startsWith("-"),ym={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]};function wm(e){if("num"===e.type)return{text:e.token,prec:e.token.startsWith("-")?4:9};if("sym"===e.type)return{text:mm[e.token]??e.token,prec:9};const t=e.args.map(wm),n=pm[e.op];switch(e.op){case"+":case"-":case"±":{const r="+"===e.op&&["+","-"].includes(vm(e.args[1])),s=bm(t[1])?`(${t[1].text})`:r?t[1].text:gm(t[1],n,!0);return{text:`${gm(t[0],n)} ${"±"===e.op?"±":e.op} ${s}`,prec:n}}case"*":{const r=gm(t[0],n),s=bm(t[1])?`(${t[1].text})`:"*"===vm(e.args[1])?t[1].text:gm(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:`${gm(t[0],n)}/${gm(t[1],n,!0)}`,prec:n};case"^":return{text:`${gm(t[0],n+1)}^${gm(t[1],n)}`,prec:n};case"neg":return{text:`-${gm(t[0],3)}`,prec:4};case"pm":return{text:`±${gm(t[0],4)}`,prec:4};case"!":return{text:`${gm(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:`${gm(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:`${ym[e.op][0]}${t.map(e=>e.text).join(", ")}${ym[e.op][1]}`,prec:9};case"&":return{text:`${t[0].text} and ${t[1].text}`,prec:0};default:return void 0!==n?{text:`${gm(t[0],n)} ${e.op} ${gm(t[1],n,!0)}`,prec:n}:{text:`${e.op.replace(/^\\:?/,"")}(${t.map(e=>e.text).join(", ")})`,prec:9}}}const xm=['name: Differentiation\n\n# `u v der` means d(u)/dv (MathZetta\'s postfix: mathzetta/docs/postfix.md). Every rule here rewrites one derivative into smaller\n# derivatives, so differentiating always terminates: the expressions sitting\n# under a `D` get strictly smaller at every step.\n#\n# The variable is a slot, not a fixed letter, so these rules work for d/dx,\n# d/dt or anything else. That is what freeOf and dependsOn are for: they ask\n# whether one operand mentions whatever the variable slot bound to.\n#\n# Where two rules share a structure key, requirements keep them apart and\n# priority picks the one that reads better. The constant-multiple rule outranks\n# the product rule for exactly that reason.\n\nrules:\n # ---- the two base cases ----------------------------------------------\n - id: d-constant\n name: Derivative of a constant\n mode: differentiate\n pattern: c v der\n require:\n - [freeOf, c, v]\n output: "0"\n priority: 10\n explain: "{c} does not change when {v} changes, so its rate of change is 0."\n tags: [base, minor]\n\n - id: d-variable\n name: Derivative of the variable\n mode: differentiate\n pattern: u v der\n require:\n - [sameAs, u, v]\n output: "1"\n priority: 10\n explain: "{v} changes exactly as fast as itself, so the rate is 1."\n tags: [base, minor]\n\n # ---- splitting a derivative into smaller ones ------------------------\n - id: d-sum\n name: Sum rule\n mode: differentiate\n pattern: u w + v der\n output: u v der w v der +\n explain: "Differentiate {u} and {w} separately, then add the two results."\n tags: [split, minor]\n\n - id: d-difference\n name: Difference rule\n mode: differentiate\n pattern: u w - v der\n output: u v der w v der -\n explain: "Differentiate {u} and {w} separately, then subtract the second from the first."\n tags: [split, minor]\n\n - id: d-negate\n name: Derivative of a negative\n mode: differentiate\n pattern: u neg v der\n output: u v der neg\n explain: "The minus sign just carries through to the derivative of {u}."\n tags: [split, minor]\n\n - id: d-constant-multiple\n name: Constant multiple rule\n mode: differentiate\n pattern: c u * v der\n commutative: true\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n output: c u v der *\n priority: 5\n explain: "{c} is only a scale factor, so it comes along unchanged while {u} is differentiated."\n tags: [split, minor]\n\n - id: d-constant-divisor\n name: Dividing by a constant\n mode: differentiate\n pattern: u c / v der\n require:\n - [freeOf, c, v]\n output: u v der c /\n priority: 5\n explain: "Dividing by {c} is only a scale factor, so differentiate {u} and keep the division."\n tags: [split, minor]\n\n - id: d-product\n name: Product rule\n mode: differentiate\n pattern: u w * v der\n require:\n - [dependsOn, u, v]\n - [dependsOn, w, v]\n output: u v der w * u w v der * +\n explain: "Differentiate {u} and keep {w}, then keep {u} and differentiate {w}, and add the two."\n tags: [split]\n\n - id: d-quotient\n name: Quotient rule\n mode: differentiate\n pattern: u w / v der\n output: u v der w * u w v der * - w 2 ^ /\n explain: "Apply the quotient rule: bottom times the derivative of the top, minus top times the derivative of the bottom, all over {w} squared."\n tags: [split]\n\n # ---- powers -----------------------------------------------------------\n - id: d-power-of-variable\n name: Power rule\n mode: differentiate\n pattern: u n ^ v der\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n output: n u n 1 - ^ *\n fold: true\n priority: 6\n explain: "Bring the {n} down in front and drop the power by one."\n tags: [power]\n\n - id: d-power-chain\n name: Power rule with the chain rule\n mode: differentiate\n pattern: u n ^ v der\n require:\n - [freeOf, n, v]\n - [dependsOn, u, v]\n output: n u n 1 - ^ * u v der *\n fold: true\n explain: "Bring the {n} down and drop the power by one, then multiply by the derivative of {u}."\n tags: [power, chain]\n\n - id: d-exponential-base\n name: Derivative of a constant to a power\n mode: differentiate\n pattern: a u ^ v der\n require:\n - [freeOf, a, v]\n - [dependsOn, u, v]\n output: a u ^ a ln * u v der *\n explain: "A constant base gives itself back, multiplied by the natural log of {a} and the derivative of {u}."\n tags: [power, chain]\n\n # ---- the standard functions, each with its chain-rule factor ---------\n # e^u is `=e u ^`: the base is the literal symbol e. Outranks the general\n # a^u rule (which would give e^u · ln e · u\').\n - id: d-exp\n name: Derivative of e to a power\n mode: differentiate\n pattern: =e u ^ v der\n require:\n - [dependsOn, u, v]\n output: =e u ^ u v der *\n priority: 7\n explain: "e to a power is its own derivative, times the derivative of {u}."\n tags: [chain]\n\n - id: d-ln\n name: Derivative of a natural log\n mode: differentiate\n pattern: u ln v der\n output: u v der u /\n explain: "A natural log differentiates to 1 over {u}, times the derivative of {u}."\n tags: [chain]\n\n - id: d-sqrt\n name: Derivative of a square root\n mode: differentiate\n pattern: u sqrt v der\n output: u v der 2 u sqrt * /\n explain: "A square root differentiates to 1 over twice the square root of {u}, times the derivative of {u}."\n tags: [chain]\n\n - id: d-sin\n name: Derivative of sine\n mode: differentiate\n pattern: u sin v der\n output: u cos u v der *\n explain: "Sine differentiates to cosine, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-cos\n name: Derivative of cosine\n mode: differentiate\n pattern: u cos v der\n output: u sin u v der * neg\n explain: "Cosine differentiates to negative sine, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-tan\n name: Derivative of tangent\n mode: differentiate\n pattern: u tan v der\n output: u v der u cos 2 ^ /\n explain: "Tangent differentiates to 1 over cosine squared of {u}, times the derivative of {u}."\n tags: [chain, trig]\n\n # ---- the rest of the standard functions -----------------------------\n - id: d-csc\n name: Derivative of cosecant\n mode: differentiate\n pattern: u csc v der\n output: u csc u cot * u v der * neg\n explain: "Cosecant differentiates to negative cosecant times cotangent, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-sec\n name: Derivative of secant\n mode: differentiate\n pattern: u sec v der\n output: u sec u tan * u v der *\n explain: "Secant differentiates to secant times tangent, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-cot\n name: Derivative of cotangent\n mode: differentiate\n pattern: u cot v der\n output: u v der u sin 2 ^ / neg\n explain: "Cotangent differentiates to negative 1 over sine squared of {u}, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-arcsin\n name: Derivative of arcsine\n mode: differentiate\n pattern: u arcsin v der\n output: u v der 1 u 2 ^ - sqrt /\n explain: "Inverse sine differentiates to 1 over the square root of 1 minus {u} squared, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-arccos\n name: Derivative of arccosine\n mode: differentiate\n pattern: u arccos v der\n output: u v der 1 u 2 ^ - sqrt / neg\n explain: "Inverse cosine differentiates to negative 1 over the square root of 1 minus {u} squared, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-arctan\n name: Derivative of arctangent\n mode: differentiate\n pattern: u arctan v der\n output: u v der 1 u 2 ^ + /\n explain: "Inverse tangent differentiates to 1 over 1 plus {u} squared, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-arcsec\n name: Derivative of arcsecant\n mode: differentiate\n pattern: u arcsec v der\n output: u v der u abs u 2 ^ 1 - sqrt * /\n explain: "Inverse secant differentiates to 1 over the absolute value of {u} times the square root of {u} squared minus 1, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-arccsc\n name: Derivative of arccosecant\n mode: differentiate\n pattern: u arccsc v der\n output: u v der u abs u 2 ^ 1 - sqrt * / neg\n explain: "Inverse cosecant differentiates to negative 1 over the absolute value of {u} times the square root of {u} squared minus 1, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-arccot\n name: Derivative of arccotangent\n mode: differentiate\n pattern: u arccot v der\n output: u v der 1 u 2 ^ + / neg\n explain: "Inverse cotangent differentiates to negative 1 over 1 plus {u} squared, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-sinh\n name: Derivative of hyperbolic sine\n mode: differentiate\n pattern: u sinh v der\n output: u cosh u v der *\n explain: "Hyperbolic sine differentiates to hyperbolic cosine, times the derivative of {u}."\n tags: [chain, hyperbolic]\n\n - id: d-cosh\n name: Derivative of hyperbolic cosine\n mode: differentiate\n pattern: u cosh v der\n output: u sinh u v der *\n explain: "Hyperbolic cosine differentiates to hyperbolic sine — no minus sign, unlike cosine — times the derivative of {u}."\n tags: [chain, hyperbolic]\n\n - id: d-tanh\n name: Derivative of hyperbolic tangent\n mode: differentiate\n pattern: u tanh v der\n output: u v der u cosh 2 ^ /\n explain: "Hyperbolic tangent differentiates to 1 over hyperbolic cosine squared of {u}, times the derivative of {u}."\n tags: [chain, hyperbolic]\n\n - id: d-arcsinh\n name: Derivative of inverse hyperbolic sine\n mode: differentiate\n pattern: u arcsinh v der\n output: u v der u 2 ^ 1 + sqrt /\n explain: "Inverse hyperbolic sine differentiates to 1 over the square root of {u} squared plus 1, times the derivative of {u}."\n tags: [chain, hyperbolic]\n\n - id: d-arccosh\n name: Derivative of inverse hyperbolic cosine\n mode: differentiate\n pattern: u arccosh v der\n output: u v der u 2 ^ 1 - sqrt /\n explain: "Inverse hyperbolic cosine differentiates to 1 over the square root of {u} squared minus 1, times the derivative of {u}."\n tags: [chain, hyperbolic]\n\n - id: d-arctanh\n name: Derivative of inverse hyperbolic tangent\n mode: differentiate\n pattern: u arctanh v der\n output: u v der 1 u 2 ^ - /\n explain: "Inverse hyperbolic tangent differentiates to 1 over 1 minus {u} squared, times the derivative of {u}."\n tags: [chain, hyperbolic]\n\n # log base a: `a u log` in MathZetta\'s postfix\n - id: d-log\n name: Derivative of a logarithm\n mode: differentiate\n pattern: a u log v der\n require:\n - [freeOf, a, v]\n output: u v der u a ln * /\n explain: "A base {a} logarithm differentiates to 1 over {u} times the natural log of {a}, times the derivative of {u}."\n tags: [chain]\n\n - id: d-abs\n name: Derivative of an absolute value\n mode: differentiate\n pattern: u abs v der\n output: u u abs / u v der *\n explain: "The absolute value keeps the sign of {u}: {u} over its absolute value, times the derivative of {u}."\n tags: [chain]\n\n # n-th root: `n u root`\n - id: d-root\n name: Derivative of a root\n mode: differentiate\n pattern: n u root v der\n require:\n - [freeOf, n, v]\n output: u v der n n u root n 1 - ^ * /\n fold: true\n explain: "Write the root as a power, then bring the power down and drop it by one: the derivative of {u}, over {n} times the same root of {u} to the power {n} minus 1."\n tags: [chain]\n','name: More derivatives\n\n# Derivative rules the CAS adds to rules/calculus.yaml (which calcvidnew also uses).\n\nrules:\n - id: d-general-power\n name: A power with the variable in both places\n mode: differentiate\n pattern: u w ^ v der\n require:\n - [dependsOn, u, v]\n - [dependsOn, w, v]\n output: u w ^ w v der u ln * w u v der * u / + *\n explain: "The variable is in the base and in the exponent, so write {u}^{w} as e to the {w} times the natural log of {u}. By the chain rule, the derivative is the same power, times the derivative of that exponent."\n tags: [chain]\n','name: Integrals\n\n# mode: integrate. `f v 2 int` is ∫ f dv (MathZetta\'s postfix; the 2 counts f and v).\n# Each rule turns one integral into smaller ones, or into an answer. The CAS also\n# tries, when no rule fits: multiplying out, a linear substitution (∫ f(ax + b) dx\n# from the rule for ∫ f(u) du), and integration by parts for polynomial × e^, sin,\n# cos, ln, arctan. Definite integrals are the antiderivative between the limits.\n#\n# Patterns see the normal form: 1/x is "1 x /", x^-2 is "1 x 2 ^ /", √x is "x sqrt",\n# 1/√(1 - x²) is "1 x 2 ^ neg 1 + sqrt /".\n\nrules:\n # ---- splitting -----------------------------------------------------------\n - id: i-sum\n name: Sum rule\n mode: integrate\n pattern: u w + v 2 int\n output: u v 2 int w v 2 int +\n explain: "Integrate {u} and {w} separately, and add."\n tags: [split, minor]\n\n - id: i-difference\n name: Difference rule\n mode: integrate\n pattern: u w - v 2 int\n output: u v 2 int w v 2 int -\n explain: "Integrate {u} and {w} separately, and subtract."\n tags: [split, minor]\n\n - id: i-negate\n name: A minus sign\n mode: integrate\n pattern: u neg v 2 int\n output: u v 2 int neg\n explain: "The minus sign comes out of the integral."\n tags: [split, minor]\n\n - id: i-constant-multiple\n name: Constant multiple\n mode: integrate\n pattern: c u * v 2 int\n commutative: true\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n output: c u v 2 int *\n priority: 5\n explain: "{c} doesn\'t change with {v}, so it comes out of the integral."\n tags: [split]\n\n - id: i-constant-divisor\n name: Dividing by a constant\n mode: integrate\n pattern: u c / v 2 int\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n output: u v 2 int c /\n priority: 5\n explain: "Dividing by {c} comes out of the integral."\n tags: [split]\n\n - id: i-constant-over\n name: A constant over something\n mode: integrate\n pattern: c u / v 2 int\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n when:\n c: [notOne]\n output: c 1 u / v 2 int *\n priority: 4\n explain: "{c} comes out of the integral, leaving ∫ 1/{u}."\n tags: [split]\n\n # ---- the table -----------------------------------------------------------\n - id: i-constant\n name: Integral of a constant\n mode: integrate\n pattern: c v 2 int\n require:\n - [freeOf, c, v]\n output: c v *\n priority: 10\n explain: "A constant {c} integrates to {c}·{v}."\n tags: [base]\n\n - id: i-variable\n name: Integral of the variable\n mode: integrate\n pattern: u v 2 int\n require:\n - [sameAs, u, v]\n output: v 2 ^ 2 /\n priority: 10\n explain: "∫ {v} d{v} = {v}²/2."\n tags: [base]\n\n - id: i-power\n name: Power rule\n mode: integrate\n pattern: u n ^ v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n when:\n n: [notMinusOne]\n output: v n 1 + ^ n 1 + /\n explain: "Add 1 to the power and divide by the new power: {result}."\n tags: [power]\n\n - id: i-reciprocal\n name: Integral of 1/x\n mode: integrate\n pattern: 1 u / v 2 int\n require:\n - [sameAs, u, v]\n output: v abs ln\n explain: "∫ 1/{v} d{v} = ln|{v}| (the power rule can\'t divide by 0 here)."\n tags: [log]\n\n - id: i-reciprocal-power\n name: Power rule (a power below)\n mode: integrate\n pattern: 1 u n ^ / v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n when:\n n: [notOne]\n output: v 1 n - ^ 1 n - /\n explain: "1/{v}^{n} is {v}^(-{n}): add 1 to the power and divide by it."\n tags: [power]\n\n - id: i-sqrt\n name: Integral of a square root\n mode: integrate\n pattern: u sqrt v 2 int\n require:\n - [sameAs, u, v]\n output: 2 v 3 2 / ^ * 3 /\n explain: "√{v} is {v}^(1/2): add 1 to the power and divide by 3/2."\n tags: [power]\n\n - id: i-reciprocal-sqrt\n name: Integral of 1/√x\n mode: integrate\n pattern: 1 u sqrt / v 2 int\n require:\n - [sameAs, u, v]\n output: 2 v sqrt *\n explain: "1/√{v} is {v}^(-1/2): add 1 to the power and divide by 1/2."\n tags: [power]\n\n - id: i-root\n name: Integral of a root\n mode: integrate\n pattern: n u root v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n output: v 1 n / 1 + ^ 1 n / 1 + /\n explain: "The {n}th root of {v} is {v}^(1/{n}): add 1 to the power and divide by it."\n tags: [power]\n\n - id: i-exp\n name: Integral of e^x\n mode: integrate\n pattern: =e u ^ v 2 int\n require:\n - [sameAs, u, v]\n output: =e v ^\n explain: "e^{v} is its own integral."\n tags: [exp]\n\n - id: i-exponential\n name: Integral of a^x\n mode: integrate\n pattern: a u ^ v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, a, v]\n output: a v ^ a ln /\n explain: "∫ {a}^{v} d{v} = {a}^{v} / ln {a}."\n tags: [exp]\n\n - id: i-ln\n name: Integral of ln x\n mode: integrate\n pattern: u ln v 2 int\n require:\n - [sameAs, u, v]\n output: v v ln * v -\n explain: "By parts: ∫ ln {v} d{v} = {v} ln {v} - {v}."\n tags: [log]\n\n - { id: i-sin, name: Integral of sin, mode: integrate, pattern: u sin v 2 int, require: [[sameAs, u, v]], output: v cos neg, tags: [trig], explain: "The derivative of -cos {v} is sin {v}." }\n - { id: i-cos, name: Integral of cos, mode: integrate, pattern: u cos v 2 int, require: [[sameAs, u, v]], output: v sin, tags: [trig], explain: "The derivative of sin {v} is cos {v}." }\n - { id: i-tan, name: Integral of tan, mode: integrate, pattern: u tan v 2 int, require: [[sameAs, u, v]], output: v cos abs ln neg, tags: [trig], explain: "tan = sin/cos, and -ln|cos {v}| differentiates to it." }\n - { id: i-sec-squared, name: Integral of sec², mode: integrate, pattern: 1 u cos 2 ^ / v 2 int, require: [[sameAs, u, v]], output: v tan, tags: [trig], explain: "The derivative of tan {v} is 1/cos²{v}." }\n - { id: i-sec-squared-written, name: Integral of sec², mode: integrate, pattern: u sec 2 ^ v 2 int, require: [[sameAs, u, v]], output: v tan, tags: [trig], explain: "The derivative of tan {v} is sec²{v}." }\n - { id: i-csc-squared, name: Integral of csc², mode: integrate, pattern: 1 u sin 2 ^ / v 2 int, require: [[sameAs, u, v]], output: v cot neg, tags: [trig], explain: "The derivative of -cot {v} is 1/sin²{v}." }\n - { id: i-sin-squared, name: Integral of sin², mode: integrate, pattern: u sin 2 ^ v 2 int, require: [[sameAs, u, v]], output: v 2 / 2 v * sin 4 / -, tags: [trig], explain: "sin²{v} = (1 - cos 2{v})/2, which integrates term by term." }\n - { id: i-cos-squared, name: Integral of cos², mode: integrate, pattern: u cos 2 ^ v 2 int, require: [[sameAs, u, v]], output: v 2 / 2 v * sin 4 / +, tags: [trig], explain: "cos²{v} = (1 + cos 2{v})/2, which integrates term by term." }\n - { id: i-sec, name: Integral of sec, mode: integrate, pattern: u sec v 2 int, require: [[sameAs, u, v]], output: v sec v tan + abs ln, tags: [trig], explain: "The derivative of ln|sec {v} + tan {v}| is sec {v}." }\n - { id: i-csc, name: Integral of csc, mode: integrate, pattern: u csc v 2 int, require: [[sameAs, u, v]], output: v csc v cot + abs ln neg, tags: [trig], explain: "The derivative of -ln|csc {v} + cot {v}| is csc {v}." }\n - { id: i-cot, name: Integral of cot, mode: integrate, pattern: u cot v 2 int, require: [[sameAs, u, v]], output: v sin abs ln, tags: [trig], explain: "cot = cos/sin, and ln|sin {v}| differentiates to it." }\n - { id: i-sec-tan, name: Integral of sec·tan, mode: integrate, pattern: u sec u tan * v 2 int, commutative: true, require: [[sameAs, u, v]], output: v sec, tags: [trig], explain: "The derivative of sec {v} is sec {v} tan {v}." }\n - { id: i-csc-cot, name: Integral of csc·cot, mode: integrate, pattern: u csc u cot * v 2 int, commutative: true, require: [[sameAs, u, v]], output: v csc neg, tags: [trig], explain: "The derivative of -csc {v} is csc {v} cot {v}." }\n - { id: i-sinh, name: Integral of sinh, mode: integrate, pattern: u sinh v 2 int, require: [[sameAs, u, v]], output: v cosh, tags: [trig], explain: "The derivative of cosh {v} is sinh {v}." }\n - { id: i-cosh, name: Integral of cosh, mode: integrate, pattern: u cosh v 2 int, require: [[sameAs, u, v]], output: v sinh, tags: [trig], explain: "The derivative of sinh {v} is cosh {v}." }\n - { id: i-arctan, name: Integral of 1/(1 + x²), mode: integrate, pattern: 1 u 2 ^ 1 + / v 2 int, require: [[sameAs, u, v]], output: v arctan, tags: [trig], explain: "The derivative of arctan {v} is 1/(1 + {v}²)." }\n - { id: i-arcsin, name: Integral of 1/√(1 - x²), mode: integrate, pattern: 1 u 2 ^ neg 1 + sqrt / v 2 int, require: [[sameAs, u, v]], output: v arcsin, tags: [trig], explain: "The derivative of arcsin {v} is 1/√(1 - {v}²)." }\n','name: Values and identities\n\n# The CAS\'s simplify rules (mode: simplify). They see expressions in normal form\n# (src/cas/form.js), as drawn: x/2, 2x - 3, -x, √x is "x sqrt",\n# ∛x is "3 x root", π/6 is "=pi 6 /", 2π/3 is "2 =pi * 3 /", e^x is "=e x ^".\n#\n# - a word is a slot (u, v, n …); a fixed symbol is written =pi, =e\n# - a number is itself; "1 2 /" is ½\n# - arithmetic (2 + 3, x + x, √8 = 2√2) is done for you before and after every rule\n# - a rule for a sum or product of two parts also fires on any two parts of a longer one\n# - tags pick what a step list shows (steps: \'brief\' hides value, identity, tidy …)\n#\n# To change one: copy it into a file of your own with the same id and edit it;\n# to turn one off: give its id with enabled: false. createCAS({ rules: [yours] }).\n\nrules:\n # ---- logs and exponentials -------------------------------------------\n - id: ln-one\n name: Log of 1\n pattern: 1 ln\n output: "0"\n explain: "e^0 = 1, so ln 1 = 0."\n tags: [value]\n\n - id: ln-e\n name: Log of e\n pattern: =e ln\n output: "1"\n explain: "e^1 = e, so ln e = 1."\n tags: [value]\n\n - id: ln-exp\n name: Log undoes e to a power\n pattern: =e u ^ ln\n output: u\n explain: "ln and e^ undo each other: ln(e^{u}) = {u}."\n tags: [inverse]\n\n - id: exp-ln\n name: e to a power undoes the log\n pattern: =e u ln ^\n output: u\n explain: "e^ and ln undo each other: e^(ln {u}) = {u} (for {u} > 0)."\n tags: [inverse]\n\n - id: exp-multiple-ln\n name: A multiple of a log in a power\n pattern: =e n u ln * ^\n when:\n n: [isRational]\n output: u n ^\n explain: "e^({n} ln {u}) = (e^(ln {u}))^{n} = {result}."\n tags: [inverse]\n\n - id: log-same-base\n name: Log of its own base\n pattern: b b log\n output: "1"\n explain: "{b}^1 = {b}, so the log of {b} to base {b} is 1."\n tags: [value]\n\n - id: log-of-power\n name: Log undoes a power of its base\n pattern: b b u ^ log\n output: u\n explain: "log base {b} and {b}^ undo each other."\n tags: [inverse]\n\n - id: power-of-log\n name: A power undoes the log to its base\n pattern: b b u log ^\n output: u\n explain: "{b}^(log base {b} of {u}) = {u}."\n tags: [inverse]\n\n # ---- roots and absolute value --------------------------------------------\n - id: sqrt-of-square\n name: Square root of a square\n pattern: u 2 ^ sqrt\n output: u abs\n explain: "√({u}²) is the size of {u}, whatever its sign: |{u}|."\n tags: [identity]\n\n - id: abs-squared\n name: Absolute value squared\n pattern: u abs 2 ^\n output: u 2 ^\n explain: "Squaring removes the sign anyway: |{u}|² = {u}²."\n tags: [identity]\n\n - id: abs-of-abs\n name: Absolute value twice\n pattern: u abs abs\n output: u abs\n explain: "|{u}| is never negative, so its absolute value is itself."\n tags: [identity]\n\n - id: abs-positive\n name: Absolute value of a positive number\n pattern: u abs\n when:\n u: [isPositiveConstant]\n output: u\n explain: "{u} is positive, so |{u}| = {u}."\n tags: [value]\n\n - id: abs-negative\n name: Absolute value of a negative number\n pattern: u abs\n when:\n u: [isNegativeConstant]\n output: u neg\n explain: "{u} is negative, so |{u}| = -({u})."\n tags: [value]\n\n - id: abs-of-exp\n name: e to a power is positive\n pattern: =e u ^ abs\n output: =e u ^\n explain: "e to any power is positive, so the absolute value changes nothing."\n tags: [identity]\n\n # ---- trigonometry: signs and turns ---------------------------------------\n - id: sin-odd\n name: Sine of a negative angle\n pattern: u sin\n when:\n u: [hasMinusSign]\n output: u neg sin neg\n explain: "sin(-θ) = -sin θ."\n tags: [symmetry]\n\n - id: cos-even\n name: Cosine of a negative angle\n pattern: u cos\n when:\n u: [hasMinusSign]\n output: u neg cos\n explain: "cos(-θ) = cos θ."\n tags: [symmetry]\n\n - id: tan-odd\n name: Tangent of a negative angle\n pattern: u tan\n when:\n u: [hasMinusSign]\n output: u neg tan neg\n explain: "tan(-θ) = -tan θ."\n tags: [symmetry]\n\n - id: sin-full-turn\n name: A full turn\n pattern: u sin\n when:\n u: [[piMultipleAtLeast, 2]]\n output: u 2 =pi * - sin\n explain: "Turning a full 2π brings you back: sin({u}) = sin({u} - 2π)."\n tags: [symmetry]\n\n - id: cos-full-turn\n name: A full turn\n pattern: u cos\n when:\n u: [[piMultipleAtLeast, 2]]\n output: u 2 =pi * - cos\n explain: "Turning a full 2π brings you back: cos({u}) = cos({u} - 2π)."\n tags: [symmetry]\n\n - id: tan-half-turn\n name: Tangent repeats every π\n pattern: u tan\n when:\n u: [[piMultipleAtLeast, 1]]\n output: u =pi - tan\n explain: "tan repeats every π: tan({u}) = tan({u} - π)."\n tags: [symmetry]\n\n - id: sin-half-turn\n name: A half turn\n pattern: u sin\n when:\n u: [[piMultipleAbove, 1], [piMultipleBelow, 2]]\n output: u =pi - sin neg\n explain: "Half a turn flips the sign: sin({u}) = -sin({u} - π)."\n tags: [symmetry]\n\n - id: cos-half-turn\n name: A half turn\n pattern: u cos\n when:\n u: [[piMultipleAbove, 1], [piMultipleBelow, 2]]\n output: u =pi - cos neg\n explain: "Half a turn flips the sign: cos({u}) = -cos({u} - π)."\n tags: [symmetry]\n\n - id: sin-second-quarter\n name: The second quarter turn\n pattern: u sin\n when:\n u: [[piMultipleAbove, 1/2], [piMultipleAtMost, 1]]\n output: =pi u - sin\n explain: "sin({u}) = sin(π - {u})."\n tags: [symmetry]\n\n - id: cos-second-quarter\n name: The second quarter turn\n pattern: u cos\n when:\n u: [[piMultipleAbove, 1/2], [piMultipleAtMost, 1]]\n output: =pi u - cos neg\n explain: "cos({u}) = -cos(π - {u})."\n tags: [symmetry]\n\n - id: tan-second-quarter\n name: The second quarter turn\n pattern: u tan\n when:\n u: [[piMultipleAbove, 1/2], [piMultipleBelow, 1]]\n output: =pi u - tan neg\n explain: "tan({u}) = -tan(π - {u})."\n tags: [symmetry]\n\n # ---- trigonometry: the standard angles -------------------------------------\n - { id: sin-0, name: Sine of 0, pattern: 0 sin, output: "0", tags: [value], explain: "sin 0 = 0." }\n - { id: sin-pi-6, name: Sine of π/6, pattern: =pi 6 / sin, output: 1 2 /, tags: [value], explain: "sin(π/6) = 1/2." }\n - { id: sin-pi-4, name: Sine of π/4, pattern: =pi 4 / sin, output: 2 sqrt 2 /, tags: [value], explain: "sin(π/4) = √2/2." }\n - { id: sin-pi-3, name: Sine of π/3, pattern: =pi 3 / sin, output: 3 sqrt 2 /, tags: [value], explain: "sin(π/3) = √3/2." }\n - { id: sin-pi-2, name: Sine of π/2, pattern: =pi 2 / sin, output: "1", tags: [value], explain: "sin(π/2) = 1." }\n - { id: sin-pi, name: Sine of π, pattern: =pi sin, output: "0", tags: [value], explain: "sin π = 0." }\n - { id: cos-0, name: Cosine of 0, pattern: 0 cos, output: "1", tags: [value], explain: "cos 0 = 1." }\n - { id: cos-pi-6, name: Cosine of π/6, pattern: =pi 6 / cos, output: 3 sqrt 2 /, tags: [value], explain: "cos(π/6) = √3/2." }\n - { id: cos-pi-4, name: Cosine of π/4, pattern: =pi 4 / cos, output: 2 sqrt 2 /, tags: [value], explain: "cos(π/4) = √2/2." }\n - { id: cos-pi-3, name: Cosine of π/3, pattern: =pi 3 / cos, output: 1 2 /, tags: [value], explain: "cos(π/3) = 1/2." }\n - { id: cos-pi-2, name: Cosine of π/2, pattern: =pi 2 / cos, output: "0", tags: [value], explain: "cos(π/2) = 0." }\n - { id: cos-pi, name: Cosine of π, pattern: =pi cos, output: "-1", tags: [value], explain: "cos π = -1." }\n - { id: tan-0, name: Tangent of 0, pattern: 0 tan, output: "0", tags: [value], explain: "tan 0 = 0." }\n - { id: tan-pi-6, name: Tangent of π/6, pattern: =pi 6 / tan, output: 3 sqrt 3 /, tags: [value], explain: "tan(π/6) = √3/3." }\n - { id: tan-pi-4, name: Tangent of π/4, pattern: =pi 4 / tan, output: "1", tags: [value], explain: "tan(π/4) = 1." }\n - { id: tan-pi-3, name: Tangent of π/3, pattern: =pi 3 / tan, output: 3 sqrt, tags: [value], explain: "tan(π/3) = √3." }\n - { id: arcsin-0, name: Arcsine of 0, pattern: 0 arcsin, output: "0", tags: [value], explain: "sin 0 = 0, so arcsin 0 = 0." }\n - { id: arcsin-half, name: Arcsine of 1/2, pattern: 1 2 / arcsin, output: =pi 6 /, tags: [value], explain: "sin(π/6) = 1/2, so arcsin(1/2) = π/6." }\n - { id: arcsin-1, name: Arcsine of 1, pattern: 1 arcsin, output: =pi 2 /, tags: [value], explain: "sin(π/2) = 1, so arcsin 1 = π/2." }\n - { id: arccos-0, name: Arccosine of 0, pattern: 0 arccos, output: =pi 2 /, tags: [value], explain: "cos(π/2) = 0, so arccos 0 = π/2." }\n - { id: arccos-half, name: Arccosine of 1/2, pattern: 1 2 / arccos, output: =pi 3 /, tags: [value], explain: "cos(π/3) = 1/2, so arccos(1/2) = π/3." }\n - { id: arccos-1, name: Arccosine of 1, pattern: 1 arccos, output: "0", tags: [value], explain: "cos 0 = 1, so arccos 1 = 0." }\n - { id: arccos-minus-1, name: Arccosine of -1, pattern: -1 arccos, output: =pi, tags: [value], explain: "cos π = -1, so arccos(-1) = π." }\n - { id: arctan-0, name: Arctangent of 0, pattern: 0 arctan, output: "0", tags: [value], explain: "tan 0 = 0, so arctan 0 = 0." }\n - { id: arctan-1, name: Arctangent of 1, pattern: 1 arctan, output: =pi 4 /, tags: [value], explain: "tan(π/4) = 1, so arctan 1 = π/4." }\n - { id: sinh-0, name: sinh of 0, pattern: 0 sinh, output: "0", tags: [value], explain: "sinh 0 = 0." }\n - { id: cosh-0, name: cosh of 0, pattern: 0 cosh, output: "1", tags: [value], explain: "cosh 0 = 1." }\n - { id: tanh-0, name: tanh of 0, pattern: 0 tanh, output: "0", tags: [value], explain: "tanh 0 = 0." }\n\n - { id: arctan-sqrt3, name: Arctangent of √3, pattern: 3 sqrt arctan, output: =pi 3 /, tags: [value], explain: "tan(π/3) = √3, so arctan √3 = π/3." }\n - { id: arctan-sqrt3-over-3, name: Arctangent of √3/3, pattern: 3 sqrt 3 / arctan, output: =pi 6 /, tags: [value], explain: "tan(π/6) = √3/3, so arctan(√3/3) = π/6." }\n\n # atan2(y, x): the angle of the point (x, y), in (-π, π]\n - id: atan2-right\n name: The angle of a point to the right\n pattern: y x atan2\n when:\n x: [isPositiveConstant]\n output: y x / arctan\n explain: "For x > 0, atan2(y, x) = arctan(y/x)."\n tags: [value]\n - id: atan2-left-up\n name: The angle of a point to the left\n pattern: y x atan2\n when:\n x: [isNegativeConstant]\n y: [isPositiveConstant]\n output: y x / arctan =pi +\n explain: "For x < 0 and y > 0, atan2(y, x) = arctan(y/x) + π."\n tags: [value]\n - id: atan2-left-down\n name: The angle of a point to the left\n pattern: y x atan2\n when:\n x: [isNegativeConstant]\n y: [isNegativeConstant]\n output: y x / arctan =pi -\n explain: "For x < 0 and y < 0, atan2(y, x) = arctan(y/x) - π."\n tags: [value]\n - { id: atan2-negative-axis, name: The angle of a point on the negative axis, pattern: 0 x atan2, when: { x: [isNegativeConstant] }, output: =pi, tags: [value], explain: "A point on the negative x-axis is at angle π." }\n - { id: atan2-up, name: Straight up, pattern: y 0 atan2, when: { y: [isPositiveConstant] }, output: =pi 2 /, tags: [value], explain: "A point straight up is at angle π/2." }\n - { id: atan2-down, name: Straight down, pattern: y 0 atan2, when: { y: [isNegativeConstant] }, output: =pi 2 / neg, tags: [value], explain: "A point straight down is at angle -π/2." }\n\n # the odd inverses take the sign out; arccos(-u) = π - arccos u\n - id: arcsin-odd\n name: Arcsine of a negative\n pattern: u arcsin\n when:\n u: [hasMinusSign]\n output: u neg arcsin neg\n explain: "arcsin(-x) = -arcsin x."\n tags: [symmetry]\n\n - id: arctan-odd\n name: Arctangent of a negative\n pattern: u arctan\n when:\n u: [hasMinusSign]\n output: u neg arctan neg\n explain: "arctan(-x) = -arctan x."\n tags: [symmetry]\n\n - id: arccos-negative\n name: Arccosine of a negative\n pattern: u arccos\n when:\n u: [hasMinusSign]\n output: =pi u neg arccos -\n explain: "arccos(-x) = π - arccos x."\n tags: [symmetry]\n\n # ---- trigonometry: identities --------------------------------------------\n - id: pythagorean\n name: sin² + cos² = 1\n pattern: u sin 2 ^ u cos 2 ^ +\n commutative: true\n output: "1"\n explain: "sin²{u} + cos²{u} = 1 for every angle."\n tags: [identity]\n\n - id: pythagorean-multiple\n name: sin² + cos² = 1\n pattern: a u sin 2 ^ * a u cos 2 ^ * +\n commutative: true\n output: a\n explain: "{a}·sin²{u} + {a}·cos²{u} = {a}(sin²{u} + cos²{u}) = {a}."\n tags: [identity]\n\n - id: one-minus-sin-squared\n name: 1 - sin² = cos²\n pattern: u sin 2 ^ neg 1 +\n output: u cos 2 ^\n explain: "1 - sin²{u} = cos²{u}."\n tags: [identity]\n\n - id: one-minus-cos-squared\n name: 1 - cos² = sin²\n pattern: u cos 2 ^ neg 1 +\n output: u sin 2 ^\n explain: "1 - cos²{u} = sin²{u}."\n tags: [identity]\n\n - id: sin-over-cos\n name: sin/cos is tan\n pattern: u sin u cos /\n output: u tan\n explain: "sin {u} / cos {u} = tan {u}."\n tags: [identity]\n\n - id: cos-over-sin\n name: cos/sin is cot\n pattern: u cos u sin /\n output: u cot\n explain: "cos {u} / sin {u} = cot {u}."\n tags: [identity]\n\n - id: sin-arcsin\n name: sin undoes arcsin\n pattern: u arcsin sin\n output: u\n explain: "sin(arcsin {u}) = {u}."\n tags: [inverse]\n\n - id: cos-arccos\n name: cos undoes arccos\n pattern: u arccos cos\n output: u\n explain: "cos(arccos {u}) = {u}."\n tags: [inverse]\n\n - id: tan-arctan\n name: tan undoes arctan\n pattern: u arctan tan\n output: u\n explain: "tan(arctan {u}) = {u}."\n tags: [inverse]\n\n - id: cosh-squared-minus-sinh-squared\n name: cosh² - sinh² = 1\n pattern: u cosh 2 ^ u sinh 2 ^ -\n output: "1"\n explain: "cosh²{u} - sinh²{u} = 1."\n tags: [identity]\n\n # ---- trigonometry: shifts by π/2 and π, written with an unknown angle ----------\n - { id: sin-plus-quarter, name: sin(u + π/2), pattern: u =pi 2 / + sin, commutative: true, output: u cos, tags: [symmetry], explain: "Shifting sine by a quarter turn gives cosine: sin({u} + π/2) = cos {u}." }\n - { id: cos-plus-quarter, name: cos(u + π/2), pattern: u =pi 2 / + cos, commutative: true, output: u sin neg, tags: [symmetry], explain: "cos({u} + π/2) = -sin {u}." }\n - { id: sin-minus-quarter, name: sin(u − π/2), pattern: u =pi 2 / - sin, output: u cos neg, tags: [symmetry], explain: "sin({u} - π/2) = -cos {u}." }\n - { id: cos-minus-quarter, name: cos(u − π/2), pattern: u =pi 2 / - cos, output: u sin, tags: [symmetry], explain: "cos({u} - π/2) = sin {u}." }\n - { id: sin-cofunction, name: sin(π/2 − u), pattern: u neg =pi 2 / + sin, commutative: true, output: u cos, tags: [symmetry], explain: "Sine of the complement is cosine: sin(π/2 - {u}) = cos {u}." }\n - { id: cos-cofunction, name: cos(π/2 − u), pattern: u neg =pi 2 / + cos, commutative: true, output: u sin, tags: [symmetry], explain: "Cosine of the complement is sine: cos(π/2 - {u}) = sin {u}." }\n - { id: tan-cofunction, name: tan(π/2 − u), pattern: u neg =pi 2 / + tan, commutative: true, output: u cot, tags: [symmetry], explain: "tan(π/2 - {u}) = cot {u}." }\n - { id: sin-supplement, name: sin(π − u), pattern: u neg =pi + sin, commutative: true, output: u sin, tags: [symmetry], explain: "sin(π - {u}) = sin {u}." }\n - { id: cos-supplement, name: cos(π − u), pattern: u neg =pi + cos, commutative: true, output: u cos neg, tags: [symmetry], explain: "cos(π - {u}) = -cos {u}." }\n - { id: sin-plus-half, name: sin(u + π), pattern: u =pi + sin, commutative: true, output: u sin neg, tags: [symmetry], explain: "Half a turn changes the sign: sin({u} + π) = -sin {u}." }\n - { id: cos-plus-half, name: cos(u + π), pattern: u =pi + cos, commutative: true, output: u cos neg, tags: [symmetry], explain: "Half a turn changes the sign: cos({u} + π) = -cos {u}." }\n - { id: tan-plus-half, name: tan(u + π), pattern: u =pi + tan, commutative: true, output: u tan, tags: [symmetry], explain: "Tangent repeats every π: tan({u} + π) = tan {u}." }\n - { id: sin-minus-half, name: sin(u − π), pattern: u =pi - sin, output: u sin neg, tags: [symmetry], explain: "sin({u} - π) = -sin {u}." }\n - { id: cos-minus-half, name: cos(u − π), pattern: u =pi - cos, output: u cos neg, tags: [symmetry], explain: "cos({u} - π) = -cos {u}." }\n\n # ---- trigonometry: more exact values (15°, 75°, 22.5°, 67.5°) -------------------\n - { id: sin-pi-12, name: Sine of π/12, pattern: =pi 12 / sin, output: 6 sqrt 2 sqrt - 4 /, tags: [value], explain: "sin(π/12) = sin(π/3 - π/4) = (√6 - √2)/4." }\n - { id: cos-pi-12, name: Cosine of π/12, pattern: =pi 12 / cos, output: 6 sqrt 2 sqrt + 4 /, tags: [value], explain: "cos(π/12) = cos(π/3 - π/4) = (√6 + √2)/4." }\n - { id: tan-pi-12, name: Tangent of π/12, pattern: =pi 12 / tan, output: 2 3 sqrt -, tags: [value], explain: "tan(π/12) = 2 - √3." }\n - { id: sin-5pi-12, name: Sine of 5π/12, pattern: 5 =pi * 12 / sin, output: 6 sqrt 2 sqrt + 4 /, tags: [value], explain: "sin(5π/12) = sin(π/4 + π/6) = (√6 + √2)/4." }\n - { id: cos-5pi-12, name: Cosine of 5π/12, pattern: 5 =pi * 12 / cos, output: 6 sqrt 2 sqrt - 4 /, tags: [value], explain: "cos(5π/12) = cos(π/4 + π/6) = (√6 - √2)/4." }\n - { id: tan-5pi-12, name: Tangent of 5π/12, pattern: 5 =pi * 12 / tan, output: 2 3 sqrt +, tags: [value], explain: "tan(5π/12) = 2 + √3." }\n - { id: sin-pi-8, name: Sine of π/8, pattern: =pi 8 / sin, output: 2 2 sqrt - sqrt 2 /, tags: [value], explain: "By the half-angle formula, sin(π/8) = √(2 - √2)/2." }\n - { id: cos-pi-8, name: Cosine of π/8, pattern: =pi 8 / cos, output: 2 2 sqrt + sqrt 2 /, tags: [value], explain: "By the half-angle formula, cos(π/8) = √(2 + √2)/2." }\n - { id: tan-pi-8, name: Tangent of π/8, pattern: =pi 8 / tan, output: 2 sqrt 1 -, tags: [value], explain: "tan(π/8) = √2 - 1." }\n - { id: sin-3pi-8, name: Sine of 3π/8, pattern: 3 =pi * 8 / sin, output: 2 2 sqrt + sqrt 2 /, tags: [value], explain: "sin(3π/8) = cos(π/8) = √(2 + √2)/2." }\n - { id: cos-3pi-8, name: Cosine of 3π/8, pattern: 3 =pi * 8 / cos, output: 2 2 sqrt - sqrt 2 /, tags: [value], explain: "cos(3π/8) = sin(π/8) = √(2 - √2)/2." }\n - { id: tan-3pi-8, name: Tangent of 3π/8, pattern: 3 =pi * 8 / tan, output: 2 sqrt 1 +, tags: [value], explain: "tan(3π/8) = √2 + 1." }\n\n # ---- trigonometry: a function of an inverse function (a right triangle) -----------\n - { id: sin-arccos, name: sin(arccos u), pattern: u arccos sin, output: u 2 ^ neg 1 + sqrt, tags: [inverse], explain: "In a right triangle with cos θ = {u}, the other side is √(1 - {u}²): sin(arccos {u}) = √(1 - {u}²)." }\n - { id: cos-arcsin, name: cos(arcsin u), pattern: u arcsin cos, output: u 2 ^ neg 1 + sqrt, tags: [inverse], explain: "In a right triangle with sin θ = {u}, cos θ = √(1 - {u}²)." }\n - { id: tan-arcsin, name: tan(arcsin u), pattern: u arcsin tan, output: u u 2 ^ neg 1 + sqrt /, tags: [inverse], explain: "tan(arcsin {u}) = {u}/√(1 - {u}²)." }\n - { id: tan-arccos, name: tan(arccos u), pattern: u arccos tan, output: u 2 ^ neg 1 + sqrt u /, tags: [inverse], explain: "tan(arccos {u}) = √(1 - {u}²)/{u}." }\n - { id: sin-arctan, name: sin(arctan u), pattern: u arctan sin, output: u u 2 ^ 1 + sqrt /, tags: [inverse], explain: "In a right triangle with tan θ = {u}, the long side is √(1 + {u}²): sin(arctan {u}) = {u}/√(1 + {u}²)." }\n - { id: cos-arctan, name: cos(arctan u), pattern: u arctan cos, output: 1 u 2 ^ 1 + sqrt /, tags: [inverse], explain: "cos(arctan {u}) = 1/√(1 + {u}²)." }\n - { id: sec-arctan, name: sec(arctan u), pattern: u arctan sec, output: u 2 ^ 1 + sqrt, tags: [inverse], explain: "sec(arctan {u}) = √(1 + {u}²)." }\n - { id: cos-arcsec, name: cos(arcsec u), pattern: u arcsec cos, output: 1 u /, tags: [inverse], explain: "arcsec {u} is the angle whose cosine is 1/{u}." }\n - { id: sin-arccsc, name: sin(arccsc u), pattern: u arccsc sin, output: 1 u /, tags: [inverse], explain: "arccsc {u} is the angle whose sine is 1/{u}." }\n - { id: tan-arccot, name: tan(arccot u), pattern: u arccot tan, output: 1 u /, tags: [inverse], explain: "arccot {u} is the angle whose tangent is 1/{u}." }\n\n # ---- trigonometry: the angle-sum formulas, read backward -------------------------\n - { id: sin-sum, name: sin(u + v), pattern: u sin v cos * u cos v sin * +, commutative: true, output: u v + sin, tags: [identity], explain: "sin {u} cos {v} + cos {u} sin {v} = sin({u} + {v})." }\n - { id: sin-difference, name: sin(u − v), pattern: u sin v cos * u cos v sin * -, commutative: true, output: u v - sin, tags: [identity], explain: "sin {u} cos {v} - cos {u} sin {v} = sin({u} - {v})." }\n - { id: sin-difference-led-by-minus, name: sin(u − v), pattern: u cos v sin * neg u sin v cos * +, commutative: true, output: u v - sin, tags: [identity], explain: "sin {u} cos {v} - cos {u} sin {v} = sin({u} - {v})." }\n - { id: cos-sum, name: cos(u + v), pattern: u cos v cos * u sin v sin * -, commutative: true, output: u v + cos, tags: [identity], explain: "cos {u} cos {v} - sin {u} sin {v} = cos({u} + {v})." }\n - { id: cos-difference, name: cos(u − v), pattern: u cos v cos * u sin v sin * +, commutative: true, output: u v - cos, tags: [identity], explain: "cos {u} cos {v} + sin {u} sin {v} = cos({u} - {v})." }\n\n # ---- logs: opt-in rewrites (run with cas.rewrite(x, \'expand-log\') or \'combine-log\') ----\n - id: ln-product\n name: Log of a product\n mode: expand-log\n pattern: a b * ln\n output: a ln b ln +\n explain: "ln({a}·{b}) = ln {a} + ln {b} (for positive {a}, {b})."\n tags: [log]\n\n - id: ln-quotient\n name: Log of a quotient\n mode: expand-log\n pattern: a b / ln\n output: a ln b ln -\n explain: "ln({a}/{b}) = ln {a} - ln {b} (for positive {a}, {b})."\n tags: [log]\n\n - id: ln-power\n name: Log of a power\n mode: expand-log\n pattern: a n ^ ln\n output: n a ln *\n explain: "ln({a}^{n}) = {n}·ln {a} (for positive {a})."\n tags: [log]\n\n - id: ln-root\n name: Log of a square root\n mode: expand-log\n pattern: a sqrt ln\n output: a ln 2 /\n explain: "ln √{a} = ½ ln {a}."\n tags: [log]\n\n - id: ln-sum-combine\n name: Sum of logs\n mode: combine-log\n pattern: a ln b ln +\n commutative: true\n output: a b * ln\n explain: "ln {a} + ln {b} = ln({a}·{b})."\n tags: [log]\n\n - id: ln-difference-combine\n name: Difference of logs\n mode: combine-log\n pattern: a ln b ln -\n output: a b / ln\n explain: "ln {a} - ln {b} = ln({a}/{b})."\n tags: [log]\n\n - id: ln-multiple-combine\n name: A multiple of a log\n mode: combine-log\n pattern: n a ln *\n when:\n n: [isRational]\n output: a n ^ ln\n explain: "{n}·ln {a} = ln({a}^{n})."\n tags: [log]\n','name: Solving by undoing\n\n# mode: isolate. Each rule undoes the outermost function on the side with the\n# unknown: ln u = r → u = e^r. The predicates hasVariable and freeOfVariable mean\n# "mentions / doesn\'t mention the unknown being solved for".\n#\n# The CAS does the rest itself: it moves terms without the unknown to the other\n# side, divides by a coefficient, and when the unknown appears in several places\n# it uses the polynomial methods (factoring, the quadratic formula) or splits a\n# product equal to 0. Every answer is checked in the original equation, so a\n# rule may give extra candidates (squaring both sides does): the wrong ones are\n# dropped, with a step saying so.\n#\n# An output can give several answers: `pm` (±) splits into two, and so does\n# `|` (or): "u r arcsin = u =pi r arcsin - = |".\n\nrules:\n - id: iso-swap\n name: Unknown on the left\n mode: isolate\n pattern: l r =\n when:\n l: [freeOfVariable]\n r: [hasVariable]\n output: r l =\n priority: 20\n explain: "Swap the sides so the unknown is on the left."\n tags: [tidy]\n\n - id: iso-ln\n name: Undo the log\n mode: isolate\n pattern: u ln r =\n when:\n u: [hasVariable]\n output: u =e r ^ =\n explain: "Raise e to each side: e^(ln {u}) = {u}."\n tags: [inverse]\n\n - id: iso-log\n name: Undo the log\n mode: isolate\n pattern: b u log r =\n when:\n u: [hasVariable]\n b: [freeOfVariable]\n output: u b r ^ =\n explain: "Raise {b} to each side: {b}^(log base {b} of {u}) = {u}."\n tags: [inverse]\n\n - id: iso-exp\n name: Undo e to a power\n mode: isolate\n pattern: =e u ^ r =\n when:\n u: [hasVariable]\n output: u r ln =\n explain: "Take ln of each side: ln(e^{u}) = {u}."\n tags: [inverse]\n\n - id: iso-exponential\n name: Undo a power of a number\n mode: isolate\n pattern: b u ^ r =\n when:\n u: [hasVariable]\n b: [freeOfVariable]\n output: u b r log =\n explain: "Take the log to base {b} of each side."\n tags: [inverse]\n\n - id: iso-square\n name: Undo the square\n mode: isolate\n pattern: u 2 ^ r =\n when:\n u: [hasVariable]\n output: u r sqrt pm =\n priority: 1\n explain: "Take the square root of each side; {u} can be positive or negative."\n tags: [inverse]\n\n - id: iso-even-power\n name: Undo an even power\n mode: isolate\n pattern: u n ^ r =\n when:\n u: [hasVariable]\n n: [isEvenWhole]\n output: u r 1 n / ^ pm =\n explain: "Take the root of each side (the {n}th root); {u} can be positive or negative."\n tags: [inverse]\n\n - id: iso-odd-power\n name: Undo an odd power\n mode: isolate\n pattern: u n ^ r =\n when:\n u: [hasVariable]\n n: [isOddWhole]\n output: u r 1 n / ^ =\n explain: "Take the root of each side (the {n}th root)."\n tags: [inverse]\n\n - id: iso-fractional-power\n name: Undo a power\n mode: isolate\n pattern: u n ^ r =\n when:\n u: [hasVariable]\n n: [isRational]\n output: u r 1 n / ^ =\n priority: -1\n explain: "Raise each side to the power 1/{n}."\n tags: [inverse]\n\n - id: iso-sqrt\n name: Undo the square root\n mode: isolate\n pattern: u sqrt r =\n when:\n u: [hasVariable]\n output: u r 2 ^ =\n explain: "Square each side (this can add answers, so each one is checked at the end)."\n tags: [inverse]\n\n - id: iso-root\n name: Undo the root\n mode: isolate\n pattern: n u root r =\n when:\n u: [hasVariable]\n n: [freeOfVariable]\n output: u r n ^ =\n explain: "Raise each side to the power {n}."\n tags: [inverse]\n\n - id: iso-reciprocal\n name: Undo the fraction\n mode: isolate\n pattern: c u / r =\n when:\n u: [hasVariable]\n c: [freeOfVariable]\n output: u c r / =\n explain: "{c}/{u} = {r}, so {u} = {c}/{r}."\n tags: [inverse]\n\n - id: iso-abs\n name: Undo the absolute value\n mode: isolate\n pattern: u abs r =\n when:\n u: [hasVariable]\n output: u r pm =\n explain: "|{u}| = {r} means {u} is {r} or -{r}."\n tags: [inverse]\n\n - id: iso-sin\n name: Undo the sine\n mode: isolate\n pattern: u sin r =\n when:\n u: [hasVariable]\n output: u r arcsin = u =pi r arcsin - = |\n explain: "Two angles in a turn have sine {r}: {u} is arcsin {r} or π - arcsin {r} (and any whole number of turns, 2πk, more)."\n tags: [inverse, trig, period-2pi]\n\n - id: iso-cos\n name: Undo the cosine\n mode: isolate\n pattern: u cos r =\n when:\n u: [hasVariable]\n output: u r arccos pm =\n explain: "Two angles in a turn have cosine {r}: {u} is ±arccos {r} (and any whole number of turns, 2πk, more)."\n tags: [inverse, trig, period-2pi]\n\n - id: iso-tan\n name: Undo the tangent\n mode: isolate\n pattern: u tan r =\n when:\n u: [hasVariable]\n output: u r arctan =\n explain: "Take arctan of each side ({u} can also be any whole number of half turns, πk, more)."\n tags: [inverse, trig, period-pi]\n\n - { id: iso-arcsin, name: Undo arcsin, mode: isolate, pattern: u arcsin r =, when: { u: [hasVariable] }, output: u r sin =, tags: [inverse], explain: "Take sin of each side." }\n - { id: iso-arccos, name: Undo arccos, mode: isolate, pattern: u arccos r =, when: { u: [hasVariable] }, output: u r cos =, tags: [inverse], explain: "Take cos of each side." }\n - { id: iso-arctan, name: Undo arctan, mode: isolate, pattern: u arctan r =, when: { u: [hasVariable] }, output: u r tan =, tags: [inverse], explain: "Take tan of each side." }\n - { id: iso-sinh, name: Undo sinh, mode: isolate, pattern: u sinh r =, when: { u: [hasVariable] }, output: u r arcsinh =, tags: [inverse], explain: "Take arcsinh of each side." }\n - { id: iso-tanh, name: Undo tanh, mode: isolate, pattern: u tanh r =, when: { u: [hasVariable] }, output: u r arctanh =, tags: [inverse], explain: "Take arctanh of each side." }\n - { id: iso-cosh, name: Undo cosh, mode: isolate, pattern: u cosh r =, when: { u: [hasVariable] }, output: u r arccosh pm =, tags: [inverse], explain: "Two numbers have cosh {r}: ±arccosh {r}." }\n - { id: iso-arcsinh, name: Undo arcsinh, mode: isolate, pattern: u arcsinh r =, when: { u: [hasVariable] }, output: u r sinh =, tags: [inverse], explain: "Take sinh of each side." }\n - { id: iso-arccosh, name: Undo arccosh, mode: isolate, pattern: u arccosh r =, when: { u: [hasVariable] }, output: u r cosh =, tags: [inverse], explain: "Take cosh of each side." }\n - { id: iso-arctanh, name: Undo arctanh, mode: isolate, pattern: u arctanh r =, when: { u: [hasVariable] }, output: u r tanh =, tags: [inverse], explain: "Take tanh of each side." }\n'],$m=['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'],km=new Set(["<",">","≤","≥"]),qm=new Set(["sin","cos","tan","sec","csc","cot"]),Mm=new Set(["arcsin","arccos","arctan","arcsec","arccsc","arccot"]),Am={normal:"Work out the numbers and collect like terms.","normal.numbers":"Work out the numbers.","normal.collect":"Collect like terms.","normal.expand-collect":"Multiply out the brackets and collect like terms.","solve.both-add":"Add {t} to both sides.","solve.both-subtract":"Subtract {t} from both sides.","solve.both-divide":"Divide both sides by {t}.","solve.both-multiply":"Multiply both sides by {t}.","solve.each-side":"Work out each side.","simplify.cancel":"Cancel the factors the top and bottom share.","simplify.expand":"Multiplying out gives something shorter.","simplify.factor":"Factoring gives something shorter.",expand:"Multiply out the brackets.",factor:"Write it as a product of factors.","factor.common":"Take out the common factor {common}.","factor.polynomial":"Factor what is left: {roots}.",together:"Write it as one fraction over a common denominator.",cancel:"Cancel the factors the top and bottom share: {canceled}.","solve.move":"Keep the terms with {v} on the left and move the others to the right.","solve.collect":"Collect the terms with {v} on the left, where {v} is multiplied by {a} in all, and move the others to the right.","solve.expand":"Multiply out the brackets.","solve.divide":"Divide both sides by {by}.","solve.multiply":"Multiply both sides by {by}.","solve.one-side":"Move everything to one side, so the equation reads … = 0.","solve.factor":"Factor the left side.","solve.zero-product":"A product is 0 exactly when one of its factors is 0.","solve.split":"There are two cases; solve each.","solve.quadratic":"The quadratic formula with a = {a}, b = {b}, c = {c}: {v} = (-b ± √(b² - 4ac)) / 2a, and b² - 4ac = {D}.","solve.no-real":"b² - 4ac = {D} is negative, so there are no real solutions.","solve.quadratic-complex":"The quadratic formula with a = {a}, b = {b}, c = {c}: {v} = (-b ± √(b² - 4ac)) / 2a. b² - 4ac = {D} is negative, so its square root is imaginary: √({D}) = {root}.","solve.roots":"{v}^{n} = {r} has {n} solutions, spaced evenly round a circle: |{r}|^(1/{n})·(cos θ + i sin θ), with θ = (arg {r} + 2πk)/{n} for k = 0 … {last}.","solve.clear-denominator":"Multiply both sides by {den} (an answer that makes it 0 is not allowed).","solve.substitute":"Write {u} for {kernel}: this is a polynomial in {u}.","solve.back":"Put {kernel} back for {u}.","solve.reject":"{value} is not a solution: {reason}.","solve.always":"This is true for every {v}.","solve.never":"This is never true, so there is no solution.","solve.interval":"In the interval from {lo} to {hi}, that is {count} answer(s): each one, and the same plus or minus a whole number of periods.","solve.never-zero":"{f} is never 0, so the rest must be: divide both sides by it.","solve.sin-cos":"Divide both sides by cos({u}): sine over cosine is the tangent.","solve.pythagorean":"Write {from}² as 1 - {to}², so there is only {to}({u}).","simplify.trig":"Write it with sin and cos, use sin² + cos² = 1 and the double-angle formulas, and cancel.","simplify.trig.sin-cos":"Write tan, sec, csc and cot with sin and cos, and cancel.","simplify.trig.pythagorean":"Write it with sin and cos, and use sin² + cos² = 1.","simplify.trig.expand-double":"Write the double angles out (sin 2u = 2 sin u cos u, cos 2u = cos²u − sin²u), and cancel.","simplify.trig.double-angle":"Read the double-angle formulas backward: 2 sin u cos u = sin 2u, cos²u − sin²u = cos 2u.","limit.substitute":"{f} is continuous at {v} = {a}: put {a} in.","limit.cancel":"{f} is 0/0 at {v} = {a}: cancel the common factor first.","limit.lhopital":"{f} is {form} as {v} → {a}: by L'Hôpital's rule, take the limit of the top's derivative over the bottom's.","limit.leading":"As {v} → {a}, the highest powers decide: {f} behaves like {lead}.","limit.zero-times-infinity":"{f} is 0·∞: write it as a quotient.","limit.combine":"{f} is ∞ − ∞: write it as one fraction.","limit.squeeze":"{bounded} stays between two bounds, and what it is multiplied by goes to 0: so does the product (the squeeze theorem).","limit.divide-power":"Divide the top and the bottom by {power}.","limit.conjugate":"{f} is ∞ − ∞ with a root: multiply top and bottom by the conjugate.","limit.exp-log":"{f} is {form}: write it as e to the power (exponent · ln base), and find the limit of the exponent.","limit.abs":"{inside} is {sign} {where}, so {abs} is {to}.","limit.one-sided":"From the left {f} goes to {left}, from the right to {right}: the limit does not exist.","solve.sign-chart":"Where each side minus the other is 0, or has no value: {points}. It keeps one sign between them, so test one {v} in each interval, and each point.","solve.unsolved":"There is no exact method here for solving for {v}; try { approximate: true }.","solve.numeric":"Found {count} solution(s) numerically.","system.swap":"Swap the {row} and {other} equations, so that the {row} one has {v} in it.","system.scale":"Divide the {row} equation by {by}, so that {v} stands alone in front.","system.subtract":"Subtract the {from} equation from the {row} one: {v} goes from it.","system.subtract-multiple":"Subtract {k} times the {from} equation from the {row} one: {v} goes from it.","system.add":"Add the {from} equation to the {row} one: {v} goes from it.","system.add-multiple":"Add {k} times the {from} equation to the {row} one: {v} goes from it.","integrate.cancel":"Write the integrand as one fraction and cancel what the top and bottom share.","integrate.expand":"Multiply out, then integrate term by term.","integrate.substitute":"Let {u} = {inside}, so d{u} = {du}.","integrate.back":"Put {inside} back for {u}.","integrate.parts":"By parts with u = {u} and dv = {dv} d{v}: ∫ u dv = u·v - ∫ v du, where v = {V} and du = {du} d{v}.","integrate.constant":"The number {c} comes out of the integral.","integrate.divide":"The top has at least the degree of the bottom: divide first.","integrate.partial-fractions":"Split the fraction into simple fractions, one for each factor below.","integrate.evaluate":"Evaluate {F} at {b} and at {a}, and subtract.","integrate.improper":"An improper integral: at an infinite end, the limit of {F} as {v} goes there; then subtract.","integrate.u-substitution":"Let {u} = {inside}, so d{u} = {du} d{v}: the integral is in {u} alone.","integrate.complete-square":"Partial fractions, and complete the square in {Q}: the top that is a multiple of its derivative gives a log, the rest an arctangent.","integrate.parts-twice":"By parts twice: the integral of {e}·{t} comes back, so solve for it.","integrate.product-to-sum":"Write the product of sines and cosines as a sum.","integrate.odd-power":"Keep one {f} and write the rest with {other} (sin² + cos² = 1): then {other} is the substitution.","integrate.reduction":"The reduction formula for {f} to the power {n}.","integrate.trig-substitution":"Let {x} = {a}·sin θ: the root becomes {a}·cos θ.",substitute:"Put in the values."},Sm=["normal","rewrite","simplify","expand","factor","cancel","diff","differentiate","integrate","solve","solveSystem","substitute","approximate","equivalent","limit"];class Nm{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 Sm){const t=Nm.prototype[e];this[e]=(...e)=>iu(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 Ll(e);if("string"!=typeof e)throw new Hl("expected an expression");if(this.read){const t=this.read(e);return Array.isArray(t)?Ll(t):"string"==typeof t?Fl(t):t}return Fl(e)}atPoints(e){if(!e||!Zl(e)||!e.s.includes("= der"))return e;const t=e.args.map(e=>this.atPoints(e)),[n,r]=t;if("der"===e.op&&Zl(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 Tl(e.op,t)}step(e,t,n,r,s,i={},o=e){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[o]??this.messages[e]??"",i,this.format)}select(e,t,n=null){const r=function(e){if(!1===e)return null;if(void 0===e||!0===e)return{show:"all",hide:cf.normal,explain:!0,detail:"normal"};if("string"==typeof e){if(!cf[e])throw new Error(`steps: "${e}" is not one of ${Object.keys(cf).join(", ")}`);return{show:"all",hide:cf[e],explain:!0,detail:e}}const t=e.detail??"normal";if(!cf[t])throw new Error(`steps.detail: "${t}" is not one of ${Object.keys(cf).join(", ")}`);return{show:e.show??"all",hide:[...cf[t],...e.hide??[]],explain:e.explain??!0,detail:t}}(t);return"full"===r?.detail&&(r.split=e=>this.splitTidy(e)),uf(function(e,t){if(!t)return[];e="full"===t.detail?t.split?e.flatMap(t.split):e:function(e){const t=[];for(const n of e){const e=t[t.length-1];if(!("d-variable"===n.id&&e&&/^(\S+) \1 der$/.test(n.before??"")&&` ${e.after??""} `.includes(` ${n.before} `))){t.push(n);continue}const r={...e,to:n.to};if(e.after&&(r.after=` ${e.after} `.replace(` ${n.before} `," 1 ").replace(/ 1 \*(?= )/g,"").trim()),e.explanation){const t=n.before.split(" ")[0],s=` The derivative of ${t} is 1.`;r.explanation=e.explanation.endsWith(`the derivative of ${t}.`)?`${e.explanation.slice(0,-1)}, which is 1.`:e.explanation.endsWith(s)||e.explanation.endsWith(`the derivative of ${t}, which is 1.`)?e.explanation:`${e.explanation}${s}`}t[t.length-1]=r}return t}(e);const n=[];let r=null;for(const s of e){if(!hf(s,t.show)||hf(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&&hf(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}(e,r),n)}splitTidy(e){if(["solve.move","solve.divide","solve.multiply"].includes(e.id))return this.splitBothSides(e);if("normal"!==e.id)return[e];let t,n;try{t=Fl(e.from),n=Kc(t)}catch{return[e]}return n.s===t.s||n.s===e.to?[e]:[this.step("normal.numbers","Work out the numbers",["arithmetic"],t,n),{...this.step("normal.collect","Collect like terms",["tidy"],n,Fl(e.to),{},Dl(n,"pre").some(({node:e})=>Zl(e)&&"*"===e.op&&e.args.some(e=>Zl(e)&&("+"===e.op||"-"===e.op)))?"normal.expand-collect":"normal.collect"),path:e.path}]}splitBothSides(e){try{return this.bothSides(e)}catch{return[e]}}bothSides(e){let t,n;try{t=Fl(e.from),n=Fl(e.to)}catch{return[e]}const r=e.path??[],s=(e,t)=>t.reduce((e,t)=>e?.args?.[t],e),i=s(t,r),o=s(n,r);if(!i||!o||"="!==i.op||"="!==o.op)return[e];const a=e=>r.length?Vl(t,r,e):e,[l,u]=i.args,[c,h]=o.args,f=[];let p=t;const m=(e,t,n,s)=>{const i=a(t);f.push({...this.step(e,"The same on both sides",["move"],p,i,{t:s}),path:r}),p=a(n),f.push({...this.step("solve.each-side","Work out each side",["arithmetic"],i,p),path:r})};if("solve.move"===e.id){const t=Pu(Tl("-",[l,c]));if(du(t)!==du(Pu(Tl("-",[u,h])))||fu(t)&&t.q.isZero)return[e];const n=Ju(t).sort((e,t)=>Number(Xu(t).size>0)-Number(Xu(e).size>0));let r=l,s=u;n.forEach((e,t)=>{const i=fu(e)?e.q.sign>0:!Hu(e).s.endsWith(" neg"),a=Hu(i?e:Cu(e)),l=Tl("=",[Tl(i?"-":"+",[r,a]),Tl(i?"-":"+",[s,a])]),u=t===n.length-1?o:Tl("=",[Wu(l.args[0]),Wu(l.args[1])]);m(i?"solve.both-subtract":"solve.both-add",l,u,a),[r,s]=u.args})}else{const t=Pu(Tl("/",[l,c])),n=e=>{const t=Pu(e);return fu(t)&&t.q.isZero};if(!(!(!n(u)||!n(h))||!n(h)&&du(t)===du(Pu(Tl("/",[u,h]))))||Xu(t).size||fu(t)&&t.q.isZero)return[e];const r=fu(t)&&!t.q.isInteger&&(1n===t.q.n||-1n===t.q.n),s=Hu(r?Zu(Pu(Il("1")),t):t);m(r?"solve.both-multiply":"solve.both-divide",Tl("=",[Tl(r?"*":"/",[l,s]),Tl(r?"*":"/",[u,s])]),o,s)}return f.length&&f.at(-1).to===e.to?f:[e]}result(e,t,n,r={},s=null){let i=e;if(n.approximate&&i){i=Nh(i,{digits:"number"==typeof n.approximate?n.approximate:15})}return{result:i,text:i?this.format(i):"",steps:this.select(t,n.steps,s),...r}}variable(e,t){if(t&&!/^\\?[A-Za-z\u0370-\u03FF][A-Za-z0-9_\u0370-\u03FF′]*$/.test(t))throw new Hl(`"${t}" is not a variable name; for a derivative at a point write der(f, x = a)`);if(t)return t;const n=[...Xu(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 Wu(this.node(e))}rewrite(e,t,n={}){const r=this.node(e),s=this.set.view(t);if(!s.size)throw new Hl(`no rules in mode "${t}" (modes: ${this.set.modes().join(", ")})`);const i=Bh(r,s,{format:this.format,order:n.order,variable:n.variable});return this.result(i.node,[...this.tidyStep(r,Wu(r)),...i.steps],n,{},r)}simplify(e,t={}){const n=this.node(e),r=[...this.tidyStep(n,Wu(n))],s=Bh(n,this.set.view("simplify"),{format:this.format});r.push(...s.steps);let i=s.node;const o=Pu(i),a=[],l=0===Xu(i).size,u=l?null:Zf(o);u&&a.push({node:jf(u),id:"simplify.cancel",name:"Cancel"});const c=Bh(Hu(df(o)),this.set.view("simplify"),{format:this.format});a.push({node:c.node,id:"simplify.expand",name:"Multiply out"}),"add"!==o.k||l||a.push({node:jf(Sf(o)),id:"simplify.factor",name:"Factor"});const h=e=>Dl(e,"pre").some(({node:e})=>Zl(e)&&qm.has(e.op)&&Dl(e.args[0],"pre").some(({node:e})=>Zl(e)&&Mm.has(e.op)));for(const e of Fp(this,i))a.push({node:e.node,id:"simplify.trig",wording:`simplify.trig.${e.how}`,name:"Trigonometric identities",prefer:h(i)&&!h(e.node)});let f=!1;for(const e of a)f&&"simplify.trig"===e.id&&!e.prefer||(e.prefer&&(f=!0),(Bl(e.node)<Bl(i)||e.prefer)&&(r.push(this.step(e.id,e.name,["shorter"],i,e.node,{},e.wording)),i=e.node));return this.result(i,r,t,{},n)}expand(e,t={}){const n=this.node(e),r=Hu(df(Pu(n)));return this.result(r,n.s===r.s?[]:[this.step("expand","Multiply out",["expand"],n,r)],t,{},n)}factor(e,t={}){const n=this.node(e),r=Sf(Pu(n)),s=jf(r),i=[],o=r.notes.find(e=>"factor.common"===e.id);return s.s!==Wu(n).s&&i.push(this.step(o?"factor.common":"factor","Factor",["factor"],n,s,o?{common:Hu(o.values.common)}:{})),this.result(s,i,t,{},n)}cancel(e,t={}){const n=this.node(e),r=Pu(n),s=Zf(r);if(!s)return this.result(Wu(n),this.tidyStep(n,Wu(n)),t,{},n);const i=jf(s),o=Cf(r),a=Tl("/",[Hu(o.num),Hu(o.den)]),l=[];return"/"===n.op&&a.s===Wu(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(Hu(e))).join(", "):"numbers"})),this.result(i,l,t,{},n)}diff(e,t,n={}){const r=this.node(e),s=this.variable(r,t),i="string"==typeof n.steps?n.steps:n.steps?.detail,o=Uh(r),a={diff:this.set.view("differentiate"),simp:this.set.view("simplify")};let l=o;const u=[];for(let e=0;e<(n.order??1);e++){const e=Qh(Tl("der",[l,Il(s)]),a.diff,{fold:"full"===i?null:a,format:this.format}),t=Qh(e.node,a.simp,{format:this.format,order:"post",maxSteps:40}),n=Wu(t.node),r=Bh(n,a.simp,{format:this.format});u.push(...e.steps,...t.steps,...this.tidyStep(t.node,n),...r.steps),l=r.node}const c=Pu(l),h=Xu(l).size?Zf(c):null,f=[h&&{node:jf(h),id:"simplify.cancel",name:"Cancel"},{node:Hu(df(c)),id:"simplify.expand",name:"Multiply out"}].find(e=>e&&Bl(e.node)<Bl(l));return f&&(u.push(this.step(f.id,f.name,["shorter"],l,f.node)),l=f.node),this.result(l,u,n,{variable:s},Tl("der",[r,Il(s)]))}differentiate(e,t){const n=Bh(Tl("der",[e,Il(t)]),this.set.view("differentiate"),{format:this.format,order:"pre"});return Bh(n.node,this.set.view("simplify"),{format:this.format}).node}integrate(e,t,n={}){t&&"object"==typeof t&&(n=t,t=void 0);let r=this.node(e);const s=r,i=e=>void 0===e?null:this.node("number"==typeof e?String(e):e);let o=i(n.from),a=i(n.to);if(Zl(r)&&"int"===r.op){const[e,n,s,i]=r.args;t=n.token,s&&i&&(o=s,a=i),r=e}const l=this.variable(r,t),u=Xp(this,r,l),c=Bh(u.node,this.set.view("simplify"),{format:this.format}),h=[...u.steps,...c.steps];if(o&&a){const e=hm(this,c.node,l,o,a,r);h.push(e.step);const t=Bh(e.value,this.set.view("simplify"),{format:this.format});return h.push(...this.tidyStep(e.shown,e.value),...t.steps),this.result(t.node,h,n,{antiderivative:c.node,variable:l},Zl(s)&&"int"===s.op?s:null)}let f=c.node;if(n.constant){const e=new Set([...Xu(r),l]);f=Tl("+",[f,Il(!0===n.constant?["C","c","K"].find(t=>!e.has(t))??"C":String(n.constant))])}return this.result(f,h,n,{variable:l},Zl(s)&&"int"===s.op?s:Tl("int",[s,Il(l)]))}solve(e,t,n={}){const r=this.node(e),s=this.variable(r,t);if(Zl(r)&&km.has(r.op))return this.inequality(r,s,n);const i=Bf(this,r,s,n);let o=i.solutions;if(n.approximate){const e="number"==typeof n.approximate?n.approximate:15;o=o.map(t=>Nh(t,{digits:e}))}const a=e=>e.length?e.map(e=>Tl("=",[Il(s),e])).reduce((e,t)=>e?Tl("|",[e,t]):t,null):null,l=(i.base??o).map(e=>Tl("=",[Il(s),e])),u=a(i.base??o),c=ff(i.steps,r,{parse:Fl,replaceAt:Vl}),h=e=>Zl(e)&&"|"===e.op?e.args.flatMap(h):[e.s],f=c[c.length-1];if(f&&u&&!n.approximate){let e=null;try{e=Fl(f.to)}catch{}if(e&&e.s!==u.s&&h(e).sort().join("\n")===h(u).sort().join("\n"))f.to=u.s;else if(e&&e.s!==u.s){const t=e=>Zl(e)&&"|"===e.op?e.args.flatMap(t):[e],n=t(e);n.length>=l.length&&n.every(e=>Zl(e)&&"="===e.op&&e.args[0].s===s)&&c.push(this.step("normal","Work out and collect",["tidy","arithmetic"],e,u))}}const p=i.base?a(o):u;if(i.base&&u&&!n.approximate){const e=c.length?Fl(c[c.length-1].to):u;p&&p.s===e.s||c.push(this.step("solve.interval","The answers in the interval",["interval"],e,p??e,{lo:i.interval[0],hi:i.interval[1],v:Il(s),count:String(o.length)}))}return i.steps=c,{solutions:o,result:p,variable:s,text:i.always?`true for every ${s}`:p?this.format(p):i.unsolved.length?`no exact solution found for ${s}`:"no solution",unsolved:i.unsolved.filter(e=>!e.always),always:i.always,periodic:Boolean(i.periodic),period:i.period??null,...i.interval?{interval:i.interval}:{},steps:this.select(i.steps,n.steps,r)}}inequality(e,t,n){const r=fp(this,e,t,n),s={solutions:[],variable:t,unsolved:[],always:!1,steps:this.select(r.steps,n.steps,e)};if(!r.pieces)return{...s,pieces:null,intervals:"",result:null,unsolved:[e],text:`no exact solution found for ${t}`};const i=Il(t),o=1===r.pieces.length&&!r.pieces[0].lo&&!r.pieces[0].hi,a=r.pieces.map(({lo:e,hi:t,loClosed:n,hiClosed:r})=>e&&t&&e.s===t.s?Tl("=",[i,e]):e||t?e?t?Tl(r?"≤":"<",[Tl(n?"≤":"<",[e,i]),t]):Tl(n?"≥":">",[i,e]):Tl(r?"≤":"<",[i,t]):null).filter(Boolean).reduce((e,t)=>e?Tl("|",[e,t]):t,null),l=r.pieces.length?r.pieces.map(({lo:e,hi:t,loClosed:n,hiClosed:r})=>e&&t&&e.s===t.s?`{${this.format(e)}}`:`${n?"[":"("}${e?this.format(e):"-∞"}, ${t?this.format(t):"∞"}${r?"]":")"}`).join(" ∪ "):"∅",u=o?`true for every ${t}`:a?this.format(a):"no solution";return{...s,pieces:r.pieces,intervals:l,result:a,always:o,text:u}}limit(e,t,n,r={}){null==n||"object"!=typeof n||Array.isArray(n)||n.type||(r=n,n=void 0);const s=this.node(e),i=_p(s);if(!i&&Dl(s,"pre").some(({node:e})=>_p(e))){let e=s;for(const{node:t,path:n}of Dl(s,"post").filter(({node:e})=>_p(e)).reverse()){const r=this.limit(t,void 0,void 0,{steps:!1});if(!r.exists)return r;if(r.infinite)throw new Hl("a limit inside an expression that is infinite is not worked out here");e=Vl(e,n,r.result)}return{...this.simplify(e,r),exists:!0,infinite:!1}}const o=i?i.f:s,a=i?i.v:this.variable(s,t),l=i?i.to:"number"==typeof n?zl(String(n)):this.node(n??"0"),u="right"===r.side||"+"===r.side?1:"left"===r.side||"-"===r.side?-1:i?i.side:0;try{const{value:e,steps:t}=Sp(this,o,a,jp(l),u);return{...this.result(Tp(e),ff(t,Wu(o),{parse:Fl,replaceAt:Vl}),r),exists:!0,infinite:Boolean(e.inf)}}catch(e){if(!(e instanceof mp))throw e;const t={result:null,text:"does not exist",exists:!1,reason:e.message,steps:[]};if(!u&&!jp(l).inf){const e=e=>{try{return Tp(Sp(this,o,a,jp(l),e).value)}catch{return null}};t.left=e(-1),t.right=e(1)}return t}}solveSystem(e,t,n={}){const r=e.map(e=>this.node(e)),s=t??[...new Set(r.flatMap(e=>[...Xu(e)]))].sort(),i=function(e,t,n){const r=[],s=t.map(t=>{const r=Rf(t)?ku([Pu(t.args[0]),Cu(Pu(t.args[1]))]):Pu(t),s=n.map(t=>{const n=vf(r,t);if(!n||Math.max(0,...n.keys())>1)throw new Hl(`not linear in ${t}`);const s=n.get(1)??lu(Yl.ZERO);if(!fu(s))throw new Hl(`the coefficient of ${t} must be a number (it is ${e.format(Hu(s))})`);return s.q});let i=r;for(let e=0;e<n.length;e++)i=ku([i,Mu([lu(s[e].neg()),Pu(Il(n[e]))])]);for(const e of n)if(bf(i,e))throw new Hl(`not linear in ${e}`);return{coeffs:s,rhs:Cu(i)}}),i=()=>s.map(e=>Ff(Hu(ku(e.coeffs.map((e,t)=>Mu([lu(e),Pu(Il(n[t]))])))),Hu(e.rhs))).reduce((e,t)=>e?Tl("&",[e,t]):t,null),o=e=>lp[e]??`${e+1}th`,a=(t,n,s,o)=>{const a=i();a.s!==s.s&&r.push(e.step(t,n,["eliminate"],s,a,o))};let l=0;const u=[];for(let e=0;e<n.length&&l<s.length;e++){const t=s.findIndex((t,n)=>n>=l&&!t.coeffs[e].isZero);if(t<0)continue;const r=Il(n[e]);if(t!==l){const e=i();[s[l],s[t]]=[s[t],s[l]],a("system.swap","Swap",e,{v:r,row:o(l),other:o(t)})}const c=s[l],h=c.coeffs[e];if(!h.equals(Yl.ONE)){const e=i();c.coeffs=c.coeffs.map(e=>e.div(h)),c.rhs=Mu([lu(h.inv()),c.rhs]),a("system.scale","Divide",e,{v:r,row:o(l),by:Hu(lu(h))})}for(let t=0;t<s.length;t++){if(t===l||s[t].coeffs[e].isZero)continue;const n=i(),u=s[t].coeffs[e];s[t].coeffs=s[t].coeffs.map((e,t)=>e.sub(u.mul(c.coeffs[t]))),s[t].rhs=ku([s[t].rhs,Mu([lu(u.neg()),c.rhs])]);const h=u.sign<0?u.neg():u,f=h.equals(Yl.ONE);a(`system.${u.sign<0?"add":"subtract"}${f?"":"-multiple"}`,"Eliminate",n,{v:r,row:o(t),from:o(l),k:Hu(lu(h))})}u.push(e),l++}for(const e of s.slice(l))if(!fu(e.rhs)||!e.rhs.q.isZero)return{solution:null,steps:r,status:"none"};if(u.length<n.length)return{solution:null,steps:r,status:"many"};const c=new Map;return u.forEach((e,t)=>c.set(n[e],Hu(s[t].rhs))),{solution:c,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:this.select(i.steps,n.steps)}}substitute(e,t,n={}){const r=this.node(e);let s=r;for(const[e,n]of Object.entries(t))s=Vf(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:[...this.select(o,n.steps),...i.steps]}}defined(e){const t=this.set.view("define");return t.size?Bh(e,t,{format:this.format}).node:e}approximate(e,t={}){const n=this.defined(this.node(e));if(Xu(n).size&&!t.scope){const e=Nh(Wu(n),t);return{result:e,text:this.format(e),number:null,exact:!1}}const r=Mh(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(Tl("-",[n,r])),i=this.simplify(s,{steps:!1}).result;if("num"===i.type&&"0"===i.token)return{equal:!0,how:"exact"};const o=[...Xu(s)];if(!o.length)try{return{equal:Math.abs(Mh(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=Mh(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 Om(e={}){const t=!1===e.defaults?[]:[...xm,...e.complex?$m:[]],{specs:n,messages:r}=function(e){Th();const t=[],n={};for(const r of e){const e="string"==typeof r?Oc(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");$l(t.symbol)||yl({symbol:String(t.symbol),arity:"any"===t.arity?gl: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=iu(e.complex,()=>Ch(n)),i={...Am};for(const e of Object.keys(r))for(const t of Object.keys(i))t.startsWith(`${e}.`)&&!(t in r)&&delete i[t];return new Nm(s,{...i,...r},e.format??dm,e.read??null,Boolean(e.complex))}const Em=Symbol.for("inlinemath.expressions"),Im=new Map,zm={re:"Re",im:"Im",conj:"overline"},_m=["Re","Im","re","im","conj","arg"];function jm(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),`\\:${zm[e.op]??e.op}`)):t.push(e.token)};return n(e),t}function Tm(e,t){if(!t)return e;const n=new Map;for(const[e,r]of Object.entries(t))if("number"==typeof r?Number.isFinite(r):"bigint"==typeof r||"string"==typeof r)try{n.set(e,mr(String(r)))}catch{}if(!n.size)return e;const r=function(e){let t;try{t=E(e)}catch{return new Set}const n=e=>"symbol"===e?.type?e.value:"op"===e?.type&&["=","→"].includes(e.op)&&"symbol"===e.args[0].type?e.args[0].value:null,r=new Set;return _(t,e=>{if("op"!==e.type||e.args.length<2)return;const t=e.op.startsWith("\\:")?e.op.slice(2):e.op;["der","int","lim","diff","derivative","differentiate","integrate","integral","solve","limit"].includes(t)&&n(e.args[1])&&r.add(n(e.args[1]))}),r}(e);return e.flatMap(e=>n.has(e)&&!r.has(e)?n.get(e):[e])}const Cm={right:"right",r:"right","+":"right",left:"left",l:"left","-":"left"},Zm=new Set(["simplify","expand","factor","cancel","diff","integrate","solve","approx","limit"]),Fm={integral:"integrate",differentiate:"diff",approximate:"approx",simp:"simplify"};function Lm(e={}){const t=e.rules||e.names?null:e.complex?"complex":"default";if(t&&Im.has(t))return Im.get(t);const n=[...e.names??[],...e.complex?_m:[],...Zm,...Object.keys(Fm)],r=Om({...e,read:e=>mr(e,{names:n}),format:dm});return t&&Im.set(t,r),r}const Rm=e=>String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");var Bm='/*\n * Inline Math stylesheet. Everything is under .mv; colors are left to the page.\n *\n * The numbers marked "metric" must match the constants at the top of\n * src/layout.js (line-height 1, bar 0.06em, gap 0.1em); everything else can\n * be changed freely.\n *\n * Handy hooks:\n * .mv-n[data-node="4"] one node (ids from MathZetta)\n * .mv-var .mv-num .mv-word variables, numbers, function names\n * .mv-op-frac .mv-op-pow … a kind of operation\n * .mv-hl the class highlight() adds\n * --mv-hl highlight color\n */\n\n.mv {\n display: inline-block;\n font-family: "Inline Math Roman", "Latin Modern Roman", "STIX Two Text", "Cambria", "Times New Roman", serif;\n font-size: 1.2em;\n font-style: normal;\n font-weight: normal;\n line-height: 1; /* metric */\n white-space: nowrap;\n text-indent: 0;\n text-align: left;\n letter-spacing: 0;\n}\n.mv-display { display: block; text-align: center; margin: 0.6em 0; }\n.mv span, .mv svg { line-height: 1; }\n.mv-n { display: inline-block; border-radius: 0.12em; }\n\n/* ---- letters and signs -------------------------------------------------- */\n.mv-var { font-style: italic; padding-right: 0.03em; }\n.mv-num, .mv-word, .mv-name, .mv-ord, .mv-text, .mv-d, .mv-conj { font-style: normal; }\n.mv-prime { margin-left: 0.04em; }\n.mv-bin { margin: 0 0.22em; }\n.mv-rel { margin: 0 0.28em; }\n.mv-conj { margin: 0 0.6em; } /* x = 2 or x = 3 */\n.mv-punct { margin-right: 0.17em; }\n.mv-sign { margin-right: 0.04em; }\n.mv-times { display: inline-block; width: 0.06em; }\n.mv-callgap { display: inline-block; width: 0.05em; }\n.mv-fnspace { display: inline-block; width: 0.17em; }\n.mv-space { display: inline-block; width: 0.33em; }\n.mv-dx { display: inline-block; margin-left: 0.17em; }\n.mv-text { margin: 0 0.25em; }\n/* Tighter spacing in limits and exponents: n=1, x→0. */\n.mv-script .mv-rel, .mv-sup .mv-rel, .mv-sub .mv-rel { margin: 0 0.12em; }\n.mv-script .mv-bin, .mv-sup .mv-bin, .mv-sub .mv-bin { margin: 0 0.1em; }\n\n/* ---- fractions (metric: padding and border) ------------------------------ */\n.mv-frac { display: inline-flex; flex-direction: column; align-items: stretch; margin: 0 0.12em; }\n.mv-numer, .mv-denom { display: block; text-align: center; padding: 0 0.1em; }\n.mv-numer { padding-bottom: 0.1em; }\n.mv-denom { padding-top: 0.1em; border-top: 0.06em solid currentColor; }\n.mv-frac-nobar > .mv-denom { border-top: 0; }\n.mv-scaled { display: inline-block; }\n\n/* ---- scripts ----------------------------------------------------------------- */\n.mv-sup, .mv-sub { display: inline-block; margin-left: 0.04em; }\n.mv-subsup, .mv-limits { display: inline-flex; flex-direction: column; justify-content: space-between; align-items: flex-start; margin-left: 0.04em; }\n.mv-limits { margin-left: 0.02em; margin-right: 0.12em; }\n.mv-limits > .mv-lower { margin-left: -0.3em; }\n.mv-script { display: block; }\n.mv-under { display: inline-flex; flex-direction: column; align-items: center; margin-right: 0.15em; }\n.mv-under > .mv-script { margin-top: 0.05em; }\n.mv-bigop { display: inline-flex; flex-direction: column; align-items: center; margin: 0 0.12em; }\n.mv-bigop > .mv-script { display: block; margin: 0.08em 0; }\n.mv-bigop > svg { display: block; }\n\n/* ---- radicals (metric: border and padding-top) ----------------------------- */\n.mv-sqrt { display: inline-block; white-space: nowrap; }\n.mv-radicand { display: inline-block; position: relative; border-top: 0.06em solid currentColor; padding: 0.1em 0.1em 0 0.06em; }\n/* the hook, in the radicand\'s left margin (layout.js sets its width and that margin): from the bar\'s center\n (just below the middle of the 0.06em border above the box) to the bottom of what it holds, so the tip always meets the bar */\n.mv-hook { position: absolute; top: -0.02em; height: calc(100% + 0.02em); overflow: visible; } /* a hair below the center: never above the bar */\n.mv-rootindex { display: inline-block; margin: 0 -0.32em 0 0.12em; }\n\n/* ---- delimiters: drawn at the full height of what they enclose -------------- */\n.mv-fence { display: inline-block; position: relative; }\n.mv-delim { position: absolute; top: 0; bottom: 0; height: 100%; }\n.mv-delim-l { left: 0.03em; }\n.mv-delim-r { right: 0.03em; }\nspan.mv-delim { width: 0.16em; border: 0 solid currentColor; box-sizing: border-box; }\n.mv-delim.mv-lbrack { border-width: 0.06em 0 0.06em 0.06em; left: 0.06em; }\n.mv-delim.mv-rbrack { border-width: 0.06em 0.06em 0.06em 0; right: 0.06em; }\n.mv-delim.mv-vert { border-left-width: 0.06em; width: 0; left: 0.07em; }\n.mv-delim.mv-vert.mv-delim-r { left: auto; right: 0.07em; }\n.mv-delim.mv-lfloor { border-width: 0 0 0.06em 0.06em; }\n.mv-delim.mv-rfloor { border-width: 0 0.06em 0.06em 0; }\n.mv-delim.mv-lceil { border-width: 0.06em 0 0 0.06em; }\n.mv-delim.mv-rceil { border-width: 0.06em 0.06em 0 0; }\n/* around one line: inline, placed from the baseline like a typed bracket (0.25em below it, 0.75em above),\n not stretched over the line box, which sits higher or lower in every font; the margins keep the widths */\n.mv-fence-line > .mv-delim { position: static; display: inline-block; vertical-align: -0.25em; height: 1em; }\n.mv-fence-line > svg.mv-delim-l { margin: 0 0.07em 0 0.03em; }\n.mv-fence-line > svg.mv-delim-r { margin: 0 0.03em 0 0.07em; }\n.mv-fence-line > span.mv-delim-l { margin: 0 0.08em 0 0.06em; }\n.mv-fence-line > span.mv-delim-r { margin: 0 0.06em 0 0.08em; }\n.mv-fence-line > .mv-delim.mv-vert.mv-delim-l { margin: 0 0.11em 0 0.07em; }\n.mv-fence-line > .mv-delim.mv-vert.mv-delim-r { margin: 0 0.07em 0 0.11em; }\n\n/* ---- shapes ----------------------------------------------------------------- */\n.mv svg { overflow: visible; }\n.mv svg path[stroke] { stroke-width: 0.065em; stroke-linecap: round; stroke-linejoin: round; }\n.mv-intsign path[stroke] { stroke-width: 0.075em; }\n.mv-bigsign { display: inline-block; margin: 0 0.06em; }\n.mv-intsign { margin-right: 0.12em; }\n\n/* ---- piecewise ------------------------------------------------------------- */\n.mv-cases { display: inline-grid; grid-template-columns: auto auto; column-gap: 1em; row-gap: 0.25em; align-items: baseline; text-align: left; margin: 0 0.1em; }\n.mv-case-value, .mv-case-cond { display: block; }\n.mv-matrix { display: inline-grid; column-gap: 0.8em; row-gap: 0.3em; align-items: baseline; justify-items: center; margin: 0 0.15em; }\n.mv-matrix-row { display: contents; }\n.mv-matrix-cell { display: block; }\n\n/* ---- decorations: \\boxed \\cancel \\overline \\vec … --------------------------- */\n.mv-boxed { display: inline-block; border: 0.06em solid currentColor; padding: 0.16em 0.2em; }\n.mv-over { display: inline-block; position: relative; padding-top: 0.14em; }\n.mv-over::before { content: \'\'; position: absolute; left: 0; right: 0; top: 0.21em; border-top: 0.06em solid currentColor; } /* metric */\n.mv-over-low::before { top: 0.48em; }\n.mv-underline { display: inline-block; border-bottom: 0.06em solid currentColor; padding-bottom: 0.06em; }\n.mv-cancel { display: inline-block; position: relative; }\n.mv-cancel-line { position: absolute; left: 0; top: 0; width: 100%; height: 100%; overflow: visible; pointer-events: none; }\n.mv-accent { display: inline-block; position: relative; padding-top: 0.3em; }\n.mv-accent-mark { position: absolute; top: -0.27em; left: 0; right: 0; text-align: center; font-size: 0.7em; line-height: 0.6; } /* metric: measured over F, h, A */\n/* ˆ ˜ ˙ ¨ are spacing marks that sit high in their em: full size, pulled down onto the letter */\n.mv-accent-hat, .mv-accent-widehat, .mv-accent-tilde, .mv-accent-dot, .mv-accent-ddot { font-size: 1em; line-height: 1; top: 0.02em; }\n/* over an italic letter the mark leans with it, right of the box\'s center */\n.mv-accent:has(> .mv-var) > .mv-accent-mark { transform: translateX(0.1em); }\n/* a letter with no ascender (x, u, α; layout.js adds -low): the mark comes down to its top */\n.mv-accent-low > .mv-accent-mark { top: 0.08em; }\n.mv-accent-low > .mv-accent-hat, .mv-accent-low > .mv-accent-widehat, .mv-accent-low > .mv-accent-tilde, .mv-accent-low > .mv-accent-dot, .mv-accent-low > .mv-accent-ddot { top: 0.31em; }\n\n/* ---- interaction -------------------------------------------------------------- */\n.mv-hl { background: var(--mv-hl, rgba(255, 200, 0, 0.35)); box-shadow: 0 0 0 0.08em var(--mv-hl, rgba(255, 200, 0, 0.35)); }\n/* Windows high contrast (and other forced colors) drops backgrounds and shadows: outline a highlight instead */\n@media (forced-colors: active) {\n .mv-hl { outline: 0.08em solid Highlight; outline-offset: 0.04em; }\n}\n.mv-clickable .mv-n { cursor: pointer; }\n.mv-editable .mv-n:hover { outline: 1px dashed rgba(0, 0, 0, 0.25); }\n/* the box editing a part in place (view.editable, or a Markdown textbox variable) */\n.mv-edit { transform: translateY(-50%); z-index: 1000; box-sizing: content-box; padding: 0.1em 0.35em; font-family: inherit;\n border: 1px solid #1a5fb4; border-radius: 0.25em; background: #fff; color: #111; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.18); }\n.mv-edit[aria-invalid="true"] { border-color: #c33; outline: 2px solid #c33; }\n/* the live region a view announces steps through ({ announce: true }): read, never seen */\n.mv-sr-only, .mv-sr-math { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }\n.mv-clickable .mv-n:hover { outline: 1px dashed rgba(0, 0, 0, 0.25); }\n/* the keyboard: the expression is one tab stop, and the part the arrow keys are on is ringed */\n.mv[tabindex]:focus-visible { outline: 0.1em solid #1a5fb4; outline-offset: 0.12em; }\n.mv[tabindex]:focus .mv-focus { outline: 0.1em solid #1a5fb4; outline-offset: 0.06em; border-radius: 0.1em; }\n/* while a part is ringed, the whole expression\'s ring steps back so the part is the one that stands out */\n.mv[tabindex]:focus-visible:has(.mv-focus) { outline: 1px dashed #1a5fb4; }\n@media (forced-colors: active) {\n .mv[tabindex]:focus-visible, .mv[tabindex]:focus .mv-focus { outline-color: Highlight; }\n}\n\n/* ---- steps (stepsHTML from \'@mathzetta/inlinemath/cas\') ---------------------------------------- */\n.mv-steps { margin: 0; padding-left: 1.6em; }\n.mv-step { margin: 0.5em 0 0.9em; }\n.mv-step-name { display: block; font-size: 0.85em; font-weight: 600; color: #555; }\n.mv-step-maths { display: flex; flex-wrap: wrap; align-items: center; gap: 0.4em 0.8em; margin: 0.15em 0; }\n.mv-step-arrow { color: #888; }\n.mv-step-why { margin: 0.1em 0 0; font-size: 0.9em; color: #444; }\n\n/* ---- Markdown with math (markdownToHTML from \'@mathzetta/inlinemath/markdown\') ------------------- */\n.mv-md-math { display: inline-block; vertical-align: middle; }\n.mv-md-display { display: block; text-align: center; margin: 0.6em 0; overflow-x: auto; }\n.mv-md-block { margin: 0.8em 0; }\n.mv-md-error code { background: rgba(200, 60, 0, 0.08); color: #a33; border-bottom: 1px dotted #a33; }\n/* saved variables: $A := 2+2$ draws A ≔ 2 + 2; $A := [[…]]$ an input that sets A */\n.mv-md-input-def { display: inline-flex; align-items: center; gap: 0.3em; }\n.mv-md-assign { margin: 0 0.1em; }\n.mv-md-input { font: inherit; font-size: 0.9em; }\ninput.mv-md-textbox { font-family: inherit; padding: 0.05em 0.3em; field-sizing: content; min-width: 3ch; }\ninput.mv-md-textbox[aria-invalid="true"] { outline: 2px solid #c33; outline-offset: 1px; }\ninput.mv-md-slider { vertical-align: middle; }\n.mv-md-output { font-variant-numeric: tabular-nums; min-width: 2ch; }\n';const Pm=Bm;if("undefined"!=typeof document&&!document.getElementById("inlinemath-css")){const e=document.createElement("style");e.id="inlinemath-css",e.textContent=Bm,document.head.append(e)}return e.CSS=Pm,e.DEFAULTS=Ko,e.PATHS=zo,e.View=Ma,e.casBlocks=function(e={}){const t=e.cas??Lm(),n=void 0===e.steps?{}:{steps:e.steps},r=(e,s)=>{let i;try{i=t.read(e)}catch{return yo(e,s)}const o=s&&s[Em];o&&(i=i.flatMap(e=>Object.hasOwn(o,e)?o[e]:[e])),i=Tm(i,s);const a=i[i.length-1],l=a?.startsWith("\\:")?Fm[a.slice(2)]??a.slice(2):null,u=l&&Zm.has(l),c="der"===a||"int"===a||"lim"===a;if(!u&&!c)return yo(e,s);const h=t.node(i),f=c&&h.op!==a,p=u?h.args:[h],m=e=>e?e.s:void 0,d=(e,r,s)=>{if(!r||"="!==r.op)return t.diff(e,m(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(f?"simplify-read":u?l:"der"===a?"derivative":"lim"===a?"lim":"antiderivative"){case"simplify-read":g=t.simplify(h,n);break;case"simplify":g=t.simplify(p[0],n);break;case"expand":g=t.expand(p[0],n);break;case"factor":g=t.factor(p[0],n);break;case"cancel":g=t.cancel(p[0],n);break;case"diff":g=d(p[0],p[1],p[2]?Number(p[2].s):1);break;case"integrate":g=t.integrate(p[0],m(p[1]),{...n,...p[3]?{from:p[2].s,to:p[3].s}:{}});break;case"solve":g=t.solve(p[0],m(p[1]),n);break;case"lim":g=t.limit(h,void 0,void 0,n);break;case"limit":g=(([e,r,s,i])=>{let o=i?Cm[i.s.replace(/^\\/,"")]:void 0;if(i&&!o)throw new Error(`a side is right or left, not ${i.s}`);if(r&&"→"===r.op){[r,s]=r.args;const e="^"===s.op?s.args[1].s.replace(/^\\/,""):null;"+"!==e&&"-"!==e||(o=Cm[e],s=s.args[0])}return t.limit(e,m(r),s,{...n,...o?{side:o}:{}})})(p);break;case"approx":g=t.approximate(p[0],{...n,digits:p[1]?Number(p[1].s):15});break;case"derivative":g=d(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=ml(jm(g.result));return/^-?\d+(\.\d+)?$/.test(v)?v:`(${v})`};return r},e.createVariables=Ra,e.extractMath=Wa,e.layout=sa,e.markdownToHTML=function(e,t={}){return il(Ha(e,t,t.variables||null),t)},e.mathCAS=Lm,e.nodeAt=da,e.numberTree=va,e.pathOf=ga,e.render=function(e,t,n={}){return new Ma(e,t,n)},e.renderMarkdown=sl,e.renderMarkdownInto=function(e,t,n={}){const r=void 0===n.variables?Ba:n.variables||null;ll();const s=ol.get(e);s&&s.stop(s.store!==r);let i=Ha(t,n,r,e);if(e.innerHTML=il(i,n),!r)return ol.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{xa(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=ga(u,c)||[];let f=null;for(let e=h.length;e>=0&&!f;e--){const t=da(u,h.slice(0,e));t&&void 0!==t.from&&(f={node:t,depth:e})}const p=f&&r.definitions().get(f.node.from);if(p&&p.input&&"textbox"===p.input.kind){s.preventDefault();const t=p.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=>xa(e),c=da(u,h);return void qa(o,a(za(c,l)),{label:`Edit ${t}`,parse:e=>xa(e,{blocks:n.blocks}),commit:e=>{const n=ka(za(f.node,l),h.slice(f.depth),e);r.set(t,a(n))}})}const m=p&&i.defs.get(p.name),d=m&&m.key===p.key&&void 0!==m.start?{...i.math[l],start:m.start,end:m.end,raw:t.slice(m.start,m.end)}:i.math[l];e.dispatchEvent(new CustomEvent("inlinemath:select",{bubbles:!0,detail:{index:l,start:d.start,end:d.end,raw:d.raw,source:d.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,ll(),(()=>{const s=Ha(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),al.delete(h),ol.delete(e),t&&r.own(e,null)}const h={element:e,store:r,stop:c,connected:()=>o};return al.add(h),ol.set(e,h),e},e.select=pa,e.shouldAnimate=Sa,e.signature=fa,e.stepsHTML=function(e,t={}){return`<ol class="mv-steps">${e.map(e=>{const n=$a(jm(Fl(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>${$a(jm(Fl(e.to)),t)}`,s=e.explanation?`<p class="mv-step-why">${Rm(e.explanation)}</p>`:"";return`<li class="mv-step" data-rule="${Rm(e.id)}"><span class="mv-step-name">${Rm(e.name)}</span><div class="mv-step-maths">${n}${r}</div>${s}</li>`}).join("")}</ol>`},e.toHTML=$a,e.toText=ml,e.tokensOf=jm,e.treeOf=xa,e.variables=Ba,e}({});
|