如何在 vb.net 中随机生成一个大整数?
How to Random a biginteger in vb.net?
我在生成随机数时遇到问题,
例如我想生成一个介于 2 到 579018135005309
之间的随机数
我在 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
还有其他方法可以从大值中获取随机数吗?
不是随机性方面的专家,但认为这可能是一个有趣的小函数。
此答案的一部分来自上面评论中的link(C# A random BigInt generator),但扩展到要求它们在一定范围内。
这是我想出的:
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
我在生成随机数时遇到问题, 例如我想生成一个介于 2 到 579018135005309
之间的随机数我在 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
还有其他方法可以从大值中获取随机数吗?
不是随机性方面的专家,但认为这可能是一个有趣的小函数。
此答案的一部分来自上面评论中的link(C# A random BigInt generator),但扩展到要求它们在一定范围内。
这是我想出的:
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