题解:P5451 [THUPC 2018] 密码学第三次小作业

· · 题解

题意

给定 c_1,c_2,e_1,e_2,N,满足

c_1\equiv m^{e_1}\pmod N\\ c_2\equiv m^{e_2}\pmod N\\

且 (e_1,e_2)=1,N 有且只有两个质因子,求 m。

思路

也就是说我们要用 m^{e_1} 和 m^{e_2} 凑出 m^1。

看到 (e_1,e_2)=1 这个性质,所以我们可以求出一个方程 e_1k_1+e_2k_2=1 的整数解 k_1,k_2,这样就可以用 s_1^{k_1}\times s_2^{k_2} 凑出 m^1。这可以用扩展欧几里得算法求出。

然而我们发现 k_1 与 k_2 可能有一个为负数,假设 k_1 为负数。那么我们需要求出 s^{-1 \times |k_1|} 即 (s^{|k_1|})^{-1},也就是 s^{|k_1|} 在模 N 意义下的逆元。

但是 N 并不为质数,若使用欧拉定理的话需要找到其质因数会爆炸,所以我们再次使用扩展欧几里得算法:

发现 (s^{|k_1|})^{-1}\times s^{|k_1|}\equiv 1\pmod N,于是有 s^{|k_1|}\times(s^{|k_1|})^{-1}+N\times b=1 ,可以求出一组整数解 (s^{|k_1|})^{-1}, b。注意此时求出的逆元并不一定是正整数,注意取模。

你也许需要使用 __int128 或者龟速乘。

代码

#include <bits/stdc++.h>
using namespace std;
typedef __int128 ll;
ll s1, s2, k1, k2, c, T, p[100002], len, m;
bitset<10000002> f;
ll qmi(ll x, ll y, ll z) {
    x %= z;
    ll res = 1 % z;
    while (y) res = res * (y & 1 ? x : 1) % z, x = x * x % z, y >>= 1;
    return res;
}
ll exgcd(ll a, ll b, ll &x, ll &y) {
    if (b == 0) return x = 1, y = 0, a;
    ll d = exgcd(b, a % b, x, y), z = x;
    x = y, y = z - y * (a / b);
    return d;
}
int main() {
    long long tt;
    cin >> tt, T = tt;
    while (T -- ) {
        cin >> tt, s1 = tt;
        cin >> tt, s2 = tt;
        cin >> tt, k1 = tt;
        cin >> tt, k2 = tt;
        cin >> tt, c = tt;
        ll c1, c2, t;
        exgcd(k1, k2, c1, c2);
        if (c1 < 0) {
            c1 = -c1;
            s1 = qmi(s1, c1, c);
            exgcd(s1, c, s1, t);
            s1 = (s1 % c + c) % c;
        }
        else s1 = qmi(s1, c1, c);
        if (c2 < 0) {
            c2 = -c2;
            s2 = qmi(s2, c2, c);
            exgcd(s2, c, s2, t);
            s2 = (s2 % c + c) % c;
        }
        else s2 = qmi(s2, c2, c);
        tt = s1 * s2 % c;
        cout << tt << "\n";
    }
}