【问题标题】:Modular exponentiation implementation in Python 3Python 3 中的模幂运算实现
【发布时间】:2013-09-14 18:19:22
【问题描述】:

基本上这是一道作业题。我应该在 Python3 中实现这两个伪代码算法。我做错了什么,我不知道是什么(看起来这应该很简单,所以我不确定我在哪里/哪里搞砸了。这可能是我的算法或我缺乏 Python 经验。我我不确定是哪个。)。

请告诉我我做错了什么,不要发布任何代码。如果我得到一个答案的代码,我会被盯上抄袭(我非常不想要)。

第一种算法(基扩展):


    procedure base expansion(n, b: positive integers with b > 1)
    q := n
    k := 0
    while q ≠ 0
        ak := q mod b
        q := q div b
        k := k + 1
    return (ak-1, ... , a1, a0) {(ak-1 ... a1 a0)b is the base b expansion of n}

第二种算法(模扩展):


    procedure modular exponentiation(b: integer, n = (ak-1ak-2...a1a0)2, m: positive integers)
    x := 1
    power := b mod m
    for i := 0 to k - 1
        if ai = 1 then x := (x * power) mod m
        power := (power * power) mod m
    return x {x equals bn mod m}

反正看起来很简单,这是我在 Python3 中实现的(请原谅所有 Python 程序员,这对我来说是一种非常新的语言)

def baseExp(n, b):
    q = n
    a = []
    while (q != 0):
        a.append(q % b)
        q = q // b
        pass
    return a

def modularExp(b, n, m):
    a = baseExp(n, b)
    x = 1
    power = b % m
    for i in range(0, len(a)):
        if (a[i] == 1):
            x = (x * power) % m
            pass
        power = (power * power) % m
        pass
    return x

这似乎应该可行,但是当我尝试解决 7644 mod 645 时,我得到的答案是 79,但正确的答案应该是 436。

如果有人能指出我的错误而不给我任何代码,我将非常感激。

【问题讨论】:

    标签: python algorithm python-3.x pseudocode modular-arithmetic


    【解决方案1】:

    您的方法只有在 b 等于 2 时才有效,这与平方取幂相同,但在 b > 2 的情况下它会失败。方法如下:

    您的字符串 n 可以包含 [0,b-1] 范围内的数字,因为它是基数 b 中数字 n 的表示。在您的代码中,您只检查数字 1,在 b = 7 的情况下,可以有 [0,6] 范围内的任何数字。你必须修改你的算法如下:

    // take appropriate remainders where required
    // Correction 1 :
    In the for loop,
    Check if a[i] = 1, then x = x * power
    else if a[i] = 2, then x = x * power^2
    else if a[i] = 3, then x = x * power^3
    .
    .
    .
    .
    till a[i] = b-1, then x = x * power^(b-1)
    // Correction 2 :
    After checking a[i] 
    power = power^b and not power = power^2 which is only good for b = 2
    

    你现在应该得到正确的答案了。

    【讨论】:

    • 非常感谢。我整个星期都在绞尽脑汁,而且我病得很重。您建议的更改使算法起作用。我不明白为什么我书中的伪代码没有像你描述的那样写出来(我仔细检查了我的书以确保我没有在这里打错,所以要么我不明白这本书的符号或它是错误的)。再次感谢,你是救命稻草!
    • 您书中的“过程模幂运算”的伪代码似乎是专门为 b = 2 编写的,如 'n = (ak-1ak-2...a1a0)2 所示' 而它在 'procedure base expansion' 中带有下标 'b' 而不是 2。
    • 天哪!我花了几个小时,但实际上我弄清楚了应该发生的事情(具有讽刺意味的是,是你最后的评论让我弄清楚了)。对于a = baseExp(n, b) 行,如果我们将其更改为a = baseExp(n, 2),它会将其扩展为二进制,即BASE 2 并适用于原始伪代码!这就是为什么这本书是这样写的!我必须再次感谢你,如果不是你的观察,我不会想到这一点!
    猜你喜欢
    • 2017-07-28
    • 2018-07-22
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多