CodeChef

GCDARR2. GCD Arrays (Hard)

2026-06-19 · 13 min read

Problem Statement

an array AA of length NN is called good if:

  • gcd⁡(A1,A2,…,AN)=1\gcd(A_1, A_2, \ldots, A_N) = 1
  • gcd⁡(AL,AL+1,…,AR)≠1\gcd(A_L, A_{L+1}, \ldots, A_R) \ne 1 for every (L,R)≠(1,N)(L, R) \ne (1, N)

every proper subsegment (any contiguous subarray except the full array itself) must have gcd >1> 1, but the full array’s gcd must be exactly 1.

given NN and MM, count the number of good arrays of length NN with 1≤Ai≤M1 \le A_i \le M. print the answer modulo 998244353998244353.

Examples

Example 1

Input
5
3 3
3 6
3 12
4 12
200000 100
Output
0
4
42
74
263141891

for N=3N=3, M=6M=6: the 4 valid arrays are [2,6,3][2,6,3], [3,6,2][3,6,2], [4,6,3][4,6,3], [3,6,4][3,6,4].

take [2,6,3][2, 6, 3]:

  • gcd⁡(2,6,3)=1\gcd(2, 6, 3) = 1 ✓ (full array)
  • gcd⁡(2,6)=2≠1\gcd(2, 6) = 2 \ne 1 ✓
  • gcd⁡(6,3)=3≠1\gcd(6, 3) = 3 \ne 1 ✓
  • gcd⁡(2)=2≠1\gcd(2) = 2 \ne 1 ✓, gcd⁡(6)=6≠1\gcd(6) = 6 \ne 1 ✓, gcd⁡(3)=3≠1\gcd(3) = 3 \ne 1 ✓

for N=3N=3, M=3M=3: no valid arrays exist — we’ll see why during the explanation.

Constraints

  • 1≤T≤501 \le T \le 50
  • 3≤N≤2⋅1053 \le N \le 2 \cdot 10^5
  • 3≤M≤2⋅1053 \le M \le 2 \cdot 10^5
  • sum of MM over all test cases ≤2⋅105\le 2 \cdot 10^5

Explanation

brute force

try all MNM^N arrays. for each, check both gcd conditions. that’s MN⋅Nlog⁡MM^N \cdot N \log M — completely hopeless for the given constraints.

we need structure.

what does a valid array look like?

let’s say N=3N = 3, so the array is [A1,A2,A3][A_1, A_2, A_3]. the proper subsegments are: [A1][A_1], [A2][A_2], [A3][A_3], [A1,A2][A_1, A_2], [A2,A3][A_2, A_3]. all of these must have gcd >1> 1.

  • [A1][A_1] having gcd >1> 1 just means A1>1A_1 > 1.
  • [A1,A2][A_1, A_2] having gcd >1> 1 means A1A_1 and A2A_2 share a prime.
  • [A2,A3][A_2, A_3] having gcd >1> 1 means A2A_2 and A3A_3 share a prime.
  • but gcd⁡(A1,A2,A3)=1\gcd(A_1, A_2, A_3) = 1 — they can’t all share the same prime.

for N=3N=3, M=3M=3: the interior is just A2∈{2,3}A_2 \in \{2, 3\} (can’t be 1). if A2=2A_2 = 2, then A1A_1 must share a factor with 2 so A1∈{2}A_1 \in \{2\}, and A3∈{2}A_3 \in \{2\}. but then gcd⁡(2,2,2)=2≠1\gcd(2, 2, 2) = 2 \ne 1. if A2=3A_2 = 3, same problem. so 0 valid arrays ✓.

the structure for general NN

take any valid array. consider the interior elements A2,A3,…,AN−1A_2, A_3, \ldots, A_{N-1}. every subarray made only from interior elements is a proper subarray, so its gcd >1> 1. in particular, gcd⁡(A2,A3,…,AN−1)>1\gcd(A_2, A_3, \ldots, A_{N-1}) > 1 — the entire interior shares a common factor.

let g=gcd⁡(A2,A3,…,AN−1)g = \gcd(A_2, A_3, \ldots, A_{N-1}). we know g≥2g \ge 2.

now for the endpoints:

  • the subarray [A1,A2,…,AN−1][A_1, A_2, \ldots, A_{N-1}] must have gcd >1> 1. that’s gcd⁡(A1,g)>1\gcd(A_1, g) > 1 — so A1A_1 shares at least one prime with gg.
  • the subarray [A2,A3,…,AN][A_2, A_3, \ldots, A_N] must have gcd >1> 1. that’s gcd⁡(g,AN)>1\gcd(g, A_N) > 1 — so ANA_N shares at least one prime with gg.
  • the full array must have gcd =1= 1, which means gcd⁡(A1,g,AN)=1\gcd(A_1, g, A_N) = 1 — no single prime divides all three.

so the answer is:

Answer=∑g=2M dp[g]⏟interior seqs with gcd exactly g ⋅ pairs(g)⏟valid endpoint pairs for this g\text{Answer} = \sum_{g=2}^{M}\ \underbrace{\text{dp}[g]}_{\text{interior seqs with gcd exactly } g}\ \cdot\ \underbrace{\text{pairs}(g)}_{\text{valid endpoint pairs for this } g}

where:

  • gg — the gcd of the interior elements A2,…,AN−1A_2, \ldots, A_{N-1}, iterated from 2 to MM
  • dp[g]\text{dp}[g] — number of length-(N−2)(N-2) sequences in [1,M][1,M] with gcd exactly gg
  • pairs(g)\text{pairs}(g) — number of valid (A1,AN)(A_1, A_N) pairs for this fixed interior gcd gg

computing dp[g] — the “exactly g” trick

dp[g]\text{dp}[g] = number of sequences of length N−2N-2 using elements from [1,M][1, M] whose gcd is exactly gg.

first, let’s count sequences whose gcd is at least gg (i.e., every element is a multiple of gg). there are ⌊M/g⌋\lfloor M/g \rfloor multiples of gg in [1,M][1, M], so:

(sequences with gcd divisible by g)=⌊Mg⌋N−2\text{(sequences with gcd divisible by } g) = \left\lfloor \frac{M}{g} \right\rfloor^{N-2}

but this overcounts — it includes sequences with gcd 2g2g, 3g3g, etc. we subtract those out:

dp[g]=⌊Mg⌋N−2−∑k≥2kg≤Mdp[kg]\text{dp}[g] = \left\lfloor \frac{M}{g} \right\rfloor^{N-2} - \sum_{\substack{k \ge 2 \\ kg \le M}} \text{dp}[kg]

where:

  • dp[g]\text{dp}[g] — sequences of length N−2N-2 in [1,M][1,M] with gcd exactly gg
  • ⌊M/g⌋\lfloor M/g \rfloor — count of multiples of gg in [1,M][1, M] (interior elements must all be multiples of gg)
  • N−2N-2 — the interior length (total array minus both endpoints)
  • kk — runs over 2,3,4,…2, 3, 4, \ldots so kgkg covers all proper multiples of gg up to MM
  • dp[kg]\text{dp}[kg] — already computed (since kg>gkg > g), sequences with gcd exactly kgkg

compute from g=Mg = M down to g=1g = 1 so every dp[kg]\text{dp}[kg] is already ready. total work: O(Mlog⁡M)O(M \log M) by the harmonic series (M1+M2+⋯≈Mln⁡M\frac{M}{1} + \frac{M}{2} + \cdots \approx M \ln M).

small example — dp with N=4N=4, M=6M=6 (interior has N−2=2N-2 = 2 elements)

dp[6]=⌊66⌋2=12=1\text{dp}[6] = \left\lfloor \frac{6}{6} \right\rfloor^2 = 1^2 = 1 dp[5]=⌊65⌋2=12=1\text{dp}[5] = \left\lfloor \frac{6}{5} \right\rfloor^2 = 1^2 = 1 dp[4]=⌊64⌋2=12=1\text{dp}[4] = \left\lfloor \frac{6}{4} \right\rfloor^2 = 1^2 = 1 dp[3]=⌊63⌋2−dp[6]=4−1=3\text{dp}[3] = \left\lfloor \frac{6}{3} \right\rfloor^2 - \text{dp}[6] = 4 - 1 = 3 dp[2]=⌊62⌋2−dp[4]−dp[6]=9−1−1=7\text{dp}[2] = \left\lfloor \frac{6}{2} \right\rfloor^2 - \text{dp}[4] - \text{dp}[6] = 9 - 1 - 1 = 7

for dp[2]=7\text{dp}[2] = 7: the 9 pairs of interior elements using only multiples of 2 are {2,4,6}2\{2,4,6\}^2, minus the pair with gcd 4 (just (4,4)(4,4)) and gcd 6 (just (6,6)(6,6)) = 7. ✓

computing pairs(g) — the Möbius trick

we need: how many pairs (A1,AN)∈[1,M]2(A_1, A_N) \in [1,M]^2 satisfy:

  • gcd⁡(A1,g)>1\gcd(A_1, g) > 1
  • gcd⁡(AN,g)>1\gcd(A_N, g) > 1
  • gcd⁡(A1,AN,g)=1\gcd(A_1, A_N, g) = 1

step 1 — how many integers in [1,M][1, M] share a prime with gg?

let’s count the complement first: integers coprime to gg.

if g=30=2×3×5g = 30 = 2 \times 3 \times 5 and M=20M = 20, we want integers from 1 to 20 not divisible by 2, 3, or 5. by inclusion-exclusion:

20−⌊20/2⌋−⌊20/3⌋−⌊20/5⌋+⌊20/6⌋+⌊20/10⌋+⌊20/15⌋−⌊20/30⌋20 - \lfloor 20/2 \rfloor - \lfloor 20/3 \rfloor - \lfloor 20/5 \rfloor + \lfloor 20/6 \rfloor + \lfloor 20/10 \rfloor + \lfloor 20/15 \rfloor - \lfloor 20/30 \rfloor =20−10−6−4+3+2+1−0=6= 20 - 10 - 6 - 4 + 3 + 2 + 1 - 0 = 6

the Möbius function packages these alternating ±\pm signs automatically:

μ(n)={1n=1(−1)kn is a product of k distinct primes0n has a squared prime factor\mu(n) = \begin{cases} 1 & n = 1 \\ (-1)^k & n \text{ is a product of } k \text{ distinct primes} \\ 0 & n \text{ has a squared prime factor} \end{cases}

for divisors of 3030:

ddfactorizationμ(d)\mu(d)
1—1
2prime−1
3prime−1
5prime−1
62·31
102·51
153·51
302·3·5−1

so the inclusion-exclusion above is exactly:

Sg=∑d∣gμ(d)⌊Md⌋S_g = \sum_{d \mid g} \mu(d) \left\lfloor \frac{M}{d} \right\rfloor

where:

  • SgS_g — count of integers in [1,M][1, M] coprime to gg
  • d∣gd \mid g — dd runs over every divisor of gg
  • μ(d)\mu(d) — Möbius value: +1+1 for even number of distinct prime factors, −1-1 for odd, 00 if any squared prime factor (those cancel and are skipped)
  • ⌊M/d⌋\lfloor M/d \rfloor — count of multiples of dd in [1,M][1, M]

and it counts the integers in [1,M][1, M] coprime to gg. why does this work? the Möbius function has a key identity: for any n>1n > 1,

∑d∣nμ(d)=0\sum_{d \mid n} \mu(d) = 0

this cancellation is exactly what makes the inclusion-exclusion over prime subsets exact — overcounted elements cancel out.

so: M−SgM - S_g integers share at least one prime with gg. both endpoints need this, giving (M−Sg)2(M - S_g)^2 candidate pairs.

step 2 — subtract pairs where gcd⁡(A1,AN,g)>1\gcd(A_1, A_N, g) > 1

a pair is invalid if some prime p∣gp \mid g divides both A1A_1 and ANA_N. count these using the same inclusion-exclusion idea, but now for pairs:

pairs(g)=(M−Sg)2+∑d∣gd>1μ(d)⌊Md⌋2\text{pairs}(g) = (M - S_g)^2 + \sum_{\substack{d \mid g \\ d > 1}} \mu(d) \left\lfloor \frac{M}{d} \right\rfloor^2

where:

  • pairs(g)\text{pairs}(g) — count of valid (A1,AN)(A_1, A_N) endpoint pairs for interior gcd gg
  • (M−Sg)2(M - S_g)^2 — both endpoints chosen from integers sharing a prime with gg
  • d∣g, d>1d \mid g,\ d > 1 — dd runs over non-trivial divisors of gg (skipping d=1d=1)
  • ⌊M/d⌋2\lfloor M/d \rfloor^2 — pairs where both A1A_1 and ANA_N are divisible by dd
  • μ(d)\mu(d) — inclusion-exclusion sign, same as before but now applied to pairs

⌊M/d⌋2\lfloor M/d \rfloor^2 vs ⌊M/d⌋\lfloor M/d \rfloor: if ⌊M/d⌋\lfloor M/d \rfloor counts elements divisible by dd, then ⌊M/d⌋2\lfloor M/d \rfloor^2 counts pairs where both are — that’s the set being inclusion-excluded.

traced example — g=6g = 6, M=6M = 6

ddμ(d)\mu(d)⌊6/d⌋\lfloor 6/d \rfloor⌊6/d⌋2\lfloor 6/d \rfloor^2
11636
2−139
3−124
6111

S6=1⋅6+(−1)⋅3+(−1)⋅2+1⋅1=6−3−2+1=2S_6 = 1 \cdot 6 + (-1) \cdot 3 + (-1) \cdot 2 + 1 \cdot 1 = 6 - 3 - 2 + 1 = 2 coprime to 6: {1,5}✓\text{coprime to 6: } \{1, 5\} \quad ✓

M−S6=4(share a prime with 6: {2,3,4,6})M - S_6 = 4 \quad \text{(share a prime with 6: } \{2, 3, 4, 6\})

base: 42=164^2 = 16 candidate pairs.

correction (d>1d > 1, both endpoints divisible by dd):

  • d=2d = 2: μ(2)⋅9=−9\mu(2) \cdot 9 = -9 (pairs where both divisible by 2: {2,4,6}2=9\{2,4,6\}^2 = 9)
  • d=3d = 3: μ(3)⋅4=−4\mu(3) \cdot 4 = -4 (pairs where both divisible by 3: {3,6}2=4\{3,6\}^2 = 4)
  • d=6d = 6: μ(6)⋅1=+1\mu(6) \cdot 1 = +1 (pairs where both divisible by 6: {6}2=1\{6\}^2 = 1, added back)

correction total: −9−4+1=−12-9 - 4 + 1 = -12.

pairs(6)=16−12=4✓\text{pairs}(6) = 16 - 12 = 4 \quad ✓

the 4 valid pairs are (A1,AN)∈{(2,3),(4,3),(3,2),(3,4)}(A_1, A_N) \in \{(2,3),(4,3),(3,2),(3,4)\} — A1A_1 is divisible by 2 only, ANA_N by 3 only (or vice versa), so no shared prime with g=6g=6 on both endpoints simultaneously.

putting it all together

for N=3N=3, M=6M=6: the only gg giving non-zero pairs is g=6g = 6 (pairs = 4, dp[6] = 1). all other gg have pairs = 0 because the prime structure of small gg forces both endpoints to share the same factor, violating the gcd = 1 condition.

answer = ∑g=26dp[g]⋅pairs(g)=1⋅4=4\sum_{g=2}^{6} \text{dp}[g] \cdot \text{pairs}(g) = 1 \cdot 4 = 4 ✓.

complexity

stepcost
μ\mu precomputation (linear sieve)O(M)O(M)
divisor listsO(Mlog⁡M)O(M \log M)
dp (harmonic series sum)O(Mlog⁡M)O(M \log M) per test case
pairs (divisor iteration)O(Mlog⁡M)O(M \log M) per test case
fast exponentiation in dpO(Mlog⁡N)O(M \log N) per test case
totalO(Mlog⁡M+Mlog⁡N)O(M \log M + M \log N) per test case

since sum of M≤2⋅105M \le 2 \cdot 10^5, total across all test cases is fine.

Code

solve() — dp + pairs
void solve() {
    long long N, M; cin >> N >> M;

    vector<long long> dp(M + 1, 0);
    for (long long g = M; g >= 1; g--) {
        dp[g] = pw(M / g, N - 2);
        for (long long k = 2 * g; k <= M; k += g)
            dp[g] = (dp[g] - dp[k] + MOD) % MOD;
    }

    long long ans = 0;
    for (long long g = 2; g <= M; g++) {
        if (!dp[g]) continue;

        // S_g = #{x in [1,M] : gcd(x,g) = 1}  via Möbius
        long long Sg = 0;
        for (int d : divs[g]) {
            if (!mu[d]) continue;
            long long fl = (M / d) % MOD;
            if (mu[d] == 1) Sg = (Sg + fl) % MOD;
            else            Sg = (Sg - fl + MOD) % MOD;
        }
        long long MSg = (M % MOD - Sg + MOD) % MOD;
        long long pairs = MSg * MSg % MOD;

        // inclusion-exclusion correction: sum_{d|g, d>1} mu(d)*floor(M/d)^2
        for (int d : divs[g]) {
            if (d == 1 || !mu[d]) continue;
            long long fl = (M / d) % MOD;
            long long term = fl * fl % MOD;
            if (mu[d] == 1) pairs = (pairs + term) % MOD;
            else            pairs = (pairs - term + MOD) % MOD;
        }
        ans = (ans + dp[g] * pairs) % MOD;
    }

    cout << ans << "\n";
}

Full code

Full solution — GCDARR2
#include <bits/stdc++.h>
using namespace std;

const long long MOD = 998244353;
const int MAXM = 200001;

int mu[MAXM];
vector<int> divs[MAXM];

long long pw(long long a, long long b) {
    long long r = 1;
    a %= MOD;
    for (; b > 0; b >>= 1, a = a * a % MOD)
        if (b & 1) r = r * a % MOD;
    return r;
}

void precompute() {
    vector<int> primes;
    vector<bool> comp(MAXM, false);
    mu[1] = 1;
    for (int i = 2; i < MAXM; i++) {
        if (!comp[i]) { primes.push_back(i); mu[i] = -1; }
        for (int j = 0; j < (int)primes.size() && (long long)i * primes[j] < MAXM; j++) {
            comp[i * primes[j]] = true;
            if (i % primes[j] == 0) { mu[i * primes[j]] = 0; break; }
            mu[i * primes[j]] = -mu[i];
        }
    }
    for (int i = 1; i < MAXM; i++)
        for (int j = i; j < MAXM; j += i)
            divs[j].push_back(i);
}

void solve() {
    long long N, M; cin >> N >> M;

    vector<long long> dp(M + 1, 0);
    for (long long g = M; g >= 1; g--) {
        dp[g] = pw(M / g, N - 2);
        for (long long k = 2 * g; k <= M; k += g)
            dp[g] = (dp[g] - dp[k] + MOD) % MOD;
    }

    long long ans = 0;
    for (long long g = 2; g <= M; g++) {
        if (!dp[g]) continue;

        long long Sg = 0;
        for (int d : divs[g]) {
            if (!mu[d]) continue;
            long long fl = (M / d) % MOD;
            if (mu[d] == 1) Sg = (Sg + fl) % MOD;
            else            Sg = (Sg - fl + MOD) % MOD;
        }
        long long MSg = (M % MOD - Sg + MOD) % MOD;
        long long pairs = MSg * MSg % MOD;
        for (int d : divs[g]) {
            if (d == 1 || !mu[d]) continue;
            long long fl = (M / d) % MOD;
            long long term = fl * fl % MOD;
            if (mu[d] == 1) pairs = (pairs + term) % MOD;
            else            pairs = (pairs - term + MOD) % MOD;
        }

        ans = (ans + dp[g] * pairs) % MOD;
    }

    cout << ans << "\n";
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    precompute();
    int T; cin >> T;
    while (T--) solve();
}

Complexity

  • Preprocessing: O(Mlog⁡M)O(M \log M) — linear sieve + divisor lists
  • Per test case: O(Mlog⁡M+Mlog⁡N)O(M \log M + M \log N) — dp sweep + pairs computation
  • Total: O(Mlog⁡M+Mlog⁡N)O(M \log M + M \log N) summed over test cases (sum of M≤2⋅105M \le 2 \cdot 10^5)

Resources