如何从模量方程中获得变量

时间:2018-08-27 21:36:16

标签: python math

如何使用python从该等式中获取'x'的值?

 5443984100737085739 * x mod 10512797518085747507 = 7873334411288369657

我尝试过逆函数

x=inverse((7873334411288369657/5443984100737085739),10512797518085747507)

但是它给了我x = 0

1 个答案:

答案 0 :(得分:0)

您使用Crypto.Util.numberinverse尝试失败了,因为它解决了一个稍有不同的问题。它解决了方程式

u * x % v = 1

请注意,右侧为1,您无法将尝试的除法作为参数进行更改。

这是我的Python例程,它使用the extended Euclidean algorithm解决了右侧不一定是一个的这类问题:

def divideresidues(dividend, divisor, modulus):
    """Divide the dividend by the divisor mod modulus. I.e., return the
    smallest positive integer solution to the equation
    x * divisor % modulus = dividend, assuming dividend and divisor
    are positive and less than modulus.
    """
    r, newr = modulus, divisor
    t, newt = 0, 1
    while newr != 0:
        quotient, remainder = divmod(r, newr)
        r, newr = newr, remainder
        t, newt = newt, t - quotient * newt
    if t < 0:
        t = t + modulus
    quotient, remainder = divmod(dividend, r)
    if remainder:
        raise ValueError('Bad division in divideresidues()')
    return t * quotient % modulus

显示您期望的x值的代码是

print(divideresidues(7873334411288369657, 5443984100737085739, 10512797518085747507))

给出打印输出

845290633298

这可以通过

进行检查
x=845290633298
print(5443984100737085739 * x % 10512797518085747507)

给出所需的数字

7873334411288369657