1
votes

I have written a short function to calculate a power of a number modulo N. I can get out of the range of any integer like type, so I've written a loop, that calculates only modulus values:

Function ModPwr(b As Integer, e As Integer, m As Integer) As Integer
Dim r As Integer
r = 1
Do While e > 0
    r = r * b Mod m
    e = e - 1
Loop
ModPwr = r
End Function

The function collapses or return zero for some input (eg: 217, 143, 221). If I completly remove all "As Integer" and the Dim declaration, everything works fine:

Function ModPwr(b, e, m)
r = 1
Do While e > 0
    r = r * b Mod m
    e = e - 1
Loop
ModPwr = r
End Function

I have to implement an RSA demo in Excel to demonstrate the encryption/decryption method (using small primes!). I am a newby in VBA.

In other (more complicated) functions I need the type declaration, so I have to find the problem.

2

2 Answers

0
votes

In VBA, an integer can have a maximum value of 32,767. I'm guessing you're exceeding that and getting an error.

When you don't declare your variable As Integer, it is automatically created as type Variant which has a much larger maximum value.

0
votes

Your data type needs to be able to handle up to m * m. The Integer datatype has a maximum value of 2^15-1 (or 32,767), so can handle m up to 181.

The default data type works because it's double which has a large range, but is also not an exact numeric. Whet you probably want is to declare everything as Decimal which has a range up to 10^28, so can handle m up to 100,000,000,000,000 and is an exact numeric.