{"type": "session", "harness": "opencode", "id": "math-0179", "name": "Advanced Modular Arithmetic"} {"type": "message", "message": {"role": "system", "content": "You are an expert mathematician and programmer."}} {"type": "message", "message": {"role": "user", "content": "Explain advanced modular arithmetic techniques"}} {"type": "message", "message": {"role": "assistant", "content": "Montgomery multiplication: convert a to Montgomery form a*R mod m where R=2^k. Multiplication in Montgomery form: REDC(a*b). Conversion back: REDC(a). Avoids expensive division by m.\n\nBarrett reduction: precompute mu = floor(2^k/m). q = floor(a*mu >> k). r = a - q*m. Adjust if r >= m.\n\nGarner's algorithm: reconstruct number from CRT residues without computing large product.\n\nHensel lifting: lift solutions mod p to mod p^k. If f(x)=0 mod p and f'(x)!=0 mod p, unique lift to mod p^2, etc.\n\nDiscrete logarithm: find x such that g^x = h (mod p). Baby-step giant-step: O(sqrt(p)) time and space.\n\nPrimitive root: generator g of (Z/pZ)*. Exists for all primes. Find by testing g^{(p-1)/q} != 1 for each prime factor q of p-1.\n\nQuadratic residues: x^2 = a (mod p) solvable iff a^{(p-1)/2} = 1 (mod p). Tonelli-Shanks algorithm for square roots mod p.\n\nApplications: Diffie-Hellman, ElGamal, discrete log crypto, quadratic residue proofs."}}