C++ 大整数解密算法修正:手动幂运算代替 pow 函数
对不起,我给出的解决方案有误。在 C++ 中,'pow' 函数的返回类型为'double',无法直接用于大整数运算。为了解决这个问题,我们可以使用循环来手动进行幂运算。
以下是修正后的 C++ 代码示例:
#include <iostream>
#include <vector>
using namespace std;
long long mod_inverse(long long a, long long m) {
long long m0 = m, t, q;
long long x0 = 0, x1 = 1;
if (m == 1)
return 0;
while (a > 1) {
q = a / m;
t = m;
m = a % m;
a = t;
t = x0;
x0 = x1 - q * x0;
x1 = t;
}
if (x1 < 0)
x1 += m0;
return x1;
}
vector<long long> decrypt(int e, int p, int q, int n, vector<long long>& ciphertext) {
long long m = p * q;
long long phi = (p - 1) * (q - 1);
long long d = mod_inverse(e, phi);
vector<long long> plaintext(n);
for (int i = 0; i < n; i++) {
long long c = ciphertext[i];
long long a = 1;
for (int j = 0; j < d; j++) {
a = (a * c) % m;
}
plaintext[i] = a;
}
return plaintext;
}
int main() {
int T;
cin >> T;
while (T--) {
int e, p, q, n;
cin >> e >> p >> q >> n;
vector<long long> ciphertext(n);
for (int i = 0; i < n; i++) {
cin >> ciphertext[i];
}
vector<long long> plaintext = decrypt(e, p, q, n, ciphertext);
for (int i = 0; i < n; i++) {
cout << plaintext[i] << " ";
}
cout << endl;
}
return 0;
}
在修正后的代码中,我们使用循环进行幂运算,而不是使用'pow' 函数。对于每个密文,我们使用循环将其乘以自身 d 次,并取模 m,从而得到解密后的明文。
非常抱歉之前给出的错误解决方案带来的困扰。希望这次的修正能够解决你的问题!如果还有其他问题,请随时提问。
原文地址: http://www.cveoy.top/t/topic/XXX 著作权归作者所有。请勿转载和采集!