Advertisement
TizzyT

Miller Rabin Primality Test? - TizzyT

Feb 16th, 2014
1,244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 1.60 KB | None | 0 0
  1. ''' Miller Rabin Primality Test '''
  2.     Public Function MRtest(N As BigInteger, iterations As Integer) As Boolean
  3.         If N < 2 then return false
  4.         Dim a, y, t As BigInteger, r As New BigInteger((N - 1).ToByteArray())
  5.         If N = 2 OrElse N = 3 Then Return True
  6.         If N Mod 2 = 0 Then Return False
  7.         While r Mod 2 = 0 : r = r / 2 : End While
  8.         For i = 0 To iterations - 1
  9.             t = r
  10.             Do : a = RandBigInt(BitLen(N), New Random) : Loop While a < 2 OrElse a > N - 2
  11.             y = BigInteger.ModPow(a, r, N)
  12.             While t <> N - 1 AndAlso y <> 1 AndAlso y <> N - 1
  13.                 y = BigInteger.ModPow(y, 2, N)
  14.                 t = BigInteger.Multiply(t, 2)
  15.             End While
  16.             If y <> N - 1 AndAlso BigInteger.ModPow(t, 1, 2) = 0 Then Return False
  17.         Next
  18.         Return True
  19.     End Function
  20.  
  21.     Private Function RandBigInt(ByVal BitLength As BigInteger, ByRef Rnd As Random) As BigInteger
  22.         Dim Rmdr, numParts(BigInteger.DivRem(BitLength, 8, Rmdr)) As Byte
  23.         For i = 0 To numParts.Length - 2 : numParts(i) = Rnd.Next(0, 256) : Next
  24.         numParts(numParts.Length - 1) = If(Rmdr = 0, 0, Rnd.Next(0, 2 ^ Rmdr - 1))
  25.         RandBigInt = New BigInteger(numParts)
  26.     End Function
  27.  
  28.     Private Function BitLen(ByVal TestingNbr As BigInteger) As BigInteger
  29.         Dim Nbr As String = TestingNbr.ToString("X")
  30.         BitLen = Convert.ToString(Convert.ToInt32(Nbr(0), 16), 2).TrimStart("0").Length
  31.         BitLen = BigInteger.Add(BitLen, BigInteger.Multiply(New BigInteger(4), New BigInteger(Nbr.Length - 1)))
  32.     End Function
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement