Primes, Divisors and GCD

Test primality, generate primes with the Sieve of Eratosthenes, factorize numbers and use GCD/LCM, the core number theory of coding rounds.

Intermediate · about 5 hours · difficulty 2/5

Learn first: Complexity Analysis

Number theory questions in online assessments are usually about primes, divisors and GCD. A few standard techniques cover most of them.

Primality and divisors

  • Trial division up to sqrt(n): if n has a divisor greater than sqrt(n), it also has one smaller. This gives O(sqrt n) primality tests and divisor enumeration.
  • Divisors come in pairs (d, n/d), so loop d from 1 while d * d <= n.

Sieve of Eratosthenes

To find all primes up to N, mark multiples of each prime starting from p * p. Complexity is O(N log log N). A smallest prime factor (SPF) sieve stores the smallest prime dividing each number, letting you factorize any number up to N in O(log n).

GCD and LCM

Euclid's algorithm: gcd(a, b) = gcd(b, a mod b), running in O(log min(a, b)). Then lcm(a, b) = a / gcd(a, b) * b (divide first to avoid overflow). Use built-ins like std::gcd or math.gcd in real code.

Where it appears

Counting coprime pairs, simplifying fractions, "make array elements equal" problems, and GCD of a subarray. Pitfalls: forgetting that 1 is not prime, overflowing i * i in the sieve loop, and sieving past memory limits (a sieve to 10^7 is fine, 10^9 is not).

Key concepts

  • Trial division up to sqrt(n)
  • Enumerating divisors
  • Sieve of Eratosthenes
  • Smallest prime factor sieve
  • Prime factorization
  • Euclid GCD and LCM
  • Segmented sieve
  • Euler's totient

Mini project

Solve 7 problems: Count Primes, check prime in O(sqrt n), print all divisors, prime factorization with an SPF sieve, GCD of Strings, Find Greatest Common Divisor of Array, and CSES Counting Divisors.

Check yourself

Why does the sieve start crossing out multiples of p from p * p rather than from 2 * p?

Free resources