使用c++计算大数的乘法逆
Calculate the multiplicative inverse of large numbers using C++
我正试图计算一个大数对另一个大数的乘法逆。例如,我想计算6003722857 mod 77695236973的乘法逆。为此,我编写了一些c++代码。对于像a = 1891和n = 3797这样的小数字,它工作得很好,但一旦我尝试非常大的数字,程序就不能工作了。没有错误。它看起来像是在计算什么,但是程序就这样结束了。
任何建议将不胜感激。谢谢!
#include <iostream>
using namespace std;
int main ()
{
long long int a = 0, n = 0;
cout << "Enter a: ";
cin >> a;
cout << "Enter n: ";
cin >> n;
for (long long int c = 1; c < n; c++) {
long long int num = a*c - 1;
if (num%n == 0) {
cout << "The multiplicative inverse is " << c << "." << endl;
break;
}
}
return 0;
}
这里是超级快速的c++:
#include <iostream>
#include <utility>
#include <exception>
#include <tuple>
using namespace std;
using temp_t = std::tuple<long long, long long>;
long long calcInverse(long long a, long long n)
{
long long t = 0, newt = 1;
long long r = n, newr = a;
while (newr != 0) {
auto quotient = r /newr;
tie(t, newt) = make_tuple(newt, t- quotient * newt);
tie(r, newr) = make_tuple(newr, r - quotient * newr);
}
if (r > 1)
throw runtime_error("a is not invertible");
if (t < 0)
t += n;
return t;
}
int main ()
{
long long int a = 6003722857 , n = 77695236973;
/*
cout << "Enter a: ";
cin >> a;
cout << "Enter n: ";
cin >> n;
*/
try {
auto inverse = calcInverse(a, n);
cout << "The multiplicative inverse is " << inverse << endl;
}
catch(exception& e) {
cout << e.what() << endl;
}
return 0;
}
您可以使用扩展欧几里得算法来完成此操作:
Wiki -扩展欧几里得算法-模整数
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 递归函数计算序列中的平方和(并输出过程)
- (C++)分析树以计算返回错误值的简单算术表达式
- 我的字符计数代码计算错误.为什么
- 在计算中使用二的幂有多有利可图
- 如何计算文件中的"columns"数?
- 计算排序向量的向量中唯一值的计数
- 如何使用 std::累积在 C++ 中计算总和立方体
- 使用Qt C++计算类似Git的SHA1哈希
- OpenCV C++.快速计算混淆矩阵
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- C++如何计算用户输入的数字中的偶数位数
- 如何计算数据类型的范围,例如int
- 类似枚举的计算常量
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 计算缩放多边形的比例,得到给定的多边形面积
- 在C++中如何在没有pow的情况下进行基础计算
- 计算平均值,不包括上次得分
- 如何计算多映射中重复对的数量