tinycodinglm / math /math-0180.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 16)
d517dc9 verified
|
Raw History Blame Contribute Delete
1.37 kB
opencode trace
System You are an expert mathematician and programmer.

You are an expert mathematician and programmer.

User

Explain modular exponentiation and multiplication in detail

Assistant

Modular exponentiation: compute a^b mod m.

Binary method: result=1; a=a%m; while(b>0) { if(b&1) result=resulta%m; a=aa%m; b>>=1; } O(log b) multiplications.

Modular multiplication: (ab)%m. Naive: ab may overflow 64-bit.

Methods to avoid overflow:

  1. __int128: compiler extension. result = (__int128)a*b % m. Fastest on x86-64.
  2. Russian peasant: double-and-add. while(b>0) { if(b&1) result=(result+a)%m; a=(a+a)%m; b>>=1; } O(log b).
  3. Montgomery multiplication: convert to Montgomery form, multiply, convert back. Batch operations: efficient for many multiplications.
  4. Barrett reduction: precompute floor(2^k/m), use approximation to avoid division.

Modular inverse: a^{-1} mod m. Extended Euclidean: O(log m). Or a^{m-2} mod m when m prime (Fermat).

Chinese Remainder Theorem: combine results from multiple moduli.

Applications: RSA encryption/decryption, fast hashing, competitive programming modular arithmetic.