man number-theory/gcd-over-arrays
lesson 3 of 27 · Divisibility and the Euclidean algorithm
GCD over arrays and subarrays
An array of numbers has about 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 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 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:
Proof. Lesson 1 showed that the common divisors of two numbers are exactly the divisors of their gcd. Let ; by induction on , the common divisors of are exactly the divisors of . So a number divides all of if and only if it divides and , if and only if it divides . The two sides have the same divisors, so they are equal.
So the gcd is associative and commutative, the order does not matter, and
the empty list has gcd 0, the value that changes nothing
(). 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 of the smaller number. (math.gcd is
implemented differently for very large numbers, but the count is the right
model.) Charging that to all calls gives
for numbers up to . 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 , takes at most division steps in total.
Proof. Euclid’s algorithm takes the same steps on as on for : every quotient is the same. Lamé’s theorem from lesson 1, applied to the reduced pair, says that steps on with need , so . For the call with result : if it takes at most steps; if , one step; if , one step to swap and then at most . In every case the call takes at most . Adding over , the logarithms telescope to .
So a fold over numbers up to costs 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 , for every . Recomputing it times costs . Instead, keep and , with 0 for the empty ends. By associativity the answer for is :
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 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 changes the gcd unpredictably, but the differences do not change. For any integers and :
Proof. A number dividing every divides every difference . A number dividing and every divides every sum . The two lists have the same common divisors.
This is Euclid’s step from lesson 1, applied to a whole list. Let . It does not depend on , so after one pass each shift costs a single gcd: .
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 , and they repeat with period 12. A second use: all leave the same remainder modulo exactly when divides every difference, that is when . So the largest such is itself, and if the numbers are all equal and every works.
Subarray gcds come in few runs
Fix the right end and let the left end move from down to 0. The gcd of is 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 take at most distinct values.
Proof. List the distinct values in the order they appear as decreases: . Each divides 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 , and gives , that is .
The bound is reached: for , 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 , the starts split into a few consecutive runs, each with one gcd. The runs for come from those for : extend every subarray by , which replaces each run’s gcd by , add the run that starts at 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:
The array 24, 36, 12, 8, 6, 9, 30, processed left to right. At each end r a table lists the runs of starts with their gcd and size. The runs never exceed three; the subarrays with gcd 3 are a[4..5], a[4..6] and a[5..6]. (This figure steps through a recorded run; it needs JavaScript.)
Runs of subarray gcds on , 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 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 the loop does one gcd per run of , plus one, so at most gcd calls for values up to , and calls in all, against for trying every subarray. Each call is at most division steps, so 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 counts the subarrays for every gcd at once, which handles many queries. And the shortest subarray with gcd 1 that ends at 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.
- LeetCode 2447. Number of Subarrays With GCD Equal to K:
count_subarrays_with_gcd, in gcd calls instead of . - Codeforces 475D. CGCDSSQ: many queries for the number of subarrays with a given gcd; add up the runs in a dictionary once.
- LeetCode 2654. Minimum Number of Operations to Make All Array Elements Equal to 1: the shortest subarray with gcd 1 decides the answer (unless the array already contains a 1).
- LeetCode 3334. Find the Maximum Factor Score of Array: prefix and suffix gcds and lcms, for every element left out, and the whole array for removing nothing.
- Codeforces 1349A. Orac and LCM: suffix gcds, using that (checked by brute force in the tests).
- Codeforces 1593D1. All are Same: the gcd of the differences, with the all-equal case separate.
- Codeforces 1458A. Row GCD:
shifted_gcd, one gcd per query after a pass over the differences. - Codeforces 1548B. Integers Have Friends: equal remainders mod some means a gcd of differences above 1; find the longest such run of adjacent differences with the runs above or a sparse table.
Try it yourself
- For , compute the prefix and suffix gcds, and the gcd of the array without each element. Which removal gives the largest gcd?
- For , what is ? For how many in is ?
- How many subarrays of have gcd 3?
- 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?
- What is the largest for which all leave the same remainder modulo ?
- What is the length of the shortest subarray of 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
- Prefix: . Suffix: . Without each element: . Removing 70 gives the largest, 3.
- The differences are 12, 24, 48, so and . In general it is , which is above 1 when is even or a multiple of 3: for 67 values of (50 odd ones, and the 17 even ones with ).
- 6: , , , , and . The others either avoid the 3, and lie inside (even gcd) or (gcd 9 or 27), or contain both the 4 and the 3, and have gcd 1.
- : the gcds of the subarrays ending at 16 are 16, 8, 4, 2, 1. With last element 16 the lemma allows at most .
- The differences from 100 are , whose gcd is 9; all four numbers leave remainder 1.
- 3: 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, , 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.