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)
|
|
|
|
*/
|
2018-02-10 16:07:17 -06:00
|
|
|
#ifndef BOOST_INTEGER_MOD_INVERSE_HPP
|
|
|
|
#define BOOST_INTEGER_MOD_INVERSE_HPP
|
2018-10-24 14:29:22 -06:00
|
|
|
#include <stdexcept>
|
|
|
|
#include <boost/throw_exception.hpp>
|
2018-01-28 14:47:14 -06:00
|
|
|
#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-10-24 14:29:22 -06:00
|
|
|
// In any case, I think this is the best name we can get for this function without agonizing.
|
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
|
|
|
{
|
|
|
|
if (modulus < 2)
|
|
|
|
{
|
2018-10-24 14:29:22 -06:00
|
|
|
BOOST_THROW_EXCEPTION(std::domain_error("Modulus must be > 1.\n"));
|
2018-01-28 14:47:14 -06:00
|
|
|
}
|
|
|
|
// make sure a < modulus:
|
|
|
|
a = a % modulus;
|
|
|
|
if (a == 0)
|
|
|
|
{
|
|
|
|
// a doesn't have a modular multiplicative inverse:
|
|
|
|
return {};
|
|
|
|
}
|
2018-10-25 09:38:16 -06:00
|
|
|
euclidean_result_t<Z> u = extended_euclidean(a, modulus);
|
|
|
|
Z gcd = u.gcd;
|
2018-01-28 14:47:14 -06:00
|
|
|
if (gcd > 1)
|
|
|
|
{
|
|
|
|
return {};
|
|
|
|
}
|
2018-10-25 09:38:16 -06:00
|
|
|
Z x = u.x;
|
2018-01-28 14:47:14 -06:00
|
|
|
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
|