0

I've been trying to do Modular exponentiation in VBA for use in MS excel, but there seems to be a logical error which crashes Excel everytime i try to use the formula.

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

I used the pseudocode which was provided here.

Community
  • 1
  • 1
  • 1
    In case b==2 (or multiple of 2) you will end up in infinite loop. – woockashek Nov 15 '16 at 16:29
  • can you step through and see where it errors? or as @woockashek suggested, let us know if it continuously loops – mojo3340 Nov 15 '16 at 16:34
  • Not sure what the point of `a` is...you set it to the same thing twice, but never modify it. – Rdster Nov 15 '16 at 16:37
  • You have introduced multiple errors while adapting the code. Look close again. Also you should use `Long` (32 bit) instead of `Integer` (16 bit). – Andre Nov 15 '16 at 16:54

1 Answers1

2

Here is an implementation I wrote a while back. Using Long rather than Integer enables it to handle higher exponents:

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
John Coleman
  • 51,337
  • 7
  • 54
  • 119