2018-01-28 14:47:14 -06:00
|
|
|
/*
|
|
|
|
* (C) Copyright Nick Thompson 2018.
|
|
|
|
* Use, modification and distribution are subject to the
|
|
|
|
* Boost Software License, Version 1.0. (See accompanying file
|
|
|
|
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
|
|
|
*/
|
|
|
|
#ifndef BOOST_INTEGER_MODULAR_MULTIPLICATIVE_INVERSE_HPP
|
|
|
|
#define BOOST_INTEGER_MODULAR_MULTIPLICATIVE_INVERSE_HPP
|
|
|
|
#include <limits>
|
|
|
|
#include <boost/optional.hpp>
|
|
|
|
#include <boost/integer/extended_euclidean.hpp>
|
|
|
|
|
|
|
|
namespace boost { namespace integer {
|
|
|
|
|
|
|
|
// From "The Joy of Factoring", Algorithm 2.7.
|
2018-02-10 13:56:11 -06:00
|
|
|
// Here's some others names I've found for this function:
|
2018-02-09 17:19:26 -06:00
|
|
|
// PowerMod[a, -1, m] (Mathematica)
|
|
|
|
// mpz_invert (gmplib)
|
|
|
|
// modinv (some dude on stackoverflow)
|
2018-02-10 13:56:11 -06:00
|
|
|
// Would mod_inverse be sometimes mistaken as the modular *additive* inverse?
|
2018-01-28 14:47:14 -06:00
|
|
|
template<class Z>
|
2018-02-09 17:19:26 -06:00
|
|
|
boost::optional<Z> mod_inverse(Z a, Z modulus)
|
2018-01-28 14:47:14 -06:00
|
|
|
{
|
|
|
|
using std::numeric_limits;
|
|
|
|
static_assert(numeric_limits<Z>::is_integer,
|
|
|
|
"The modular multiplicative inverse works on integral types.\n");
|
|
|
|
if (modulus < 2)
|
|
|
|
{
|
|
|
|
throw std::domain_error("Modulus must be > 1.\n");
|
|
|
|
}
|
|
|
|
// make sure a < modulus:
|
|
|
|
a = a % modulus;
|
|
|
|
if (a == 0)
|
|
|
|
{
|
|
|
|
// a doesn't have a modular multiplicative inverse:
|
|
|
|
return {};
|
|
|
|
}
|
|
|
|
auto u = extended_euclidean(a, modulus);
|
|
|
|
Z gcd = std::get<0>(u);
|
|
|
|
if (gcd > 1)
|
|
|
|
{
|
|
|
|
return {};
|
|
|
|
}
|
|
|
|
Z x = std::get<1>(u);
|
|
|
|
x = x % modulus;
|
2018-02-09 17:19:26 -06:00
|
|
|
// x might not be in the range 0 < x < m, let's fix that:
|
2018-01-28 14:47:14 -06:00
|
|
|
while (x <= 0)
|
|
|
|
{
|
|
|
|
x += modulus;
|
|
|
|
}
|
2018-02-09 17:19:26 -06:00
|
|
|
BOOST_ASSERT(x*a % modulus == 1);
|
2018-01-28 14:47:14 -06:00
|
|
|
return x;
|
|
|
|
}
|
|
|
|
|
|
|
|
}}
|
|
|
|
#endif
|