跳到正文

个人记录

数论好题

Magnus2012约 17 分钟
原文

这是 2026年1月1日 存档的第 2 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

收录
2025年12月28日
更新
2026年1月7日
篇幅
约 17 分钟

版本

  1. v3当前
  2. v2
  3. v1

深思熟虑了一下,还是决定深刻探讨一下这道题。

关键观察:XOR 永远在和 0 异或

对任意一对 (a,b)(a,b):

  • 若 a<ba<b ,则 b!b! 的乘积里包含因子 aa,所以 b!moda=0b! mod a =0,那么此时项变成 (a!(a! mod mod b)=a!b)=a! modmod bb。
  • 若 a>ba>b ,同理 a!a! modmod b=0b=0,此时的项变成 b!b! modmod aa。
  • 若a=ba=b,两边都为 00,贡献也是 00。

所以原式等价于:

∑i,j{ai! mod bj,ai<bjbj! mod ai,bj<ai0,ai=bj\sum_{i, j} \begin{cases} a_{i}! \bmod b_{j}, & a_{i} < b_{j} \\ b_{j}! \bmod a_{i}, & b_{j} < a_{i} \\ 0, & a_{i} = b_{j} \end{cases}

也就是拆成两部分:

  • S(A,B)=∑a∈A∑b∈B,a<b(a! mod b)S(A,B)=\sum_{a\in A}\sum_{b\in B,a<b}(a!\bmod b)
  • S(B,A)S(B,A) 同理

综上答案为: (S(A,B)+S(B,A))(S(A,B)+S(B,A)) modmod 998244353998244353

做法概述

对每个模数 mm(来自另一数组的元素)我们需要算:

∑x<mcnt⁡(x)⋅(x! mod m)\sum_{x<m} \operatorname{cnt}(x) \cdot (x! \bmod m)

实现上:

  • 先把数组排序压缩成 (value, count)
  • 对每个 mm 取出所有 x<mx<m 的前缀。
  • 计算这些 x!x! modmod mm 并加权求和。

优化点:

  • 合数 mm:一旦达到最小 k0k_0 使得 m∣k0!m∣k_0!,之后阶乘模 mm 全是 0,所以只用算到 k0−1k_0 -1。
  • 素数 p:用 Wilson:(p−1)!≡−1(mod(p−1)!≡−1(mod p)p),对“大 xx”用尾部乘积 + 批量求逆,避免每个查询都 pow。

总时间复杂度应是:

O(∑i=1t(mi+Vi2+Vi⋅mi))O\left(\sum_{i=1}^{t}\left(m_{i}+V_{i}^{2}+V_{i}\cdot m_{i}\right)\right)

其中

  • tt 数据组数
  • nn:数组长度
  • m=max(max(A),max(B))m=max(max(A),max(B)),即数组元素最大值
  • V=∣vals∣V=∣vals∣,表示去重后元素个数,显然 V≤2nV≤2n且 V≤m+1V≤m+1

具体实现请看代码:

C++
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
using uint = unsigned int;
using ld = long double;
using cd = complex<double>;
#define i128  __int128
#define fir first
#define sec second
#define pii pair<int, int>
#define pll pair<ll, ll>
#define ls(x) (x << 1)
#define rs(x) (x << 1 | 1)
#define lowbit(x) (x & -x)
#define AC return 0
const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};
const int dx8[] = {-1, 1, 0, 0, -1, -1, 1, 1};
const int dy8[] = {0, 0, -1, 1, -1, 1, -1, 1};
const int MOD1 = 1e9 + 7;
const int MOD = 998244353;
const double PI = acos(-1);
namespace FastIO{
	const int Size=1<<21;
	char ibuf[Size],obuf[Size],*p1=ibuf,*p2=ibuf,*p3=obuf;
	#define getchar() (p1==p2&&(p2=(p1=ibuf)+fread(ibuf,1,Size,stdin),p1==p2)?EOF:*p1++)
	#define putchar(x) (p3-obuf<Size?(*p3++=(x)):(fwrite(obuf,1,p3-obuf,stdout),p3=obuf,*p3++=(x)))
	inline void flush(){if(p3>obuf) fwrite(obuf,1,p3-obuf,stdout),p3=obuf;}
	template<class T>
	T read(T&x){
		x=0;bool f=false;char ch=getchar();
		while(!isdigit(ch)) f|=!(ch^'-'),ch=getchar();
		while(isdigit(ch)) x=(x<<1)+(x<<3)+(ch&0xF),ch=getchar();
		x=(f?-x:x);return x;
	}template<class T>
	int reads(T*s){
		char ch=getchar();int len=0;
		while(ch==' '||ch=='\n'||ch=='\r') ch=getchar();
		while(ch!=' '&&ch!='\n'&&ch!=EOF&&ch!='\r') s[len++]=ch,ch=getchar();
		s[len]='\0';return len;
	}template<class T>
	T readd(T&x){
		x=0;bool f=false;char ch=getchar();
		while(!isdigit(ch)) f|=!(ch^'-'),ch=getchar();
		while(isdigit(ch)) x=x*10+(ch&0xF),ch=getchar();
		if(ch=='.'){ch=getchar();T d=1;while(isdigit(ch)) d*=0.1,x+=d*(ch&0xF),ch=getchar();}
		x=(f?-x:x);return x;
	}template<class T>
	void write(T x,char ch=' '){
		if(x<0) putchar('-'),x=-x;
		char tmp[41];int cnt=0;
		while(x>9) tmp[cnt++]=x%10+'0',x/=10;tmp[cnt++]=x+'0';
		while(cnt) putchar(tmp[--cnt]);putchar(ch);
	}template<class T>
	void writes(T x,int l=0,int r=-1){
		if(~r){for(int i=l;i<=r;i++) putchar(x[i]);}
		else{for(int i=l;x[i];i++) putchar(x[i]);}
	}template<class T>
	void writed(T x,int p=6,char ch=' '){
		if(x<0) putchar('-'),x=-x;
		T d=0.5;for(int i=0;i<p;i++) d*=0.1;x+=d;
		i128 g=(i128)(x);p?write(g,'.'):write(g,ch);
		if(p){T f=x-g;for(int i=0,d;i<p;i++) f*=10,d=(int)(f),putchar(d+'0'),f-=d;putchar(ch);}
	}
}
using namespace FastIO;

static inline long long mod_pow(long long a, long long e, long long mod) {
    long long r = 1 % mod;
    while (e > 0) {
        if (e & 1) r = (long long)((__int128)r * a % mod);
        a = (long long)((__int128)a * a % mod);
        e >>= 1;
    }
    return r;
}

void solve(){
	int n;
    read(n);
    vector<int> A(n), B(n);
    int maxV = 0;
    for (int i = 0; i < n; i++) { read(A[i]); maxV = max(maxV, A[i]); }
    for (int i = 0; i < n; i++) { read(B[i]); maxV = max(maxV, B[i]); }

    vector<int> cntA(maxV + 1, 0), cntB(maxV + 1, 0);
    vector<char> vis(maxV + 1, 0);
    vector<int> vals;
    vals.reserve(2 * n);

    for (int v : A) {
        cntA[v]++;
        if (!vis[v]) { vis[v] = 1; vals.push_back(v); }
    }
    for (int v : B) {
        cntB[v]++;
        if (!vis[v]) { vis[v] = 1; vals.push_back(v); }
    }
    sort(vals.begin(), vals.end());

    // Linear sieve for SPF
    vector<int> spf(maxV + 1, 0), primes;
    primes.reserve(maxV / 10);
    for (int i = 2; i <= maxV; i++) {
        if (!spf[i]) { spf[i] = i; primes.push_back(i); }
        for (int p : primes) {
            long long v = 1LL * i * p;
            if (v > maxV || p > spf[i]) break;
            spf[(int)v] = p;
        }
    }
    auto isPrime = [&](int x) -> bool {
        return x >= 2 && spf[x] == x;
    };

    long long ans = 0;

    vector<int> xs, coefs;
    vector<int> tail, pre;

    for (int yi = 0; yi < (int)vals.size(); yi++) {
        int y = vals[yi];
        int cyA = cntA[y], cyB = cntB[y];
        if (cyA == 0 && cyB == 0) continue;

        xs.clear(); coefs.clear();
        xs.reserve(yi);
        coefs.reserve(yi);

        for (int xi = 0; xi < yi; xi++) {
            int x = vals[xi];
            long long coef = 1LL * cntA[x] * cyB + 1LL * cyA * cntB[x];
            if (!coef) continue;
            xs.push_back(x);
            coefs.push_back((int)(coef % MOD));
        }
        int Q = (int)xs.size();
        if (Q == 0) continue;

        if (isPrime(y)) {
            int p = y;

            // choose best split k in [0..Q]
            int best_k = 0;
            long long best_cost = 1LL * (p - 1 - xs[0]); // k=0: all high
            for (int k = 1; k <= Q; k++) {
                long long cost = xs[k - 1];            // prefix cost
                if (k < Q) cost += 1LL * (p - 1 - xs[k]); // suffix cost
                if (cost < best_cost) {
                    best_cost = cost;
                    best_k = k;
                }
            }
            int k = best_k;

            // low part: [0, k) by prefix factorial
            if (k > 0) {
                int max_low = xs[k - 1];
                long long f = 1;
                int idx = 0;
                for (int t = 1; t <= max_low; t++) {
                    f = (f * t) % p;
                    if (idx < k && xs[idx] == t) {
                        ans += 1LL * coefs[idx] * f;
                        ans %= MOD;
                        idx++;
                    }
                }
            }

            // high part: [k, Q) using Wilson + tail product + batch inverse
            if (k < Q) {
                int H = Q - k;
                tail.assign(H, 0);
                pre.assign(H, 0);

                int qidx = H - 1;

                // x == p-1 => tail is empty product => 1
                while (qidx >= 0 && xs[k + qidx] == p - 1) {
                    tail[qidx] = 1;
                    qidx--;
                }

                long long prod = 1;
                int min_high = xs[k]; // first x in high group (sorted)

                // compute tail(x) = product_{t=x+1}^{p-1} t
                for (int kk = p - 1; kk >= min_high + 1 && qidx >= 0; --kk) {
                    prod = (prod * kk) % p;
                    while (qidx >= 0 && xs[k + qidx] + 1 == kk) {
                        tail[qidx] = (int)prod;
                        qidx--;
                    }
                }

                // batch inverse tails
                long long cur = 1;
                for (int i = 0; i < H; i++) {
                    cur = (cur * tail[i]) % p;
                    pre[i] = (int)cur;
                }

                long long inv_total = mod_pow(pre[H - 1], p - 2, p);
                for (int i = H - 1; i >= 0; i--) {
                    long long before = (i ? pre[i - 1] : 1);
                    long long inv_tail = (inv_total * before) % p;
                    inv_total = (inv_total * tail[i]) % p;

                    // x! = - inv(tail) mod p
                    long long fact = 1LL * (p - 1) * inv_tail % p;

                    ans += 1LL * coefs[k + i] * fact;
                    ans %= MOD;
                }
            }
        } else {
            // composite: prefix factorial, stop if becomes 0
            int max_x = xs.back();
            long long f = 1;
            int idx = 0;
            for (int t = 1; t <= max_x; t++) {
                f = (f * t) % y;
                if (idx < Q && xs[idx] == t) {
                    ans += 1LL * coefs[idx] * f;
                    ans %= MOD;
                    idx++;
                }
                if (f == 0) break;
            }
        }
    }

    ans %= MOD;
    if (ans < 0) ans += MOD;
    cout << ans << "\n";
}
int main()
{
    int t;
	read(t);
	while(t--) solve();
	flush();
    AC;
}