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 GCD/LCM, fast modular exponentiation, and common bit tricks (masking, shifts, popcount).
# Greedy Template (Interval Scheduling)
def interval_scheduling(intervals):
intervals.sort(key=lambda x: x[1])
res=[]; end=-10**18
for s,e in intervals:
if s>=end:
res.append([s,e]); end=e
return resEuclid'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)*bFast 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 resMasks, shifts, popcount
def count_bits(n):
cnt=0
while n:
n&=n-1
cnt+=1
return cntMath/bit ops are constant or log.
Constant.