U737316 题解报告

· · 个人记录

U737316 题解报告

显然,大部分筛法是不行的,因为 10^{12} 连 bitset 都存不下。

然而 \sqrt{n} 的判定素数方法也不行,因为会 TLE。

不过,根据唯一分解定理,n 可以看作 \prod_{i}p_{i}^{k_{i}},所以朴素的质数判定可以与线性筛结合,先用线性筛晒出 \sqrt{n} 范围内的素数,然后只用这些素数来试除 n 这样就能做到 \mathcal{O}(\pi(\sqrt{n})),其中 \pi(x) 表示 2 \sim x 之间的素数个数。

正确性证明

如果有我们没有试除过的数,那么这个数一定小于等于 n 且是合数,但是合数一定是若干质数的乘积,而 2 \sim x 之间的素数都我们都试除过了,故命题得证。

AC CODE

实现简单,读者自行实现。

后记

其实 Miller-Rabin 素性测试可以做到更快,不过出题人不会,所以给出 AI 生成代码,仅供参考。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;

// 快速乘,防止 ll * ll 溢出 (__int128 版本更简洁,大部分OJ支持)
ull mul(ull a, ull b, ull mod) {
    return (__int128)a * b % mod;
}

// 快速幂 a^b % mod
ull qpow(ull a, ull b, ull mod) {
    ull res = 1;
    while(b) {
        if(b & 1) res = mul(res, a, mod);
        a = mul(a, a, mod);
        b >>= 1;
    }
    return res;
}

// Miller-Rabin 单次测试,a是基底
bool check(ull a, ull n) {
    if(n <= 1) return false;
    if(n == a) return true;
    if(n % a == 0) return false;
    ull d = n - 1;
    int s = 0;
    while((d & 1) == 0) {
        d >>= 1;
        s++;
    }
    ull x = qpow(a, d, n);
    if(x == 1 || x == n - 1) return true;
    for(int i = 1; i <= s - 1; i++) {
        x = mul(x, x, n);
        if(x == n - 1) return true;
    }
    return false;
}

// 主素性判断函数
bool isprime(ull n) {
    if(n <= 1) return false;
    if(n <= 3) return true;
    if((n & 1) == 0) return false;
    // 固定基底,对 n < 2^64 完全正确
    vector<ull> bases = {2,3,5,7,11,13,17,19,23,29,31,37};
    for(ull a : bases) {
        if(!check(a, n)) return false;
    }
    return true;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int t;
    cin >> t;
    while(t--) {
        ull x;
        cin >> x;
        if(isprime(x)) cout << "Is prime!\n";
        else cout << "Is not prime!\n";
    }
    return 0;
}
/*AI代码,仅供参考、学习用途,不得抄袭*/

::::info[AI 使用说明] 本题解使用 豆包 AI 生成 Miller-Rabin 素性测试相关代码。作者保证本人贡献严格大于 AI。 ::::