2019杭电多校第三场hdu6608 Fansblog(威尔逊定理)

质数求逆元算法
本文解析了一道涉及质数和逆元的算法题目,利用威尔逊定理简化计算过程,通过__int128类型处理大数运算,实现高效求解。

Fansblog

题目传送门

解题思路

Q! % P = (P-1)!/(P-1)...(Q-1) % P。
因为P是质数,根据威尔逊定理,(P-1)!%P=P-1。所以答案就是(P-1)((P-1)...*(Q-1)的逆元)%P。数据很大,用__int128。

代码如下

#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;

inline int read(){
    int res = 0, w = 0; char ch = 0;
    while(!isdigit(ch)){
        w |= ch == '-', ch = getchar();
    }
    while(isdigit(ch)){
        res = (res << 3) + (res << 1) + (ch ^ 48);
        ch = getchar();
    }
    return w ? -res : res;
}

template <typename A, typename B, typename C>
inline A fpow(A x, B p, C lyd){
    A ans = 1;
    for(; p; p >>= 1, x = 1LL * x * x % lyd)if(p & 1)ans = 1LL * x * ans % lyd;
    return ans % lyd;
}

__int128 get_inv(__int128 b, __int128 mod){
    return fpow(b, mod - 2, mod);
}

int main()
{
    int t;
    t = read();
    while(t --){
        ll p;
        scanf("%lld", &p);
        __int128 ans = 1;
        for(ll i = p - 1; i >= 2; i --){
            bool flg = true;
            for(ll j = 2; j <= sqrt(i); j ++){
                if(i % j == 0){
                    flg = false;
                    break;
                }
            }
            if(flg)
                break;
            ans = (ans * i) % p;
            //cout << ans << endl;
        }
        //cout << ans << endl;
        ll k = get_inv(ans, p) % p * (p - 1) % p;
        printf("%lld\n", k);
    }
    return 0;
}

转载于:https://www.cnblogs.com/whisperlzw/p/11272401.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值