man number-theory/gcd-over-arrays

lesson 3 of 27 · Divisibility and the Euclidean algorithm

GCD over arrays and subarrays

lib / Number theory for competitive programming 14 mindraft

checked against: proofs in the text, code tested with Python 3.15.2

code: toothywalrus/cp-math@lesson-03

An array of 10510^5 numbers has about 5⋅1095 \cdot 10^9 subarrays. How many of them have gcd exactly 3? Computing each gcd is hopeless, but it is not needed: among the subarrays that end at one index there are only a handful of distinct gcds, at most 1+log⁡21 + \log_2 of the last element. This lesson proves that, and before it the simpler tools for gcds over arrays: folding, prefix and suffix gcds, and a trick with differences that turns a gcd of nn shifted numbers into a gcd of two.

The code is in cp-math at tag lesson-03, in cpmath/gcd_arrays.py. Its tests compare every function with brute force over all subarrays of thousands of random arrays, and python3 -m cpmath.lesson03 prints every output on this page.

The gcd of a list

The gcd of several numbers is the largest number dividing all of them. It can be computed two at a time:

gcd⁡(a1,…,an)=gcd⁡(gcd⁡(a1,…,an−1), an).\gcd(a_1, \dots, a_n) = \gcd\bigl(\gcd(a_1, \dots, a_{n-1}),\ a_n\bigr).

Proof. Lesson 1 showed that the common divisors of two numbers are exactly the divisors of their gcd. Let g=gcd⁡(a1,…,an−1)g = \gcd(a_1, \dots, a_{n-1}); by induction on nn, the common divisors of a1,…,an−1a_1, \dots, a_{n-1} are exactly the divisors of gg. So a number divides all of a1,…,ana_1, \dots, a_n if and only if it divides gg and ana_n, if and only if it divides gcd⁡(g,an)\gcd(g, a_n). The two sides have the same divisors, so they are equal. ■\blacksquare

So the gcd is associative and commutative, the order does not matter, and the empty list has gcd 0, the value that changes nothing (gcd⁡(0,x)=∣x∣\gcd(0, x) = \lvert x\rvert). In Python, math.gcd(*nums) does the whole list. Written out, with the one shortcut worth having:

def gcd_all(nums):
    """The gcd of a list (0 for an empty list). Stops early at 1, since
    the gcd cannot go lower."""
    g = 0
    for x in nums:
        g = gcd(g, x)
        if g == 1:
            break
    return g

The running values are the prefix gcds. Each one divides the one before, so they can only stay or drop:

a = [84, 126, 210, 35, 50]  prefix gcds: [84, 42, 42, 7, 1]  gcd_all: 1

What the fold costs

Measure the cost in the division steps of Euclid’s algorithm, which lesson 1 bounded by about log⁡φ\log_\varphi of the smaller number. (math.gcd is implemented differently for very large numbers, but the count is the right model.) Charging that to all nn calls gives O(nlog⁡M)O(n \log M) for numbers up to MM. The truth is better, because a call is only expensive when the running gcd drops a lot, and it can drop a lot only a few times.

Claim. For positive integers, computing g1=a1g_1 = a_1, gi=gcd⁡(ai,gi−1)g_i = \gcd(a_i, g_{i-1}) takes at most 2(n−1)+log⁡φ(a1/gn)2(n - 1) + \log_\varphi(a_1/g_n) division steps in total.

Proof. Euclid’s algorithm takes the same steps on (a,b)(a, b) as on (a/d,b/d)(a/d, b/d) for d=gcd⁡(a,b)d = \gcd(a, b): every quotient is the same. Lamé’s theorem from lesson 1, applied to the reduced pair, says that kk steps on (a,b)(a, b) with a>ba > b need b/d≥Fk+1≥φk−1b/d \ge F_{k+1} \ge \varphi^{k-1}, so k≤1+log⁡φ(b/d)k \le 1 + \log_\varphi(b/d). For the call gcd⁡(ai,gi−1)\gcd(a_i, g_{i-1}) with result gig_i: if ai>gi−1a_i > g_{i-1} it takes at most 1+log⁡φ(gi−1/gi)1 + \log_\varphi(g_{i-1}/g_i) steps; if ai=gi−1a_i = g_{i-1}, one step; if ai<gi−1a_i < g_{i-1}, one step to swap and then at most 1+log⁡φ(ai/gi)≤1+log⁡φ(gi−1/gi)1 + \log_\varphi(a_i/g_i) \le 1 + \log_\varphi(g_{i-1}/g_i). In every case the call takes at most 2+log⁡φ(gi−1/gi)2 + \log_\varphi(g_{i-1}/g_i). Adding over i=2,…,ni = 2, \dots, n, the logarithms telescope to log⁡φ(g1/gn)\log_\varphi(g_1/g_n). ■\blacksquare

So a fold over nn numbers up to MM costs O(n+log⁡M)O(n + \log M) division steps. Measured with the step counter from lesson 1:

n = 100000 multiples of 2**20 * 3**10 below 10**18: gcd = 61917364224, total division steps = 100012, bound 2(n-1) + log_phi(a[0]/g) = 200026.5
F(92), F(91), ..., F(2): 91 numbers, total steps = 180, bound = 270.3
gcd(F(91), F(92)) alone: 91 steps

The Fibonacci list is the bad case for a single call: its first gcd costs 91 steps, since the smaller number comes first. After it the running gcd is 1, and each of the 89 later calls costs one step, so the total is 180. gcd_all would stop as soon as the running gcd is 1, right after that first pair.

Prefix and suffix gcds: leaving one element out

A frequent question is the gcd of everything except aia_i, for every ii. Recomputing it nn times costs O(n2)O(n^2). Instead, keep pre[i]=gcd⁡(a0,…,ai−1)\mathit{pre}[i] = \gcd(a_0, \dots, a_{i-1}) and suf[i]=gcd⁡(ai,…,an−1)\mathit{suf}[i] = \gcd(a_i, \dots, a_{n-1}), with 0 for the empty ends. By associativity the answer for ii is gcd⁡(pre[i],suf[i+1])\gcd(\mathit{pre}[i], \mathit{suf}[i+1]):

def prefix_gcds(nums):
    """pre[i] = gcd(nums[0], ..., nums[i-1]); pre[0] = 0, the gcd of nothing."""
    pre = [0]
    for x in nums:
        pre.append(gcd(pre[-1], x))
    return pre


def suffix_gcds(nums):
    """suf[i] = gcd(nums[i], ..., nums[-1]); suf[len(nums)] = 0."""
    suf = [0] * (len(nums) + 1)
    for i in range(len(nums) - 1, -1, -1):
        suf[i] = gcd(nums[i], suf[i + 1])
    return suf


def gcd_without_each(nums):
    """out[i] = the gcd of all elements except nums[i], for every i, in
    linear time."""
    pre, suf = prefix_gcds(nums), suffix_gcds(nums)
    return [gcd(pre[i], suf[i + 1]) for i in range(len(nums))]
a = [24, 36, 60, 9, 48]
pre = [0, 24, 12, 12, 3, 3]
suf = [3, 3, 3, 3, 48, 0]
without each: [3, 3, 3, 12, 3]  best: 12 by removing a[3] = 9

The same answer serves “replace one element by any number”: replacing aia_i by the gcd of the others keeps that gcd, and no replacement can do better, since the result still has to divide all the others. The pattern works for any associative operation (sum, product, lcm, min); it does not need an inverse, which is why it is used for gcd instead of subtraction.

The gcd of differences

Shifting every element by the same xx changes the gcd unpredictably, but the differences do not change. For any integers a1,…,ana_1, \dots, a_n and xx:

gcd⁡(a1+x,a2+x,…,an+x)=gcd⁡(a1+x, a2−a1, …, an−a1).\gcd(a_1 + x, a_2 + x, \dots, a_n + x) = \gcd(a_1 + x,\ a_2 - a_1,\ \dots,\ a_n - a_1).

Proof. A number dividing every ai+xa_i + x divides every difference (ai+x)−(a1+x)=ai−a1(a_i + x) - (a_1 + x) = a_i - a_1. A number dividing a1+xa_1 + x and every ai−a1a_i - a_1 divides every sum (a1+x)+(ai−a1)=ai+x(a_1 + x) + (a_i - a_1) = a_i + x. The two lists have the same common divisors. ■\blacksquare

This is Euclid’s step gcd⁡(u,v)=gcd⁡(u,v−u)\gcd(u, v) = \gcd(u, v - u) from lesson 1, applied to a whole list. Let D=gcd⁡(a2−a1,…,an−a1)D = \gcd(a_2 - a_1, \dots, a_n - a_1). It does not depend on xx, so after one pass each shift costs a single gcd: gcd⁡(a1+x,D)\gcd(a_1 + x, D).

def shifted_gcd(nums, x):
    """gcd(nums[0] + x, ..., nums[-1] + x) for a non-empty list.

    Equals gcd(nums[0] + x, D) with D the gcd of the differences
    nums[i] - nums[0], which does not depend on x: so after O(n) work once,
    each new x costs one gcd.
    """
    d = 0
    for v in nums:
        d = gcd(d, v - nums[0])
    return gcd(nums[0] + x, d)
a = [5, 17, 29, 53]  differences from a[0]: [12, 24, 48]  D = 12
x = 0: gcd(a + x) = 1  check 1
x = 1: gcd(a + x) = 6  check 6
x = 2: gcd(a + x) = 1  check 1
x = 3: gcd(a + x) = 4  check 4
x = 4: gcd(a + x) = 3  check 3
x = 5: gcd(a + x) = 2  check 2
x = 6: gcd(a + x) = 1  check 1
x = 7: gcd(a + x) = 12  check 12

The answers are always divisors of D=12D = 12, and they repeat with period 12. A second use: all aia_i leave the same remainder modulo mm exactly when mm divides every difference, that is when m∣Dm \mid D. So the largest such mm is DD itself, and if D=0D = 0 the numbers are all equal and every mm works.

Subarray gcds come in few runs

Fix the right end rr and let the left end ll move from rr down to 0. The gcd of al,…,ara_l, \dots, a_r is ara_r at first, and each step left takes the gcd with one more number, so each value divides the one before it. The values can repeat, but they cannot take many different values:

Lemma. For positive integers, the gcds of the subarrays ending at rr take at most 1+log⁡2ar1 + \log_2 a_r distinct values.

Proof. List the distinct values in the order they appear as ll decreases: ar=d1,d2,…,dka_r = d_1, d_2, \dots, d_k. Each dj+1d_{j+1} divides djd_j and is different from it, so it is a proper divisor, and a proper divisor of a positive number is at most half of it. So dk≤ar/2k−1d_k \le a_r / 2^{k-1}, and dk≥1d_k \ge 1 gives 2k−1≤ar2^{k-1} \le a_r, that is k≤1+log⁡2ark \le 1 + \log_2 a_r. ■\blacksquare

The bound is reached: for 1,2,4,…,2201, 2, 4, \dots, 2^{20}, the subarrays ending at the last element have 21 different gcds. On random data the lists are much shorter. The lemma needs positive values, and so does the code below.

So for each rr, the starts 0,…,r0, \dots, r split into a few consecutive runs, each with one gcd. The runs for rr come from those for r−1r - 1: extend every subarray by ara_r, which replaces each run’s gcd gg by gcd⁡(g,ar)\gcd(g, a_r), add the run that starts at rr itself, and merge neighbours that became equal.

def subarray_gcd_runs(nums):
    """For each r, the gcds of the subarrays nums[l..r] that end at r,
    grouped into runs: a list of (g, lo, hi) meaning gcd(nums[l..r]) == g
    for every start l in [lo, hi]. Runs are in order of l; g strictly
    increases along the list and each g divides the next.

    Yields (r, runs) for r = 0, 1, ..., len(nums) - 1. For positive inputs
    each list has at most 1 + log2(nums[r]) runs.
    """
    runs = []
    for r, a in enumerate(nums):
        new = []
        for g, lo, hi in runs + [(a, r, r)]:
            g = gcd(g, a)
            if new and new[-1][0] == g:
                new[-1] = (g, new[-1][1], hi)      # same gcd: merge the runs
            else:
                new.append((g, lo, hi))
        runs = new
        yield r, runs

Equal gcds are always adjacent, because the gcds along a list only grow from left to right; that is why merging only the last run is enough. Step through it on a short array, counting the subarrays whose gcd is 3:

Runs of subarray gcds on 24,36,12,8,6,9,3024, 36, 12, 8, 6, 9, 30, with the subarrays of gcd 3 counted. Trace from python3 -m cpmath.subarray_gcd_trace 3 24 36 12 8 6 9 30 in cp-math.

r = 0: [(24, 0, 0)]
r = 1: [(12, 0, 0), (36, 1, 1)]
r = 2: [(12, 0, 2)]
r = 3: [(4, 0, 2), (8, 3, 3)]
r = 4: [(2, 0, 3), (6, 4, 4)]
r = 5: [(1, 0, 3), (3, 4, 4), (9, 5, 5)]
r = 6: [(1, 0, 3), (3, 4, 5), (30, 6, 6)]
subarrays with gcd 3: 3

Counting the subarrays with gcd kk is then a sum of run sizes:

def count_subarrays_with_gcd(nums, k):
    """How many subarrays (contiguous, non-empty) have gcd exactly k."""
    total = 0
    for _, runs in subarray_gcd_runs(nums):
        for g, lo, hi in runs:
            if g == k:
                total += hi - lo + 1
    return total

Cost. At step rr the loop does one gcd per run of r−1r - 1, plus one, so at most 2+log⁡2M2 + \log_2 M gcd calls for values up to MM, and O(nlog⁡M)O(n \log M) calls in all, against O(n2)O(n^2) for trying every subarray. Each call is at most O(log⁡M)O(\log M) division steps, so O(nlog⁡2M)O(n \log^2 M) steps is a safe bound; I have not proved a tighter one here. On random input the lists stay short:

100000 random values up to 10**9: at most 6 runs at any r (bound 1 + log2(10**9) = 30.9)

The same runs answer other questions. Adding every run’s size into a dictionary keyed by gg counts the subarrays for every gcd at once, which handles many queries. And the shortest subarray with gcd 1 that ends at rr starts at the last start of the first run, when that run’s gcd is 1:

def shortest_subarray_with_gcd_1(nums):
    """The length of the shortest subarray whose gcd is 1, or None."""
    best = None
    for r, runs in subarray_gcd_runs(nums):
        g, lo, hi = runs[0]          # the smallest gcd: the longest subarrays
        if g == 1:
            length = r - hi + 1      # the latest start that still gives 1
            if best is None or length < best:
                best = length
    return best
[6, 10, 15] -> 3
[2, 6, 3, 4] -> 2
[4, 6, 8] -> None
[6, 10, 15, 4] -> 2

Practice problems

Each needs an idea from this lesson. Links go to the problem pages; the one line is what to use, not the statement.

Try it yourself

  1. For a=[18,30,42,105,70]a = [18, 30, 42, 105, 70], compute the prefix and suffix gcds, and the gcd of the array without each element. Which removal gives the largest gcd?
  2. For a=[7,19,31,55]a = [7, 19, 31, 55], what is gcd⁡(ai+5)\gcd(a_i + 5)? For how many xx in 1,…,1001, \dots, 100 is gcd⁡(ai+x)>1\gcd(a_i + x) > 1?
  3. How many subarrays of [2,4,6,3,9,27][2, 4, 6, 3, 9, 27] have gcd 3?
  4. Give an array of length 5 for which the subarrays ending at the last element have 5 distinct gcds. Why can no array whose last element is 16 do better?
  5. What is the largest mm for which 100,37,64,163100, 37, 64, 163 all leave the same remainder modulo mm?
  6. What is the length of the shortest subarray of [6,10,15,12,20,18][6, 10, 15, 12, 20, 18] with gcd 1?

Answers

Each one is asserted in tests/test_lesson03.py, by brute force over the subarrays or the elements.

Show the answers
  1. Prefix: 0,18,6,6,3,10, 18, 6, 6, 3, 1. Suffix: 1,1,7,35,70,01, 1, 7, 35, 70, 0. Without each element: 1,1,1,2,31, 1, 1, 2, 3. Removing 70 gives the largest, 3.
  2. The differences are 12, 24, 48, so D=12D = 12 and gcd⁡(ai+5)=gcd⁡(12,12)=12\gcd(a_i + 5) = \gcd(12, 12) = 12. In general it is gcd⁡(7+x,12)\gcd(7 + x, 12), which is above 1 when 7+x7 + x is even or a multiple of 3: for 67 values of xx (50 odd ones, and the 17 even ones with x≡2(mod6)x \equiv 2 \pmod 6).
  3. 6: [3][3], [6,3][6, 3], [3,9][3, 9], [6,3,9][6, 3, 9], [3,9,27][3, 9, 27] and [6,3,9,27][6, 3, 9, 27]. The others either avoid the 3, and lie inside [2,4,6][2, 4, 6] (even gcd) or [9,27][9, 27] (gcd 9 or 27), or contain both the 4 and the 3, and have gcd 1.
  4. [1,2,4,8,16][1, 2, 4, 8, 16]: the gcds of the subarrays ending at 16 are 16, 8, 4, 2, 1. With last element 16 the lemma allows at most 1+log⁡216=51 + \log_2 16 = 5.
    1. The differences from 100 are −63,−36,63-63, -36, 63, whose gcd is 9; all four numbers leave remainder 1.
  5. 3: [6,10,15][6, 10, 15] has gcd 1, and no two adjacent elements are coprime.

Sources

  • Wikipedia, Greatest common divisor, section “Properties”: associativity, the gcd of several numbers, every common divisor divides the gcd, gcd⁡(a+mb,b)=gcd⁡(a,b)\gcd(a + mb, b) = \gcd(a, b), and the distributive laws between gcd and lcm.
  • Wikipedia, Euclidean algorithm, section “Number of steps”: Lamé’s theorem, used above for the cost of the fold (proved in lesson 1).
  • CodeChef, editorial of problem FUZZYLIN: the logarithmic number of distinct gcds of subarrays with a fixed end, and the update from one end to the next.
  • cp-algorithms, Sparse Table: one-lookup range queries for idempotent operations.
  • Python documentation, math.integer.gcd: any number of arguments, 0 for none.

ls number-theory/

Divisibility and the Euclidean algorithm

  • 01 GCD, Euclid, and Bézout draftWhy gcd(a, b) = gcd(b, a mod b), why it takes so few steps, extended Euclid and ax + by = c. Unlocks gcd-of-array, water jug and lcm problems.
  • 02 Integer division, floors and ceilings draft// and % on negative numbers in Python and C++, ceiling division without floats, math.isqrt. Unlocks problems whose answer is a count of multiples in a range.
  • 03 GCD over arrays and subarrays draftPrefix and suffix gcds, the gcd of differences, why a subarray's gcd changes only a logarithmic number of times. Unlocks subarray-gcd counting and remove-one-element problems.

Primes and factorization

  • 04 Primality and factoring by trial division draftWhy checking up to the square root suffices, and how far that goes in a time limit. Unlocks single-number primality and factorization queries.
  • 05 The sieve of Eratosthenes plannedCrossing out multiples from p squared, its n log log n cost, and a fast bytearray version in Python. Unlocks prime counting and prime listing up to about ten million.
  • 06 The linear sieve plannedEach composite crossed out exactly once, by its smallest prime factor, with multiplicative functions computed in the same pass.
  • 07 Smallest-prime-factor sieve plannedStore each number's smallest prime factor and factor any number below the limit in logarithmic time. Unlocks problems that factor many numbers.
  • 08 The segmented sieve plannedPrimes in a window [L, R] with R far beyond what fits in memory, using only the primes up to the square root of R.
  • 09 Number and sum of divisors plannedBoth from the prime factorization, listing all divisors, and the harmonic-series sieve that does it for every n at once. Unlocks divisor-counting and perfect-number problems.
  • 10 Prime powers in factorials plannedLegendre's formula for the exponent of p in n!. Unlocks trailing-zero and divisibility-of-factorial problems.

Modular arithmetic

  • 11 Arithmetic mod m plannedCongruences, the remainder of a negative number, which operations survive reduction, and why so many problems use 10^9 + 7.
  • 12 Fast exponentiation plannedSquare-and-multiply, Python's three-argument pow, and matrix powers for linear recurrences. Unlocks huge-exponent and n-th Fibonacci problems.
  • 13 Modular inverses plannedDivision mod m by Fermat's little theorem and by extended Euclid, when an inverse exists, and all inverses of 1..n in linear time.
  • 14 Euler's totient and Euler's theorem plannedCounting the numbers coprime to n, by formula and by sieve, and reducing exponents mod phi(m). Unlocks power towers mod m.
  • 15 Linear congruences plannedSolving a x ≡ b (mod m), how many solutions there are, and when there are none.
  • 16 The Chinese remainder theorem plannedCombining congruences into one, for coprime and non-coprime moduli. Unlocks problems with several periodic conditions.
  • 17 Orders, primitive roots and discrete logarithms plannedThe order of an element, finding a generator, and baby-step giant-step for a^x ≡ b (mod m).

Counting mod p

  • 18 Factorials, inverse factorials and nCr plannedPrecompute factorials and their inverses once, then answer each binomial coefficient in constant time. Unlocks most counting problems with a prime modulus.
  • 19 Binomial identities and Pascal's triangle plannedPascal's rule for composite moduli, stars and bars, and Catalan numbers.
  • 20 Lucas's theorem plannednCr mod a small prime p when n is far larger than p, digit by digit in base p.
  • 21 Inclusion–exclusion plannedCounting by alternating sums over subsets: numbers coprime to n in a range, derangements, surjections.
  • 22 The Möbius function and Möbius inversion plannedInclusion–exclusion over divisors. Unlocks counting coprime pairs and sums of gcds.
  • 23 Divisor blocks: iterating over n // i plannedn // i takes only about 2 sqrt(n) distinct values; summing over blocks of equal value turns many O(n) sums into O(sqrt n).
  • 24 Sums over gcds plannedSums of gcd(i, n) and of gcd(i, j) over a grid, by grouping on the gcd and using the totient and Möbius function.

Large numbers

  • 25 The Miller–Rabin primality test plannedA probabilistic test, and a fixed set of bases that makes it exact for every 64-bit number. Unlocks primality checks up to 10^18.
  • 26 Pollard's rho factorization plannedFactoring 64-bit numbers by finding a cycle in a pseudo-random sequence, with Brent's improvement.
  • 27 Floor sums by a Euclid-like recursion plannedThe sum of floor((a i + b) / m) over a range in logarithmic time, by the same reduction Euclid's algorithm uses. Unlocks lattice-point counting under a line.