【发布时间】:2013-06-08 11:05:48
【问题描述】:
这里是……
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 中的实现会有所帮助。
EDIT到目前为止编写的代码:
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
【问题讨论】:
-
有一个VB6 implementation here 是否容易移植到 VB.NET?
-
这太复杂了......你不能给我一个合适的伪代码吗?
-
您从wiki发布的伪代码一点也不复杂,您遇到了什么问题?如果您编写了一些代码,也许可以编辑您的问题,以便我们可以看到您卡在哪里。只有在涉及非常大的数字时(大多数情况下),实现才会很痛苦。
-
好的,请稍等.. 给我几分钟..
-
这是我写的代码...link
标签: vb.net algorithm primes pseudocode primality-test