2016-11-15 13 views
0

私はMSエクセルで使用するためにVBAでモジュラ累乗をしようとしましたが、論理式エラーがあり、この式を使用するたびにExcelがクラッシュするようです。VBA - モジュラ累乗

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 

私は擬似コードhereを使用しました。

+1

あなたが無限ループになってしまいます。 – woockashek

+0

エラーをどこまで進んで確認できますか?または@woockashekが示唆したように、それが連続してループするかどうかを私たちに知らせてください。 – user1

+0

'a'のポイントは...同じものに2回設定しますが、決して変更しないでください。 – Rdster

答えて

1

ここに私が書いた実装があります。 Longを使用するのではなくIntegerは高い指数を処理することを可能にします:ケースb == 2(または2の倍数)で

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 
+0

ありがとう! –

関連する問題