VBA – 模数求幂

我一直在尝试在MS Excel中使用VBA中的模幂运算,但似乎有一个逻辑错误,每当我尝试使用公式时崩溃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 

我使用了这里提供的伪代码。

这是我后来写的一个实现。 使用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