Modular exponentiation implementation in Python 3

£可爱£侵袭症+ 提交于 2019-12-11 07:54:25

问题


Basically this is a homework question. I'm supposed to implement these two pseudo-code algorithms in Python3. I'm doing something wrong and I can't figure out what (it seems like this should be simple so I'm not sure what/where I botched this. It could be my algorithm or my lack of experience with Python. I'm not sure which.).

Please tell me what I did wrong, don't post any code. If I get code for an answer I'll get pegged for plagiarism (which I very much do not want).

The first algorithm (base expansion):


    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}

the second algorithm (modular expansion):


    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}

Seems simple enough anyway, here's what I implemented in Python3 (and I beg forgiveness of all Python programmers out there, this is a very new language for me)

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

This seems like it should work, but when I attempt to solve 7644 mod 645 I get the answer 79 but the right answer should be 436.

If anyone could point out my mistakes without actually giving me any code I'd be extremely appreciative.


回答1:


Your method will only work if b equals 2, which is same as exponentiation by squaring but it will fail in cases with b > 2. Here's how:

Your string n can contain numbers in the range [0,b-1] as it is the representation of number n in base b. In your code, you only check for digit 1, and in the case of b = 7, there can be any digit in the range [0,6]. You have to modify your algorithm as follows :

// 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

You should now get the correct answer.



来源:https://stackoverflow.com/questions/18804958/modular-exponentiation-implementation-in-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!