Better ways to implement a modulo operation (algorithm question)

后端 未结 5 1467
孤城傲影
孤城傲影 2020-12-28 18:36

I\'ve been trying to implement a modular exponentiator recently. I\'m writing the code in VHDL, but I\'m looking for advice of a more algorithmic nature. The main componen

5条回答
  •  盖世英雄少女心
    2020-12-28 19:39

    If you're using shift-and-add for the multiplication (which is by no means the fastest way) you can do the modulo operation after each addition step. If the sum is greater than the modulus you then subtract the modulus. If you can predict the overflow, you can do the addition and subtraction at the same time. Doing the modulo at each step will also reduce the overall size of your multiplier (same length as input rather than double).

    The shifting of the modulus you're doing is getting you most of the way towards a full division algorithm (modulo is just taking the remainder).

    EDIT Here is my implementation in python:

    def mod_mul(a,b,m):
        result = 0
        a = a % m
        b = b % m
        while (b>0):
            if (b&1)!=0:
                result += a
                if result >= m: result -= m
            a = a << 1
            if a>=m: a-= m
            b = b>>1
        return result
    

    This is just modular multiplication (result = a*b mod m). The modulo operations at the top are not needed, but serve a reminder that the algorithm assumes a and b are less than m.

    Of course for modular exponentiation you'll have an outer loop that does this entire operation at each step doing either squaring or multiplication. But I think you knew that.

提交回复
热议问题