Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Math & Number Theory/Math / Number Theory

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.

Learn firstMath / Number TheoryUnlocksMobius Inversion & Multiplicative FunctionsFew Distinct Subarray OR / AND / GCD ValuesBurnside's Lemma / Polya Counting
0%
mastery
0/9 solved
Practise nextNumber of Subarrays With GCD Equal to K
IdeaPracticePitfalls

Recognise it

The signal

common divisors, reducing fractions

  1. 1Brute force

    Try every divisor.

  2. 2The observation

    Divisor enumeration: Euclid shrinks the pair geometrically.

  3. 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

Next

Number of Subarrays With GCD Equal to K

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

    CGCDSSQNumber of Subarrays With GCD Equal to K

Resources

  • Binary exponentiationcp-algorithms · article
  • Sieve of Eratosthenescp-algorithms · article
  • Modular inversecp-algorithms · article
  • DivisibilityUSACO Guide · course
  • CombinatoricsUSACO Guide · course
  • Math cheatsheetTech Interview Handbook · article
TodayReviewPatternsProblems