hagant - 8 months ago 64

Vb.net Question

i have a problem when generate a random number,

for example i want generate a random number between 2 to 579018135005309

i try function random in vb.net, but it cant compute a **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

any other way to get random number from a big value?

Answer Source

Not an expert on randomness, but thought this could be a fun little function to make.

A part of this answer is from the link in the comments above (C# A random BigInt generator), but extended to the requirement for them to be within a certain range.

This is what I came up with:

```
Public Function GenerateRandom(min as biginteger, max as biginteger) As BigInteger
' 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 rng = New RNGCryptoServiceProvider()
Dim bytes As Byte() = range.ToByteArray()
rng.GetBytes(bytes)
' 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
Dim 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.
If (bigint > max)
return GenerateRandom(min, max)
End If
' we have a number in the given range!
return bigint
End Function
```