Function findInverse(m As Integer, modulus As Integer) As Variant
Dim i As Integer
Dim xOne As Integer
Dim xTwo As Integer
Dim temp As Integer
Dim remainder As Integer
Dim divisor As Integer
Dim dividend As Integer
Dim allQuotients() As Integer
'-----Calculate the GCD and quotients
'The expression a = b * q + r will become
'dividand = divisor * q + remainder
dividend = m
divisor = modulus
'need to swap for this one because the number of quotients matters;
'if a < b then we get a large initial quotient as an extra step
If modulus > m Then
dividend = modulus
divisor = m
End If
ReDim allQuotients(0 To (dividend - 1)) 'resize the array
remainder = dividend 'arbitrary initialization
i = 0
'---Loop go get quotients
Do While remainder > 1
'calculate new q and r
remainder = dividend Mod divisor
allQuotients(i) = dividend \ divisor
i = i + 1
'Shift over b and r to replace a and b
dividend = divisor
divisor = remainder
Loop
'-----If the GCD is not 1, then the inverse is not defined.
If Not (remainder = 1) Then
findInverse = "No Inverse"
Exit Function
End If
ReDim Preserve allQuotients(0 To (i - 1)) 'cut off unused elements
'-----Calculate the Inverse using the quotients obtained
'Extended euclidian algorithm with block method
'Uses only the second row.
' |(quotients q1, q2, ...)
'----------
'0 1 | 0 - 1 * q1 | 1 - (0 - 1 * q1) * q2 |...
xOne = 0
xTwo = 1
temp = 0 'arbitrary initialisation
'---Loop for the calculation of the inverse via block
For i = 0 To UBound(allQuotients)
temp = xOne - (xTwo * allQuotients(i))
xOne = xTwo
xTwo = temp
Next i
'-----Make sure the inverse is between zero and the modulus
While xTwo < 0
xTwo = xTwo + modulus
Wend
findInverse = xTwo 'return!
End Function