2016-11-26 80 views
1

我有当生成一个随机数, 例如我要产生2至579018135005309如何在vb.net中随机选择一个biginteger?

我试图函数在vb.net随机的随机数的问题,但它不能计算的BigInteger

Function RandomNumber(ByVal min As BigInteger, ByVal max As BigInteger) As BigInteger 
    Static Generate As System.Random = New System.Random() 

    Return Generate.Next(min, max) 
End Function 

任何其他方式从一个大的值获得随机数?

+3

有一个很好的答案[在这个问题上(http://stackoverflow.com/q/2965707/1070452)它是在C#中,但很容易转换 – Plutonix

回答

2

不是随机性的专家,但认为这可能是一个有趣的小功能。

这个答案的一部分来自上面评论中的链接(C#一个随机BigInt生成器),但扩展到它们在一定范围内的要求。

这是我想出了:

Public Function GenerateRandom(min as biginteger, max as biginteger) As BigInteger 

    Dim bigint As BigInteger 

    Do 
     ' find the range of number (so we can generate #s from 0 --> diff) 
     Dim range as BigInteger = max - min 

     ' create random bigint fitting for the range 
     Dim bytes As Byte() = range.ToByteArray() 
     Using rng As New RNGCryptoServiceProvider() 
      rng.GetBytes(bytes) 
     End Using 

     ' ensure positive number (remember we're using 0 --> diff) 
     bytes(bytes.Length - 1) = bytes(bytes.Length - 1) And CByte(&H7f) 

     ' add minimum to this positive number so that the number is now 
     ' a candiate for being between min&max 
     bigint = min + New BigInteger(bytes) 

     ' since we now only have a random number within a certain number of 
     ' bytes it could be out of range. If so, just try again. 

    Loop While (bigint > max) 

    ' we have a number in the given range! 
    return bigint 

End Function 
+0

thx ,,它解决了我的问题,但实际上我并不知道它热的工作,什么里面> RNGCryptoServiceProvider()<。 – hagant

+0

它生成随机数字:https://www.dotnetperls.com/rngcryptoserviceprovider – Stokke

+0

顺便说一句,更新方法周围RNGCryptoServiceProvider using语句。 – Stokke

相关问题