HDU多校第三場6608 Fansblog(米勒羅賓+威爾遜定理)

題目鏈接 http://acm.hdu.edu.cn/showproblem.php?pid=6608

1e91e14ppqq!mod  p題目說給你一個1e9-1e14的素數p,讓你找到比p小的最大素數q,求q! \mod p的值

lognp1qq(p1)1(mod p),1p1,p2,p3q+1我們知道相鄰兩個素數之間的距離不會很大,一般小於logn,所以我們可以從p-1開始枚舉q,用米勒羅賓判定是否爲素數即可找到q,根據威爾遜定理 (p-1)!\equiv-1(mod\ p),用-1乘上p-1,p-2,p-3……q+1的逆元即可

#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
const int maxn = 2e5 + 500;
int t;
ll p,q,ans;
ll qmul(ll a, ll b, ll mod)
{
    ll res = 0;
    while(b)
    {
        if (b & 1)
            res = (res + a) % mod;
        a = (a << 1) % mod;
        b >>= 1;
    }
    return res;
}
ll qpow(ll x, ll n, ll mod)
{
    ll res = 1;
    while(n)
    {
        if (n & 1)
            res = qmul(res, x, mod);
        x = qmul(x, x, mod);
        n >>= 1;
    }
    return res;
}
bool Miller_Rabin(ll n){
    if(n==2)return true;
    if(n<2||!(n&1))return false;
    int cishu=2,ji=0;
    ll m=n-1;
    while(!(m&1)){
        ji++;
        m>>=1;
    }
    srand(100);
    while(cishu--){
        ll a=rand()%(n-1)+1;
        ll x=qpow(a,m,n),tmp=0;
        for(int i=0;i<ji;i++){
            tmp=qmul(x,x,n);
            if(tmp==1&&x!=1&&x!=n-1)return false;
            x=tmp;
        }
        if(tmp!=1)return false;
    }
    return true;
}
int main()
{
    scanf("%d", &t);
    while(t--)
    {
        scanf("%lld", &p);
        q = p - 1;
        while(!Miller_Rabin(q))
            --q;
        printf("%lld\n", q);
        ans = p - 1;
        for (ll i = p - 1; i > q; --i)
            ans = qmul(ans, qpow(i, p - 2, p), p);
        printf("%lld\n", ans);
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章