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

时间:2014-05-19 19:17:16

标签: 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;
}

2 个答案:

答案 0 :(得分:1)

这里是超快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;
}

答案 1 :(得分:0)

您可以使用扩展的Euclid算法来执行此操作:

Wiki - extended Euclidean algorithm - modular integers