import { modinv, modpow, modsqrt } from "./math.js"; function binaryOpPop(stack) { const b = stack.pop(); const a = stack.pop(); if (a === undefined || b === undefined) { throw new Error("invalid expression"); } return [a, b]; } function compute(queue, modulus) { const stack = []; for (const token of queue) { if (typeof token === "bigint") { stack.push(token); } else if (token === "+") { let [a, b] = binaryOpPop(stack); a %= modulus; b %= modulus; const c = (a + b) % modulus; stack.push(c); } else if (token === "-") { let [a, b] = binaryOpPop(stack); a %= modulus; b %= modulus; const c = (a - b) % modulus; stack.push(c); } else if (token === "*") { let [a, b] = binaryOpPop(stack); a %= modulus; b %= modulus; const c = (a * b) % modulus; stack.push(c); } else if (token === "/") { let [a, b] = binaryOpPop(stack); a %= modulus; b %= modulus; const binv = modinv(b, modulus); const c = (a * binv) % modulus; stack.push(c); } else if (token === "u") { let a = stack.pop(); if (a === undefined) { throw new Error("invalid expression"); } a *= -1n; stack.push(a); } else if (token === "^") { const [a, b] = binaryOpPop(stack); const c = modpow(a, b, modulus); stack.push(c); } else if (token === "sqrt") { const a = stack.pop(); const s = modsqrt(a, modulus); stack.push(s); } } if (stack.length !== 1) { throw new Error("error evaluating expression"); } let result = stack[0] % modulus; if (result < 0n) { result += modulus; } return result; } export { compute };