这里是...
Input: n > 3, an odd integer to be tested for primality;
Input: k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
Write n − 1 as (2^s)·d with d odd by factoring powers of 2 from n − 1
WitnessLoop: repeat k times:
pick a random integer a in the range [2, n − 2]
x ← a^d mod n
if x = 1 or x = n − 1 then do next WitnessLoop
repeat s − 1 times:
x ← x^2 mod n
if x = 1 then return composite
if x = n − 1 then do next WitnessLoop
return composite
return probably prime
我从关于Miller-Rabin primality test的维基百科文章中得到了这个。但我一直无法理解它......我不想理解它背后的数学,而只是在程序中实现它。在我看来,这个算法有点令人困惑。一个更好、更简单的伪代码或在 vb.net 中的实现会很有帮助。
编辑到目前为止编写的代码:
Function Miller_Rabin(ByVal n As Integer) As Boolean
If n <= 3 Then : Return True
ElseIf n Mod 2 = 0 Then : Return False
Else
Dim k, s, a, d, x As Integer
k = 3
d = n - 1
While d Mod 2 = 0
d = d / 2
s += 1
End While
For c = 1 To k
a = Random(2, n - 1)
x = a ^ d Mod n
If x = 1 Or x = n - 1 Then GoTo skip
For r = 1 To s - 1
x = x ^ 2 Mod n
If x = 1 Then
Return False
Exit Function
Else
If x = n - 1 Then
GoTo skip
Else
Return False
Exit Function
End If
End If
Next
skip: Next
Return True
End If
End Function
Function Random(ByVal x As Integer, ByVal n As Integer) As Integer
Dim a As Integer = Now.Millisecond * Now.Second
skip:
a = (a ^ 2 + 1) Mod (n + 1)
If a < x Then
GoTo skip
Else
Return a
End If
End Function