{"type": "session", "harness": "opencode", "id": "math-0180", "name": "Modular Exponentiation and Multiplication"} {"type": "message", "message": {"role": "system", "content": "You are an expert mathematician and programmer."}} {"type": "message", "message": {"role": "user", "content": "Explain modular exponentiation and multiplication in detail"}} {"type": "message", "message": {"role": "assistant", "content": "Modular exponentiation: compute a^b mod m.\n\nBinary method: result=1; a=a%m; while(b>0) { if(b&1) result=result*a%m; a=a*a%m; b>>=1; } O(log b) multiplications.\n\nModular multiplication: (a*b)%m. Naive: a*b may overflow 64-bit.\n\nMethods to avoid overflow:\n1. __int128: compiler extension. result = (__int128)a*b % m. Fastest on x86-64.\n2. Russian peasant: double-and-add. while(b>0) { if(b&1) result=(result+a)%m; a=(a+a)%m; b>>=1; } O(log b).\n3. Montgomery multiplication: convert to Montgomery form, multiply, convert back. Batch operations: efficient for many multiplications.\n4. Barrett reduction: precompute floor(2^k/m), use approximation to avoid division.\n\nModular inverse: a^{-1} mod m. Extended Euclidean: O(log m). Or a^{m-2} mod m when m prime (Fermat).\n\nChinese Remainder Theorem: combine results from multiple moduli.\n\nApplications: RSA encryption/decryption, fast hashing, competitive programming modular arithmetic."}}