VBA - 模幂运算

时间:2016-11-15 16:17:09

标签: excel vba excel-vba

我一直在尝试在VBA中进行模块化取幂以便在MS excel中使用,但似乎每次尝试使用公式时都会出现崩溃Excel的逻辑错误。

Function expmod(ax As Integer, bx As Integer, cx As Integer)
' Declare a, b, and c
Dim a As Integer
Dim b As Integer
Dim c As Integer

' Declare new values
Dim a1 As Integer
Dim p As Integer

' Set variables
a = ax
b = bx
c = cx
a1 = a Mod c
p = 1

' Loop to use Modular exponentiation
While b > 0
    a = ax
    If (b Mod 2 <> 0) Then
        p = p * a1
        b = b / 2
    End If
    a1 = (a1 * a1) Mod c
Wend
expmod = a1
End Function

我使用了here提供的伪代码。

1 个答案:

答案 0 :(得分:2)

这是我前一段时间写的一个实现。使用Long而不是Integer可以使其处理更高的指数:

Function mod_exp(alpha As Long, exponent As Long, modulus As Long) As Long
    Dim y As Long, z As Long, n As Long
    y = 1
    z = alpha Mod modulus
    n = exponent

    'Main Loop:
    Do While n > 0
        If n Mod 2 = 1 Then y = (y * z) Mod modulus
        n = Int(n / 2)
        If n > 0 Then z = (z * z) Mod modulus
    Loop

    mod_exp = y
End Function