t11_generate.py

back to table · edit · history · where entries came from · files · download

1815 bytes, as of the version from 2026-09-21 11:19 (current). Recorded here, not run.

"""Factorial of natural numbers -- numberdb.org/T11

Run it with SageMath:

    $ sage -pip install numberdb          # once
    $ sage -python generate.py            # check the table against this code
    $ sage -python generate.py --publish  # send it, with NUMBERDB_API_KEY set

The table holds exact integers. The range stops at 170 because 170! is the
largest factorial representable as a double-precision floating-point number;
171! overflows.
"""

import os
import sys

import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ


UP_TO = 170


def _key_from_stdin():
    if os.environ.get("NUMBERDB_KEY_FROM_STDIN") != "1":
        return
    token = sys.stdin.read().strip()
    if "=" in token and token.split("=", 1)[0].isupper():
        token = token.split("=", 1)[1].strip().strip("'\"")
    if token:
        os.environ["NUMBERDB_API_KEY"] = token


class Factorials(numberdb.Generator):

    table = "T11"
    parameters = ("n",)
    type = "Z"
    rigour = "exact"

    def enumerate(self, up_to=UP_TO):
        for n in range(up_to + 1):
            yield {"n": str(n)}

    def value(self, params, digits):
        return ZZ(params["n"]).factorial()


if __name__ == "__main__":
    _key_from_stdin()
    generator = Factorials()

    if os.environ.get("NUMBERDB_PUBLISH") == "1" or "--publish" in sys.argv:
        print(generator.publish(
            message="extend factorials through the double-precision limit",
            overwrite=False,
            assisted_by=os.environ.get("NUMBERDB_ASSISTED_BY", "codex-cli"),
        ))
    elif os.environ.get("NUMBERDB_PREVIEW") == "1" or "--preview" in sys.argv:
        print(generator.preview(overwrite=False))
    else:
        report = generator.verify(sample=None)
        print(report)
        sys.exit(0 if report.ok else 1)