Gym - 102861N - Number Multiplication (分解质因数、Miller_Rabin、Pollard_Rho)

15 篇文章 0 订阅
6 篇文章 0 订阅

2020-2021 ACM-ICPC Brazil Subregional Programming Contest
Codeforces - Gym102861 N. Number Multiplication

#include <bits/stdc++.h>
#define ll long long
using namespace std;
int M, N, K;
int m, n, d;
ll c;
set<ll> ans;
ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
ll mul(ll a, ll b, ll p) {
    ll res = 0;
    a %= p;
    while (b) {
        if (b & 1) {
            res = (res + a) % p;
        }
        a = (a + a) % p;
        b >>= 1;
    }
    return res;
}
ll pow(ll a, ll b, ll p) {
    ll res = 1;
    a %= p;
    while (b) {
        if (b & 1) {
            res = mul(res, a, p);
        }
        a = mul(a, a, p);
        b >>= 1;
    }
    return res;
}
bool Miller_Rabin(ll n) {
    if (n <= 2) return n == 2;
    if ((n & 1) == 0) return false;
    ll m = n - 1;
    int k = 0;
    while ((m & 1) == 0) {
        m >>= 1;
        ++k;
    }
    ll A[] = {2, 325, 9375, 28178, 450775, 9780504, 1795265022};
    for (auto a : A) {
        ll x = pow(a, m, n);
        if(x <= 1 || x >= n - 1) continue;
        for (int i = 0; i < k; ++i) {
            x = mul(x, x, n);
            if (x == n - 1 && i != k - 1) {
                x = 1;
                break;
            }
            if(x == 1) return false;
        }
        if (x != 1) return false;
    }
    return true;
}
ll Pollard_Rho(ll n) {
    ll s = 0, t = 0;
    ll c = 1ll * rand() % (n - 1) + 1;
    int step = 0, goal = 1;
    ll val = 1;
    for (goal = 1;; goal <<= 1, s = t, val = 1) {
        for (step = 1; step <= goal; ++step) {
            t = (mul(t, t, n) + c) % n;
            val = mul(val, abs(t - s), n);
            if ((step % 127) == 0) {
                ll d = gcd(val, n);
                if (d > 1) return d;
            }
        }
        ll d = gcd(val, n);
        if (d > 1) return d;
    }
}
void find(ll n) {
    if (Miller_Rabin(n)) {
        ans.insert(n);
        return;
    }
    ll p = n;
    while (p >= n) {
        p = Pollard_Rho(p);
    }
    find(n / p);
    find(p);
}
int main() {
    scanf("%d%d%d", &M, &N, &K);
    for (int i = 1; i <= N; ++i) {
        scanf("%lld", &c);
        find(c);
    }
    for (int i = 1; i <= K; ++i) {
        scanf("%d%d%d", &m, &n, &d);
    }
    for (auto iter : ans) {
        printf("%lld ", iter);
    }
    printf("\n");
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值