Thread: Mod Function
View Single Post
  #5  
Old November 30th, 2007, 10:24 AM posted to microsoft.public.excel.worksheet.functions
Diogo
external usenet poster
 
Posts: 38
Default Mod Function

Dana, thanks you putted me in the right direction, found this code on the net.

Function PowerMod(ByVal B As Long, ByVal X As Long, ByVal N As Long) As Long
'================================================= =============
'
' Dr Memory's "PowerMOD" function (Nov 2003)
'
' Returns B ^ X mod N
'
' 100% VB, no API, no DLL, and no Overflow
'
' Superfast, only 1 iteration for each BIT in X
' (i.e. max 31 iterations!).
'
' Valid for all 0 N,X,B &H7FFFFFFF = 2 ^ 32 - 1
' 2,147,483,647
'
' Method:
' Binary Decomposition/Residual of the Exponent
'
'================================================= ==============
Dim K As Long
Dim BX2N As Long
K = 1
BX2N = B ' B^1

Do While X 0
If X Mod 2 Then K = MulMod32(BX2N, K, N) ' K = (BX2N * K) mod N
BX2N = MulMod32(BX2N, BX2N, N) ' BX2N = (BX2N ^ 2) mod N
X = X \ 2
Loop
PowerMod = K ' that's all, folks!
End Function

Function MulMod32(ByVal A As Long, ByVal B As Long, ByVal M As Long)
'
' return A * B mod M without risking overflow
'
Const MAXLONG = &H7FFFFFFF
Dim MM As Long
A = A Mod M
While B 0
If (B Mod 2) = 1 Then
If A MAXLONG - MM Then ' (A + MM) Mod M will overflow
If A = MM Then MM = A - (M - MM) Else MM = MM - (M - A)
Else
MM = (A + MM) Mod M ' it's safe
End If
End If

If A MAXLONG - A Then ' ditto for 2*A mod M
A = A - (M - A)
Else
A = (A + A) Mod M
End If
B = B \ 2
Wend
MulMod32 = MM
End Function

This works good for numbers that are easly decomposed in 10th powers, but
what about strange numbers like mod(13523456273456;97). It's difficult to
decompose it without loosing significant decimal places along the way. Any
thoughts?
Thanks.