tools / math / is-prime.py

math/is-prime.py

mathcomputation○ hermeticpython3

Check whether a number is prime, and show its smallest prime factor if not. Pure computation, no network.

Use when the user asks whether a number is prime or for its smallest factor.

Run it

1. Once per machine: install fragletc (Docker must already be running).

curl -fsSL https://raw.githubusercontent.com/ofthemachine/fraglet/main/install.sh | sh

2. Fetch the tool and print its contract.

curl -fsSLO https://tools.ofthemachine.com/math/is-prime.py && chmod +x is-prime.py && ./is-prime.py --fraglet-help

3. Run it.

./is-prime.py -p n="<n>"

Parameters

nametyperequirementdescription
nstringrequiredInteger to test for primality

Outputs

stdout

Provenance

image
ofthemachine/python3@sha256:a015b4f9f0e7c1648f8fcd4164f6a296dd3c9189404f88f333a9764d08d13522
reach
network=none — a run is a pure function of its inputs; results are safe to memoize.
procedure_hash
sha256:5f53ce9a167214d6a6646be2fdc26967dbed499a1167bece04997d0c20ee22e5
receipt
add --receipt run.json to any run; receipt/attest.py verifies it against this hash without re-running.

Source

is-prime.py · 27 lines · sha256 5f53ce9a1672…
#!/usr/bin/env -S fragletc --image ofthemachine/python3@sha256:a015b4f9f0e7c1648f8fcd4164f6a296dd3c9189404f88f333a9764d08d13522
#: d=Check whether a number is prime, and show its smallest prime factor if not. Pure computation, no network.
#: when=Use when the user asks whether a number is prime or for its smallest factor.
#: network=none
#: stdin=none
#: param=n:required:d=Integer to test for primality
import os

n = int(os.environ["N"])
if n < 2:
    print("Prime: no")
    print("Reason: less than 2")
    raise SystemExit(0)

factor = None
i = 2
while i * i <= n:
    if n % i == 0:
        factor = i
        break
    i += 1

if factor:
    print("Prime: no")
    print(f"Smallest Factor: {factor}")
else:
    print("Prime: yes")