Files
rssearch/factor_extra.py

86 lines
2.8 KiB
Python

#!/usr/bin/env python3
"""Factor Phi_d(2) for d in {251,253,254,255,256} -- SEPARATE from factor_2m1.py.
Writes ~/workspace/rssearch/factors_extra.json (never touches factors_2m1.json).
Phi_256(2) = 2^128+1 has known factors (from gen_large_m.py); verify by product.
Others: sympy factorint with a per-d wall-clock timeout; record partial factors
and complete flag (product of prime powers == Phi_d(2))."""
import json, os, signal, time
from sympy import factorint
OUT = "/home/hatch/workspace/rssearch/factors_extra.json"
DS = [251, 253, 254, 255, 256]
PER_D_TIMEOUT = 900
KNOWN = {256: {59649589127497217: 1, 5704689200685129054721: 1}}
def divisors(m):
return [d for d in range(1, m + 1) if m % d == 0]
# Phi_d(2) via Mobius inversion over divisors, d = 1..256
phi_val = {1: 1}
for d in range(2, 257):
num = (1 << d) - 1
for dd in divisors(d):
if dd < d:
num //= phi_val[dd]
phi_val[d] = num
class Timeout(Exception):
pass
def _handler(signum, frame):
raise Timeout()
def factor_with_timeout(n, timeout):
signal.signal(signal.SIGALRM, _handler)
signal.alarm(timeout)
try:
return factorint(n, verbose=False)
finally:
signal.alarm(0)
def main():
data = {}
if os.path.exists(OUT):
with open(OUT) as f:
data = json.load(f)
for d in DS:
key = str(d)
if key in data and data[key].get("complete"):
print(f"d={d} already complete in extras", flush=True)
continue
n = phi_val[d]
t0 = time.time()
if d in KNOWN:
fac = {int(p): int(e) for p, e in KNOWN[d].items()}
prod = 1
for p, e in fac.items():
prod *= p ** e
complete = (prod == n)
print(f"d={d} known factors, complete={complete}", flush=True)
else:
try:
fac_raw = factor_with_timeout(n, PER_D_TIMEOUT)
fac = {int(p): int(e) for p, e in fac_raw.items()}
except Timeout:
fac = {}
print(f"d={d} TIMEOUT after {PER_D_TIMEOUT}s (partial: none)", flush=True)
except Exception as e:
fac = {}
print(f"d={d} ERROR {e}", flush=True)
prod = 1
for p, e in fac.items():
prod *= p ** e
complete = (prod == n) and bool(fac)
print(f"d={d} bits={n.bit_length()} complete={complete} nfac={len(fac)} "
f"t={time.time()-t0:.1f}s fac={fac}", flush=True)
data[key] = {"fac": {str(p): e for p, e in fac.items()},
"complete": bool(complete),
"bits": n.bit_length(), "time_s": round(time.time() - t0, 2)}
with open(OUT, "w") as f:
json.dump(data, f)
print("DONE", flush=True)
if __name__ == "__main__":
main()