【问题标题】:Given 3 non-negative integers, n, m, and a, what is the fastest way to find the smallest x such that (x*a) % n = m % n? [duplicate]给定 3 个非负整数 n、m 和 a,找到满足 (x*a) % n = m % n 的最小 x 的最快方法是什么? [复制]
【发布时间】:2020-11-13 17:47:20
【问题描述】:

最好,我喜欢时间复杂度为 O(1)、O(log(n)) 或 O(sqrt(n)) 的解决方案,因为所有数字都会非常大。

提前致谢!

注意: 一个

【问题讨论】:

    标签: python numbers theory modulo


    【解决方案1】:

    我会使用:

    (m * pow(a,-1,n) ) % n
    

    我们想要 x,使得 x = m/a,这与 m * 1/a 相同。如果您拥有最新版本,Python 可以自动进行模逆运算。 :-)

    根据下面的评论,这是我的模块化逆函数:

    def findModularInverse(m,n) -> int:
        """Find m' such that m*m' === 1 (mod n)"""
        if "HCF" not in globals(): HCF = __import__("math").gcd
        assert HCF(m,n) == 1, "Not coprime."
        s,sx,sy,t,tx,ty = m,1,0,n,0,1
        while True:
            q,r = s//t, s % t 
            u,ux,uy = r, sx-q*tx, sy-q*ty
            #print("{} = {}x + {}y".format(u,ux,uy))
            if r == 0: a,b = tx,ty; break
            else: s,sx,sy,t,tx,ty = t,tx,ty,u,ux,uy; del q,r,u,ux,uy
        return a%n
    

    这个可怜的东西已经被弃用并被送到了代码退休之家。

    【讨论】:

    • 哦,他们添加了模块化逆支持。不过,这确实假设an 相对质数。它需要调整以处理非相对主要的情况。 (此外,如果您使用的是 Python
    猜你喜欢
    • 1970-01-01
    • 2012-05-18
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 2022-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多