rusqsieve 0.4.0

High-performance SIQS integer factorization for native Rust and WebAssembly
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
// Main thread: UI + coordinator. Peels easy factors with BigInt number theory and
// hands hard composites to a pool of wasm Web Workers running the quadratic sieve,
// with the pool sized to navigator.hardwareConcurrency.
import { loadModule, bytesToBigInt } from "./abi.js";
import { trialDivide, isPrime, perfectPower, pollardBrent, groupFactors, rsaNumber, bitLength } from "./numtheory.js";

const SIMD_WASM_URL = new URL("./rusqsieve-simd.wasm", import.meta.url);
const SCALAR_WASM_URL = new URL("./rusqsieve.wasm", import.meta.url);
// Small jobs reduce the tail after the relation target is reached. Two
// families was consistently best in Node/V8 from 192 through 256 bits.
const BATCH = 2;
// Keep the browser scheduler on the engine's bounded family domain. The last
// issued family is MAX_FAMILIES - 1.
const MAX_FAMILIES = 100_000;
const MAX_INPUT_BITS = 512;
const MAX_DECIMAL_DIGITS = 155;
const BOOT_TIMEOUT_MS = 30_000;
const JOB_TIMEOUT_MS = 120_000;
const RUN_TIMEOUT_MS = 30 * 60_000;

const els = {
  input: document.getElementById("input"),
  inputMirror: document.getElementById("input-mirror"),
  inputInfo: document.getElementById("input-info"),
  go: document.getElementById("go"),
  bar: document.getElementById("bar"),
  status: document.getElementById("status"),
  result: document.getElementById("result"),
  workers: document.getElementById("workers"),
  meter: document.getElementById("meter"),
  rsaBits: document.getElementById("rsa-bits"),
  rsaBitsLabel: document.getElementById("rsa-bits-label"),
  rsaGen: document.getElementById("rsa-gen"),
};

let coord = null; // coordinator Worker (owns its own wasm instance)
let workers = []; // sieve worker pool
let gen = 0; // generation token so stale worker messages are ignored
let wasmFlavor = "scalar";
let runtimeReady = false;
// Scaling remains positive through 32–48 workers on the 96-thread reference
// host, while 96 workers regress from startup, memory traffic, and job overshoot.
const nWorkers = Math.max(1, Math.min(48, navigator.hardwareConcurrency || 4));

async function boot() {
  runtimeReady = false;
  let module;
  try {
    module = await withTimeout(loadModule(SIMD_WASM_URL), BOOT_TIMEOUT_MS, "SIMD wasm load");
    wasmFlavor = "SIMD";
  } catch {
    // Older engines can still use the portable artifact.
    module = await withTimeout(
      loadModule(SCALAR_WASM_URL),
      BOOT_TIMEOUT_MS,
      "scalar wasm load",
    );
    wasmFlavor = "scalar";
  }
  const nextCoord = new Worker(new URL("./coordinator.js", import.meta.url), { type: "module" });
  const nextWorkers = Array.from(
    { length: nWorkers },
    () => new Worker(new URL("./worker.js", import.meta.url), { type: "module" }),
  );
  const bootAbort = new AbortController();
  try {
    const [coordinatorReady] = await Promise.all([
      waitForWorkerReady(nextCoord, module, true, bootAbort.signal),
      ...nextWorkers.map((worker) =>
        waitForWorkerReady(worker, module, false, bootAbort.signal),
      ),
    ]);
    coord = nextCoord;
    workers = nextWorkers;
    runtimeReady = true;
    els.workers.textContent =
      `${nWorkers} worker${nWorkers === 1 ? "" : "s"} · ${wasmFlavor} · ` +
      `ABI v${coordinatorReady.abi}`;
  } catch (error) {
    bootAbort.abort();
    nextCoord.terminate();
    for (const worker of nextWorkers) worker.terminate();
    throw error;
  }
  els.go.disabled = false;
  els.status.textContent = "Ready.";
}

function shutdownRuntime() {
  runtimeReady = false;
  coord?.terminate();
  for (const worker of workers) worker.terminate();
  coord = null;
  workers = [];
}

async function restartRuntime() {
  shutdownRuntime();
  els.go.disabled = true;
  await boot();
}

function waitForWorkerReady(worker, module, requireAbi, signal) {
  return new Promise((resolve, reject) => {
    let settled = false;
    const timer = setTimeout(
      () => finish(new Error("worker initialization timed out")),
      BOOT_TIMEOUT_MS,
    );
    const cleanup = () => {
      clearTimeout(timer);
      worker.removeEventListener("message", onMessage);
      worker.removeEventListener("error", onError);
      worker.removeEventListener("messageerror", onMessageError);
      signal?.removeEventListener("abort", onAbort);
    };
    const finish = (error, data) => {
      if (settled) return;
      settled = true;
      cleanup();
      if (error) reject(error);
      else resolve(data);
    };
    const onMessage = ({ data }) => {
      if (data?.type === "error") {
        finish(new Error(data.error || "worker initialization failed"));
      } else if (data?.type === "ready") {
        if (requireAbi && data.abi !== 2) {
          finish(new Error(`unsupported rusqsieve wasm ABI ${String(data.abi)}`));
        } else {
          finish(null, data);
        }
      }
    };
    const onError = (event) => {
      event.preventDefault?.();
      finish(new Error(event.message || "worker failed during initialization"));
    };
    const onMessageError = () => finish(new Error("worker initialization message was invalid"));
    const onAbort = () => finish(new Error("worker initialization cancelled"));
    worker.addEventListener("message", onMessage);
    worker.addEventListener("error", onError);
    worker.addEventListener("messageerror", onMessageError);
    signal?.addEventListener("abort", onAbort, { once: true });
    if (signal?.aborted) {
      onAbort();
      return;
    }
    try {
      worker.postMessage({ cmd: "init", module });
    } catch (error) {
      finish(error);
    }
  });
}

function withTimeout(promise, milliseconds, label) {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => reject(new Error(`${label} timed out`)), milliseconds);
    Promise.resolve(promise).then(
      (value) => {
        clearTimeout(timer);
        resolve(value);
      },
      (error) => {
        clearTimeout(timer);
        reject(error);
      },
    );
  });
}

// Parallel quadratic sieve for one hard composite; resolves to a nontrivial factor.
function siqsParallel(decimal, bits, report) {
  return new Promise((resolve, reject) => {
    const myGen = ++gen;
    const sieveStarted = performance.now();
    let target = 0;
    let relations = 0;
    let nextFamily = 0;
    let activeJobs = 0;
    let pendingSubmissions = 0;
    let preparedWorkers = 0;
    let finished = false;
    const workerBusy = new Array(workers.length).fill(false);
    const workerPrepared = new Array(workers.length).fill(false);
    const jobTimers = new Map();
    const runTimer = setTimeout(
      () => fail(new Error("factorization timed out")),
      RUN_TIMEOUT_MS,
    );

    const cleanup = () => {
      clearTimeout(runTimer);
      for (const timer of jobTimers.values()) clearTimeout(timer);
      jobTimers.clear();
      coord.onmessage = null;
      coord.onerror = null;
      coord.onmessageerror = null;
      for (const worker of workers) {
        worker.onmessage = null;
        worker.onerror = null;
        worker.onmessageerror = null;
      }
    };
    const fail = (error) => {
      if (finished) return;
      finished = true;
      cleanup();
      reject(error instanceof Error ? error : new Error(String(error)));
    };
    const succeed = (factor) => {
      if (finished) return;
      finished = true;
      cleanup();
      resolve(factor);
    };
    const maybeExhausted = () => {
      if (
        !finished &&
        nextFamily >= MAX_FAMILIES &&
        activeJobs === 0 &&
        pendingSubmissions === 0 &&
        preparedWorkers === workers.length
      ) {
        fail(new Error(`relation budget exhausted after ${MAX_FAMILIES} families`));
      }
    };
    const dispatch = (worker, workerIndex) => {
      if (finished || workerBusy[workerIndex]) return false;
      if (nextFamily >= MAX_FAMILIES) {
        maybeExhausted();
        return false;
      }
      const family = nextFamily;
      const count = Math.min(BATCH, MAX_FAMILIES - nextFamily);
      nextFamily += count;
      workerBusy[workerIndex] = true;
      activeJobs++;
      const timer = setTimeout(
        () => fail(new Error(`sieve worker ${workerIndex + 1} timed out`)),
        JOB_TIMEOUT_MS,
      );
      jobTimers.set(workerIndex, timer);
      try {
        worker.postMessage({ cmd: "sieve", family, count, gen: myGen });
      } catch (error) {
        clearTimeout(timer);
        jobTimers.delete(workerIndex);
        workerBusy[workerIndex] = false;
        activeJobs--;
        fail(error);
        return false;
      }
      return true;
    };
    const finishJob = (workerIndex) => {
      if (!workerBusy[workerIndex]) {
        fail(new Error(`unexpected response from idle sieve worker ${workerIndex + 1}`));
        return false;
      }
      clearTimeout(jobTimers.get(workerIndex));
      jobTimers.delete(workerIndex);
      workerBusy[workerIndex] = false;
      activeJobs--;
      return true;
    };

    coord.onmessage = ({ data }) => {
      if (data?.gen !== myGen) return;
      if (data.type === "error") {
        fail(new Error(data.error || "coordinator failed"));
      } else if (data.type === "session") {
        if (!Number.isInteger(data.target) || data.target <= 0) {
          fail(new Error("coordinator returned an invalid relation target"));
          return;
        }
        target = data.target;
        try {
          for (const w of workers) {
            w.postMessage({ cmd: "prepare", n: decimal, gen: myGen });
          }
        } catch (error) {
          fail(error);
        }
      } else if (data.type === "submitted") {
        if (pendingSubmissions <= 0) {
          fail(new Error("coordinator acknowledged an unknown submission"));
          return;
        }
        pendingSubmissions--;
        if (
          !Number.isInteger(data.worker) ||
          data.worker < 0 ||
          data.worker >= workers.length ||
          !Number.isInteger(data.relations) ||
          data.relations < relations ||
          !Number.isInteger(data.target) ||
          data.target <= 0
        ) {
          fail(new Error("coordinator returned invalid progress"));
          return;
        }
        relations = data.relations;
        target = data.target;
        const now = performance.now();
        const elapsedSeconds = (now - sieveStarted) / 1000;
        // The accepted relation count accelerates as the partial-relation graph
        // accumulates edges and closes more cycles. A linear rate extrapolation
        // is therefore wildly pessimistic early in 272-bit runs. The measured
        // browser curve is close to relations ∝ time^1.6; invert that curve to
        // estimate total sieve time without embedding a machine-specific rate.
        const progress = target > 0 ? Math.min(1, relations / target) : 0;
        const etaSeconds =
          progress >= 0.03 ? elapsedSeconds * (progress ** (-1 / 1.6) - 1) : null;
        report({
          phase: "sieving",
          bits,
          relations,
          target,
          elapsedSeconds,
          etaSeconds,
        });
        if (!finished) {
          dispatch(workers[data.worker], data.worker);
          maybeExhausted();
        }
      } else if (data.type === "linalg") {
        report({ phase: "linalg" });
      } else if (data.type === "factor") {
        if (!(data.factor instanceof Uint8Array)) {
          fail(new Error("coordinator returned a malformed factor"));
          return;
        }
        const factor = bytesToBigInt(data.factor);
        const composite = BigInt(decimal);
        if (factor <= 1n || factor >= composite || composite % factor !== 0n) {
          fail(new Error("coordinator returned an invalid factor"));
          return;
        }
        succeed(factor);
      } else {
        fail(new Error(`unknown coordinator response: ${String(data.type)}`));
      }
    };
    coord.onerror = (event) => {
      event.preventDefault?.();
      fail(new Error(event.message || "coordinator worker crashed"));
    };
    coord.onmessageerror = () => fail(new Error("coordinator returned an invalid message"));

    workers.forEach((w, workerIndex) => {
      w.onmessage = ({ data }) => {
        // Every run response, including errors, is generation-scoped. Old jobs
        // may finish after a successful factor was already returned.
        if (data?.gen !== myGen) return;
        if (data.type === "error") {
          fail(new Error(data.error || `sieve worker ${workerIndex + 1} failed`));
          return;
        }
        if (finished) return;
        if (data.type === "prepared") {
          if (workerPrepared[workerIndex]) {
            fail(new Error(`sieve worker ${workerIndex + 1} prepared twice`));
            return;
          }
          if (!data.ok) {
            fail(new Error(`sieve worker ${workerIndex + 1} could not build a sieve`));
            return;
          }
          workerPrepared[workerIndex] = true;
          preparedWorkers++;
          dispatch(w, workerIndex);
        } else if (data.type === "relations") {
          if (!finishJob(workerIndex)) return;
          if (data.payload) {
            if (!(data.payload instanceof Uint8Array)) {
              fail(new Error(`sieve worker ${workerIndex + 1} returned invalid relations`));
              return;
            }
            pendingSubmissions++;
            try {
              coord.postMessage(
                { cmd: "submit", payload: data.payload, worker: workerIndex, gen: myGen },
                [data.payload.buffer],
              );
            } catch (error) {
              pendingSubmissions--;
              fail(error);
            }
            return;
          }
          fail(new Error(`sieve worker ${workerIndex + 1} could not serialize relations`));
        } else {
          fail(new Error(`unknown sieve-worker response: ${String(data.type)}`));
        }
      };
      w.onerror = (event) => {
        event.preventDefault?.();
        fail(new Error(event.message || `sieve worker ${workerIndex + 1} crashed`));
      };
      w.onmessageerror = () =>
        fail(new Error(`sieve worker ${workerIndex + 1} returned an invalid message`));
    });
    try {
      coord.postMessage({ cmd: "new", n: decimal, gen: myGen });
    } catch (error) {
      fail(error);
    }
  });
}

async function factorize(N, report) {
  const primes = [];
  const stack = [N];
  while (stack.length) {
    let c = stack.pop();
    report({ phase: "trial", n: c });
    await tick();
    c = trialDivide(c, primes);
    if (c === 1n) continue;
    report({ phase: "primality", n: c });
    await tick();
    if (isPrime(c)) {
      primes.push(c);
      continue;
    }
    const pp = perfectPower(c);
    if (pp) {
      for (let i = 0; i < pp.k; i++) stack.push(pp.base);
      continue;
    }
    // Pollard-Brent is a cheap opportunistic peel, not the primary tool at any size: it costs
    // O(sqrt p) in the smallest factor while the sieve costs by the size of `c`, so it only wins
    // where `c` is unbalanced. This used to spend a 2^21 budget below 84 bits on the theory that
    // rho owned that range. Measured here in node (BigInt, single-threaded), 2^21 against 2^15:
    // an 80-bit balanced semiprime 825 ms vs 44 ms, an 85-bit one 724 ms vs 44 ms, while the
    // unbalanced 127-bit case splits in 0.3 ms either way — and the sieve handles those sizes in
    // milliseconds. The large budget was up to 825 ms of blocked main thread for nothing.
    report({ phase: "pollard", n: c });
    await tick();
    const d = pollardBrent(c, 1 << 15);
    if (d && d > 1n && d < c) {
      stack.push(d, c / d);
      continue;
    }
    const factor = await siqsParallel(c.toString(), bitLength(c), report);
    if (factor <= 1n || factor >= c || c % factor !== 0n) {
      throw new Error("quadratic sieve returned an invalid factor");
    }
    stack.push(factor, c / factor);
  }
  return groupFactors(primes);
}

const tick = () => new Promise((r) => setTimeout(r, 0));
const SUP = { "0": "", "1": "¹", "2": "²", "3": "³", "4": "", "5": "", "6": "", "7": "", "8": "", "9": "" };
const sup = (n) => String(n).replace(/\d/g, (d) => SUP[d]);

const PHASE_TEXT = {
  trial: (s) => `Trial division on a ${digits(s.n)}-digit number`,
  primality: (s) => `MillerRabin primality test (${digits(s.n)} digits)`,
  pollard: (s) => `Pollard's rho on a ${digits(s.n)}-digit number`,
  sieving: (s) => {
    const progress =
      `Quadratic sieve: ${s.relations}/${s.target} relations across ${nWorkers} workers`;
    if (s.bits <= 256) return progress;
    const elapsed = `elapsed ${formatDuration(s.elapsedSeconds)}`;
    const eta =
      Number.isFinite(s.etaSeconds) && s.etaSeconds >= 0
        ? `ETA  ${formatDuration(s.etaSeconds)}`
        : "ETA calculating…";
    return `${progress} ${elapsed} · ${eta}`;
  },
  linalg: () => `Linear algebra over GF(2)  extracting a factor`,
};
const digits = (n) => n.toString().length;
const normalizeNumberText = (text) =>
  text
    .replace(/[-]/gu, (digit) => String(digit.codePointAt(0) - 0xff10))
    .replace(/[\p{White_Space}\uFEFF]/gu, "");
const formatDuration = (seconds) => {
  const rounded = Math.max(0, Math.round(seconds));
  if (rounded < 60) return `${rounded}s`;
  const minutes = Math.floor(rounded / 60);
  const remainder = rounded % 60;
  return `${minutes}m ${String(remainder).padStart(2, "0")}s`;
};

function render(grouped, original, seconds) {
  const plain = grouped
    .map(({ prime, exponent }) => (exponent === 1 ? `${prime}` : `${prime}^${exponent}`))
    .join(" * ");
  let product = 1n;
  for (const { prime, exponent } of grouped) product *= prime ** BigInt(exponent);
  const verified = product === original;
  els.result.innerHTML = "";

  // Each factor is shown with its own bit length beneath it, joined by "·".
  const big = document.createElement("div");
  big.className = "factors";
  if (!grouped.length) {
    big.textContent = "1";
  } else {
    grouped.forEach(({ prime, exponent }, i) => {
      if (i) {
        const sep = document.createElement("span");
        sep.className = "sep";
        sep.textContent = "·";
        big.append(sep);
      }
      const factor = document.createElement("span");
      factor.className = "factor";
      const value = document.createElement("span");
      value.className = "value";
      value.textContent = exponent === 1 ? `${prime}` : `${prime}${sup(exponent)}`;
      const bits = document.createElement("span");
      bits.className = "bits";
      bits.textContent = `${bitLength(prime)} bits`;
      factor.append(value, bits);
      big.append(factor);
    });
  }

  const meta = document.createElement("div");
  meta.className = "meta";
  meta.textContent =
    `${grouped.length} distinct prime${grouped.length === 1 ? "" : "s"} · ` +
    `${bitLength(original)}-bit input · ` +
    `${verified ? "✓ verified" : "✗ VERIFICATION FAILED"} · ` +
    `${seconds.toFixed(seconds < 10 ? 2 : 1)} s`;
  const copy = document.createElement("code");
  copy.className = "plain";
  copy.textContent = plain || "1";
  els.result.append(big, meta, copy);
  els.result.classList.toggle("bad", !verified);
}

// Live "N digits · M bits" readout for whatever is currently in the input box.
function updateInputInfo() {
  const text = normalizeNumberText(els.input.value);
  const significant = text.replace(/^0+/u, "") || "0";
  if (/^\d+$/.test(text) && significant.length > MAX_DECIMAL_DIGITS) {
    els.inputInfo.textContent =
      `${significant.length} significant digits · exceeds the ${MAX_INPUT_BITS}-bit limit`;
  } else if (/^\d+$/.test(text) && BigInt(text) > 0n) {
    const N = BigInt(text);
    const bits = bitLength(N);
    els.inputInfo.textContent =
      `${text.length} digit${text.length === 1 ? "" : "s"} · ${bits} bits` +
      (bits > MAX_INPUT_BITS ? ` · limit ${MAX_INPUT_BITS}` : "");
  } else {
    els.inputInfo.textContent = "";
  }
}

function resizeNumberInput() {
  // The mirror participates in layout while the textarea overlays it. Updating
  // the mirror, rather than the control's value, cannot disturb IME state.
  els.inputMirror.textContent = `${els.input.value}\u200b`;
}

function normalizeNumberInput() {
  const normalized = normalizeNumberText(els.input.value);
  if (normalized !== els.input.value) els.input.value = normalized;
  resizeNumberInput();
  updateInputInfo();
  return normalized;
}

function insertAtNumberSelection(text) {
  els.input.setRangeText(text, els.input.selectionStart, els.input.selectionEnd, "end");
  resizeNumberInput();
  updateInputInfo();
}

async function run() {
  const text = normalizeNumberInput();
  if (!/^\d+$/.test(text)) {
    els.status.textContent = "Enter a positive whole number.";
    return;
  }
  const significant = text.replace(/^0+/u, "") || "0";
  if (significant.length > MAX_DECIMAL_DIGITS) {
    els.status.textContent = `Enter a number no wider than ${MAX_INPUT_BITS} bits.`;
    return;
  }
  const N = BigInt(text);
  if (N < 1n) {
    els.status.textContent = "Enter a positive whole number.";
    return;
  }
  if (bitLength(N) > MAX_INPUT_BITS) {
    els.status.textContent = `Enter a number no wider than ${MAX_INPUT_BITS} bits.`;
    return;
  }
  els.go.disabled = true;
  els.result.innerHTML = "";
  els.result.classList.remove("bad");
  els.meter.classList.add("busy");
  setBar(0, true);
  const t0 = performance.now();
  const report = (s) => {
    els.status.textContent = (PHASE_TEXT[s.phase] || (() => s.phase))(s);
    if (s.phase === "sieving" && s.target) setBar(s.relations / s.target, false);
    else setBar(0, true);
  };
  try {
    if (N === 1n) {
      render([], 1n, 0);
      els.status.textContent = "1 has no prime factors.";
    } else {
      const grouped = await factorize(N, report);
      render(grouped, N, (performance.now() - t0) / 1000);
      els.status.textContent = "Done.";
    }
  } catch (error) {
    const message = String(error?.message || error);
    els.status.textContent = `Error: ${message} Resetting workers`;
    try {
      await restartRuntime();
      els.status.textContent = `Error: ${message} Worker runtime was reset.`;
    } catch (restartError) {
      els.status.textContent =
        `Error: ${message} Worker reset failed: ` +
        String(restartError?.message || restartError);
    }
  } finally {
    els.meter.classList.remove("busy");
    setBar(0, false);
    els.go.disabled = !runtimeReady;
  }
}

function setBar(fraction, indeterminate) {
  els.meter.classList.toggle("indeterminate", indeterminate);
  els.bar.style.width = indeterminate ? "100%" : `${Math.min(100, Math.max(0, fraction * 100)).toFixed(1)}%`;
}

els.go.addEventListener("click", run);
els.input.addEventListener("keydown", (e) => {
  // Enter confirms many IME candidates. Never intercept it while composition
  // is active (keyCode 229 covers older engines that omit isComposing).
  if (e.isComposing || e.keyCode === 229) return;
  if (e.key === "Enter") {
    e.preventDefault();
    if (!els.go.disabled) run();
  }
});
els.input.addEventListener("beforeinput", (e) => {
  if (e.isComposing) return;
  const lineAction = e.inputType === "insertLineBreak" || e.inputType === "insertParagraph";
  const hasLine = typeof e.data === "string" && /[\n\r\u2028\u2029]/u.test(e.data);
  if (!lineAction && !hasLine) return;
  e.preventDefault();
  if (hasLine) insertAtNumberSelection(e.data.replace(/[\n\r\u2028\u2029]/gu, ""));
});
els.input.addEventListener("paste", (e) => {
  const pasted = e.clipboardData?.getData("text");
  if (pasted == null || !/[\n\r\u2028\u2029]/u.test(pasted)) return;
  e.preventDefault();
  insertAtNumberSelection(pasted.replace(/[\n\r\u2028\u2029]/gu, ""));
});
els.input.addEventListener("input", () => {
  resizeNumberInput();
  updateInputInfo();
});
els.input.addEventListener("blur", normalizeNumberInput);

// RSA-style semiprime generator (128–384 bits, in steps of 16).
els.rsaBits.addEventListener("input", () => {
  els.rsaBitsLabel.textContent = `${els.rsaBits.value} bits`;
});
els.rsaGen.addEventListener("click", () => {
  const bits = Number(els.rsaBits.value);
  els.rsaGen.disabled = true;
  els.rsaGen.textContent = "Generating…";
  // Yield one frame so the disabled/label state paints before the (synchronous,
  // but brief) prime search runs.
  requestAnimationFrame(() => {
    try {
      els.input.value = rsaNumber(bits).toString();
      resizeNumberInput();
      updateInputInfo();
      els.input.focus();
    } catch (e) {
      els.status.textContent = "Generator error: " + (e?.message || e);
    } finally {
      els.rsaGen.disabled = false;
      els.rsaGen.textContent = "Generate";
    }
  });
});

els.go.disabled = true;
els.status.textContent = "Loading WebAssembly…";
resizeNumberInput();
boot().catch((e) => {
  shutdownRuntime();
  els.status.textContent = "Failed to load: " + (e?.message || e);
});