Zhiltsoff Igor
Zhiltsoff Igor

Reputation: 1822

Modular Inverse Built-In, C++

There is a very nice way to find a modular inverse (that is, such b that ab ≡ 1 (mod m) for given a and m) in :

b = pow(a, -1, m)

pow is built-in in . Is there something like this in ?

Upvotes: 3

Views: 1168

Answers (2)

Stef
Stef

Reputation: 15504

Yes, the relatively standard library boost has function boost::integer::mod_inverse:

#include <boost/integer/mod_inverse.hpp>
#include <iostream>

using boost::integer::mod_inverse;

int main(void)
{
  int x = 3;
  int m = 5;

  int y = mod_inverse(x, m);

  std::cout << x << " ^-1 (mod " << m << ") = " << y << std::endl;;

  return 0;
}

Output:

3 ^-1 (mod 5) = 2

References:

Please note that mod_inverse(x, m) returns 0 if a and m are not coprime, whereas python's pow(x, -1, m) raises ValueError: base is not invertible for the given modulus.

Upvotes: 1

Coder
Coder

Reputation: 1254

No there is no built-in function in C++ (to answer your question :) ).

Upvotes: 1

Related Questions