6

这两个函数执行扩展欧几里得算法,然后找到乘法逆。这个顺序似乎是正确的,但它并没有得到我所期望的结果,正如悉尼大学http://magma.maths.usyd.edu.au/calc/提供的这个工具一样,因为这是在 GF(2 ) 有限域,我想我错过了一些从基数 10 转换为该域的关键步骤。

这是在以 10 为底的情况下测试和工作的,但在这里可能无法采用具有二进制系数的多项式。所以我的问题是我错误地将 Python 的哪些部分应用于该算法,例如 // floor,这可能无法从函数在 base 10 中能够在 GF(2) 中执行此操作的能力中携带。

上面的工具可以这样测试:

R<x>:=PolynomialRing(GF(2));
p:=x^13+x+1; q:=x^12+x;
g,r,s:=XGCD(p,q);

g eq r*p+s*q;

g,r,s;

功能:

def extendedEuclideanGF2(self,a,b): # extended euclidean. a,b are values 10110011... in integer form
    inita,initb=a,b;  x,prevx=0,1;  y,prevy = 1,0
    while b != 0:
        q = int("{0:b}".format(a//b),2)
        a,b = b,int("{0:b}".format(a%b),2);
        x,prevx = (int("{0:b}".format(prevx-q*x)), int("{0:b}".format(x,2)));  y,prevy=(prevy-q*y, y)
    print("Euclidean  %d * %d + %d * %d = %d" % (inita,prevx,initb,prevy,a))
    return a,prevx,prevy  # returns gcd of (a,b), and factors s and t

def modular_inverse(self,a,mod): # a,mod are integer values of 101010111... form
    a,mod = prepBinary(a,mod)
    bitsa = int("{0:b}".format(a),2); bitsb = int("{0:b}".format(mod),2)
    #return bitsa,bitsb,type(bitsa),type(bitsb),a,mod,type(a),type(mod)
    gcd,s,t = extendedEuclideanGF2(a,mod); s = int("{0:b}".format(s))
    initmi = s%mod; mi = int("{0:b}".format(initmi))
    print ("M Inverse %d * %d mod %d = 1"%(a,initmi,mod))
    if gcd !=1: return mi,False
    return mi   # returns modular inverse of a,mod

我一直在用这样的多项式进行测试,但当然是二进制形式:

p = "x**13 + x**1 + x**0" 
q = "x**12 + x**1"
4

1 回答 1

4

该函数在使用 base-10 测试时有效,因为您的所有转换int("{0:b}".format(x))都对 x 没有影响:

37 == int("{0:b}".format(37), 2)  # >>> True

python中的数字对象都是以10为底的。将您的数字转换为二进制字符串,然后再转换为整数无效。这是您的函数的替代版本,它应该在以 10 为基数的整数上工作ab以二进制形式返回它们。您可以删除该bin()函数以返回以 10 为底的数字,或者在函数的第一行使用类似将二进制lambda x: int("%d".format(x))转换a为十进制的方法。b

def extendedEuclideanGF2(a, b): # extended euclidean. a,b are values 10110011... in         integer form
    inita, initb = a, b   # if a and b are given as base-10 ints
    x, prevx = 0, 1
    y, prevy = 1, 0
    while b != 0:
        q = a//b
        a, b = b, a%b
        x, prevx = prevx - q*x, x
        y, prevy = prevy - q*y, y
    print("Euclidean  %d * %d + %d * %d = %d" % (inita, prevx, initb, prevy, a))
    i2b = lambda n: int("{0:b}".format(n))  # convert decimal number to a binary value in a decimal number
    return i2b(a), i2b(prevx), i2b(prevy)  # returns gcd of (a,b), and factors s and t

综上所述,不要在这样的函数中使用 lambdas - 我建议编写程序以避免完全使用二进制文件,您可以通过仅在程序接口与源数据转换为二进制文件来做到这一点。

于 2013-07-30T20:48:00.220 回答