GCD/LCM, modular arithmetic, and bit manipulation tricks
Exploit mathematical properties and bit operations for constant-time hacks and logarithmic algorithms.
Use for parity/counting bits, fast exponentiation, and modular inverses.
Euclid's algorithm and lcm(a,b)=a/gcd*b
def gcd(a,b):
while b: a,b=b,a%b
return a
def lcm(a,b):
return a//gcd(a,b)*b
Fast pow, inverses (when applicable)
def mod_pow(a, e, m):
res=1; a%=m
while e:
if e&1: res=res*a%m
a=a*a%m; e>>=1
return res
Masks, shifts, popcount
def count_bits(n):
cnt=0
while n:
n&=n-1
cnt+=1
return cnt
def template(*args, **kwargs):
# General template placeholder
pass
Math/bit ops are constant or log.
Constant.