mcalc/modules/compute.js

79 lines
1.7 KiB
JavaScript
Raw Normal View History

2025-12-12 04:49:34 +00:00
import { tonelliShanks, modinv, modpow, isprime } from "./math.js";
2025-12-12 04:49:34 +00:00
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);
2025-12-12 04:49:34 +00:00
} else if (token === "u") {
let a = stack.pop();
if (a === undefined) {
throw new Error("invalid expression");
}
a *= -1n;
stack.push(a);
2025-12-12 04:49:34 +00:00
} else if (token === "^") {
const [a, b] = binaryOpPop(stack);
const c = modpow(a, b, modulus);
stack.push(c);
2025-12-12 04:49:34 +00:00
} else if (token === "sqrt") {
if (!isprime(modulus)) {
throw new Error("modulus must be prime to compute square root");
}
const a = stack.pop();
const s = tonelliShanks(a, modulus);
stack.push(s);
2025-12-12 04:49:34 +00:00
}
}
if (stack.length !== 1) {
throw new Error("error evaluating expression");
}
let result = stack[0] % modulus;
if (result < 0n) {
result += modulus;
}
return result;
}
export { compute };