Merge pull request #17 from NAThompson/remove_optional

Return integer with zero signaling common factor rather than boost::optional
This commit is contained in:
Andrey Semashev
2018-12-05 13:06:55 +03:00
committed by GitHub
3 changed files with 20 additions and 23 deletions

View File

@ -14,7 +14,7 @@ A fast algorithm for computing modular multiplicative inverses based on the exte
namespace boost { namespace integer {
template<class Z>
boost::optional<Z> mod_inverse(Z a, Z m);
Z mod_inverse(Z a, Z m);
}}
@ -22,20 +22,19 @@ A fast algorithm for computing modular multiplicative inverses based on the exte
[section Usage]
Multiplicative modular inverses exist if and only if /a/ and /m/ are coprime.
So for example
int x = mod_inverse(2, 5);
// prints x = 3:
std::cout << "x = " << x << "\n";
auto x = mod_inverse(2, 5);
if (x)
{
int should_be_three = x.value();
}
auto y = mod_inverse(2, 4);
if (!y)
int y = mod_inverse(2, 4);
if (y == 0)
{
std::cout << "There is no inverse of 2 mod 4\n";
}
Multiplicative modular inverses exist if and only if /a/ and /m/ are coprime.
If /a/ and /m/ share a common factor, then `mod_inverse(a, m)` returns zero.
[endsect]
[section References]

View File

@ -8,8 +8,6 @@
#define BOOST_INTEGER_MOD_INVERSE_HPP
#include <stdexcept>
#include <boost/throw_exception.hpp>
#include <boost/none.hpp>
#include <boost/optional/optional.hpp>
#include <boost/integer/extended_euclidean.hpp>
namespace boost { namespace integer {
@ -22,26 +20,26 @@ namespace boost { namespace integer {
// Would mod_inverse be sometimes mistaken as the modular *additive* inverse?
// In any case, I think this is the best name we can get for this function without agonizing.
template<class Z>
boost::optional<Z> mod_inverse(Z a, Z modulus)
Z mod_inverse(Z a, Z modulus)
{
if (modulus < 2)
if (modulus < Z(2))
{
BOOST_THROW_EXCEPTION(std::domain_error("mod_inverse: modulus must be > 1"));
}
// make sure a < modulus:
a = a % modulus;
if (a == 0)
if (a == Z(0))
{
// a doesn't have a modular multiplicative inverse:
return boost::none;
return Z(0);
}
boost::integer::euclidean_result_t<Z> u = boost::integer::extended_euclidean(a, modulus);
if (u.gcd > 1)
if (u.gcd > Z(1))
{
return boost::none;
return Z(0);
}
// x might not be in the range 0 < x < m, let's fix that:
while (u.x <= 0)
while (u.x <= Z(0))
{
u.x += modulus;
}

View File

@ -34,17 +34,17 @@ void test_mod_inverse()
for (Z a = 1; a < modulus; ++a)
{
Z gcdam = gcd(a, modulus);
boost::optional<Z> inv_a = mod_inverse(a, modulus);
Z inv_a = mod_inverse(a, modulus);
// Should fail if gcd(a, mod) != 1:
if (gcdam > 1)
{
BOOST_TEST(!inv_a);
BOOST_TEST(inv_a == 0);
}
else
{
BOOST_TEST(inv_a.value() > 0);
BOOST_TEST(inv_a > 0);
// Cast to a bigger type so the multiplication won't overflow.
int256_t a_inv = inv_a.value();
int256_t a_inv = inv_a;
int256_t big_a = a;
int256_t m = modulus;
int256_t outta_be_one = (a_inv*big_a) % m;