Cube root modulo P — how do I do this?

前端 未结 2 1283
[愿得一人]
[愿得一人] 2021-01-31 22:36

I am trying to calculate the cube root of a many-hundred digit number modulo P in Python, and failing miserably.

I found code for the Tonelli-Shanks algorithm which supp

2条回答
  •  南旧
    南旧 (楼主)
    2021-01-31 22:57

    Note added later: In the Tonelli-Shanks algorithm and here it is assumed that p is prime. If we could compute modular square roots to composite moduli quickly in general we could factor numbers quickly. I apologize for assuming that you knew that p was prime.

    See here or here. Note that the numbers modulo p are the finite field with p elements.

    Edit: See this also (this is the grandfather of those papers.)

    The easy part is when p = 2 mod 3, then everything is a cube and athe cube root of a is just a**((2*p-1)/3) %p

    Added: Here is code to do all but the primes 1 mod 9. I'll try to get to it this weekend. If no one else gets to it first

    #assumes p prime returns cube root of a mod p
    def cuberoot(a, p):
        if p == 2:
            return a
        if p == 3:
            return a
        if (p%3) == 2:
            return pow(a,(2*p - 1)/3, p)
        if (p%9) == 4:
            root = pow(a,(2*p + 1)/9, p)
            if pow(root,3,p) == a%p:
                return root
            else:
                return None
        if (p%9) == 7:
            root = pow(a,(p + 2)/9, p)
            if pow(root,3,p) == a%p:
                return root
            else:
                return None
        else:
            print "Not implemented yet. See the second paper"
    

提交回复
热议问题