权解释到左模块化arithematic的二进制方法是什么?方法、arithematic

由网友(青丝挽来生)分享简介:我一直在研究从大量模的维基百科链接,下面是伪code。I have been studying this link from wikipedia of modulo of a large number, Here is the pseudocode.function modular_pow(base, expone...

我一直在研究从大量模的维基百科链接,下面是伪code。

I have been studying this link from wikipedia of modulo of a large number, Here is the pseudocode.

function modular_pow(base, exponent, modulus)
    result := 1
    while exponent > 0
        if (exponent mod 2 == 1):
           result := (result * base) mod modulus
        exponent := exponent >> 1
        base = (base * base) mod modulus
    return result

我不明白wiki.Why给出的解释,我要检查是否EXP%2为偶数或奇数。也就是为什么我做了三个操作?

I don't understand the explanation given in wiki.Why I have to check if exp%2 is even or odd. also why I am doing the three operations?

推荐答案

该算法的组合 幂的平方的算法和模运算。

This algorithm is a combination of the Exponentiation by Squaring algorithm and modulo arithmetic.

要理解这是怎么回事,首先要考虑一个情况,当指数 2 的力量。然后,假设指数= 2 ^氏/ code>,其结果可能是由于平方的结果计算 K 倍,即

To understand what's going on, first consider a situation when exponent is a power of 2. Then, assuming that exponent = 2 ^ k, the result could be computed by squaring the result k times, i.e.

res = (...((base ^ 2) ^2 ) ... ) ^2))
              ---------------------
                     k times

指数不是 2 的力量,我们需要做更多的乘法。事实证明,如果我们可以把指数 2无余,我们可以广场基地,并划分的指数。但是,如果有一个部分,我们必须另外由电流基础值乘以中间结果

When exponent is not a power of 2, we need to make additional multiplications. It turns out that if we can divide exponent by 2 without remainder, we can square the base, and divide the exponent. If, however, there is a remainder, we must additionally multiply the intermediate result by the value of the current base.

您看到的是相同幂的平方应用于模乘法。 >使用指数&GT的算法表示整数除以2; 1 运行,这等同于地板(指数/ 2)

What you see is the same exponentiation by squaring applied to modulo multiplication. The algorithm denotes integer division by two using the exponent >> 1 operation, which is identical to floor(exponent / 2).