Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ''' Miller Rabin Primality Test '''
- Public Function MRtest(N As BigInteger, iterations As Integer) As Boolean
- If N < 2 then return false
- Dim a, y, t As BigInteger, r As New BigInteger((N - 1).ToByteArray())
- If N = 2 OrElse N = 3 Then Return True
- If N Mod 2 = 0 Then Return False
- While r Mod 2 = 0 : r = r / 2 : End While
- For i = 0 To iterations - 1
- t = r
- Do : a = RandBigInt(BitLen(N), New Random) : Loop While a < 2 OrElse a > N - 2
- y = BigInteger.ModPow(a, r, N)
- While t <> N - 1 AndAlso y <> 1 AndAlso y <> N - 1
- y = BigInteger.ModPow(y, 2, N)
- t = BigInteger.Multiply(t, 2)
- End While
- If y <> N - 1 AndAlso BigInteger.ModPow(t, 1, 2) = 0 Then Return False
- Next
- Return True
- End Function
- Private Function RandBigInt(ByVal BitLength As BigInteger, ByRef Rnd As Random) As BigInteger
- Dim Rmdr, numParts(BigInteger.DivRem(BitLength, 8, Rmdr)) As Byte
- For i = 0 To numParts.Length - 2 : numParts(i) = Rnd.Next(0, 256) : Next
- numParts(numParts.Length - 1) = If(Rmdr = 0, 0, Rnd.Next(0, 2 ^ Rmdr - 1))
- RandBigInt = New BigInteger(numParts)
- End Function
- Private Function BitLen(ByVal TestingNbr As BigInteger) As BigInteger
- Dim Nbr As String = TestingNbr.ToString("X")
- BitLen = Convert.ToString(Convert.ToInt32(Nbr(0), 16), 2).TrimStart("0").Length
- BitLen = BigInteger.Add(BitLen, BigInteger.Multiply(New BigInteger(4), New BigInteger(Nbr.Length - 1)))
- End Function
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement