Universal Code Competition Template in Python3 (editing) [2022]
Number Theory
Quick power and modulo
To calculate $ n^m % mod $:
Division and modulo
DO NOT dividing an integer by another integer with respect to the modulus $mod$.
To calculate $ n/m%mod $ correctly ($ mod$ is a prime number thus $ φ(mod)=mod-1 $).
Use Eular function or modular multiplicative inversion.
Euler function $ φ(n) $
Quick greatest common divisor
1 | def kgcd(a, b): |
Extended Euclid Theorem
Solve $ ax+by=gcd(a,b) $, of which the value of $ a $ and of $ b $ are known.
Either $x$ or $y$ can be negative.
1 | def extgcd(a, b): |
Modular multiplicative inverse
Wiki: A modular multiplicative inverse of an integer $a$ is an integer $x$ such that the product $ax$ is congruent to 1 with respect to the modulus $m$.
In the standard notation of modular arithmetic this congruence is written as
$
ax \equiv 1 \pmod{m}
$
If using Extended Euclid Theorem:
1 | def cal_inv(n, mod): |
According to Euler’s theorem, if $ a$ is coprime to $ m$, that is, $ gcd(a, m) = 1$, then $ a^φ(m)≡1\pmod{m}$,where $ φ(m)$ is Euler’s totient function.
$ a^{φ(m)-1}≡a^{-1}\pmod{m}$.
In the special case when $ m$ is a prime, the modular inverse is given by the below equation as: $ a^{-1}≡a^{m-2}\pmod{m}$.
If using Euler function:
1 | def cal_inv(n, mod): |
If generating multiple inversions:
1 | def cal_inv(int maxn, long mod): |
Universal Code Competition Template in Python3 (editing) [2022]