使用c++计算大数的乘法逆

Calculate the multiplicative inverse of large numbers using C++

本文关键字:c++ 计算 使用      更新时间:2023-10-16

我正试图计算一个大数对另一个大数的乘法逆。例如,我想计算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 -扩展欧几里得算法-模整数