python求模逆元

时间:2025-03-06 22:25:31

 方法一:使用Crypto库

from  import *
print(inverse(3,7))  #3是要求逆元的数,7是模数

注:如果 两个数不互素, 则返回  最大公因数的 逆元

方法二:用 gmpy2

安装方法

官方只提供到 3.4 的gmpy2 的包。

参考下方的方法在高版本的python安装gmpy2

Python3.7下如何安装gmpy2_yundi的博客-****博客

使用方法

from gmpy2 import invert
print(invert(3,7))  #3是要求逆元的数,7是模数

注:两参数 不互素时  会报错