在编程中,有一种非常好的方法可以找到模反元素(也就是给定 a
和 m
,满足 ab ≡ 1 (mod m)
的 b
),这种方法可以在 Python 3.8 中使用:
b = pow(a, -1, m)
pow
是 python-3.8 中的内置函数。在 c++ 中有类似的东西吗?
在编程中,有一种非常好的方法可以找到模反元素(也就是给定 a
和 m
,满足 ab ≡ 1 (mod m)
的 b
),这种方法可以在 Python 3.8 中使用:
b = pow(a, -1, m)
pow
是 python-3.8 中的内置函数。在 c++ 中有类似的东西吗?
不,C++没有内置的函数(回答你的问题 :))。
是的,相对标准库boost
有函数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;
}
输出:
3 ^-1 (mod 5) = 2
参考资料:
请注意,如果a
和m
不互质,则mod_inverse(x, m)
返回0
,而Python的pow(x, -1, m)
会引发ValueError: base is not invertible for the given modulus
异常。