Technique
GCD / LCM & Euclid
gcd(a, b) = gcd(b, a mod b) in O(log); lcm = a / gcd * b; extended Euclid solves ax + by = g and modular inverses.
0%
mastery
0/9 solved
0/9 solved
Recognise it
The signal
common divisors, reducing fractions
1Brute force
Try every divisor.
2The observation
Divisor enumeration: Euclid shrinks the pair geometrically.
3Why it works
gcd(a, b) = gcd(b, a mod b).
Reach for it when
- +gcd of string patterns
- +Bezout / reachability of amounts
Not when
- ×need all divisors (enumerate up to sqrt)
Practice
0/9 solved
- Greatest Common Divisor of StringsEasy
- Number of Subarrays With GCD Equal to KMedium
- Row GCDCodeforces1600
- Fadi and LCMCodeforces1400
- CGCDSSQCodeforces2000
- Ant colonyCodeforces2100
- Water Containers QueriesCSESHard
- Water Containers MovesCSESHard
- Prefix GCDCodeforces2200
Pitfalls
Misconceptions
- !computing a*b before dividing (overflow) for lcm
Go deeper1 combinations · resources
Combinations
Few Distinct Subarray OR / AND / GCD Values+GCD / LCM & Euclid+Hash Map / Hash Set Lookup
the number of subarrays whose gcd equals x, for many x
- Few Distinct Subarray OR / AND / GCD Values:
- O(log V) (gcd, count) pairs per right end
- GCD / LCM & Euclid:
- the gcd as j moves left only drops to a divisor
- Hash Map / Hash Set Lookup:
- global count of subarrays per gcd value