1

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?

hagant
  • 47
  • 1
  • 2
  • 5

1 Answers1

2

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

    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
Stokke
  • 1,871
  • 2
  • 13
  • 18
  • thx,, its solved my problem, but actually i didnt know hot it work , whats inside >RNGCryptoServiceProvider()< . – hagant Nov 27 '16 at 09:18
  • It generates random numbers: https://www.dotnetperls.com/rngcryptoserviceprovider – Stokke Nov 27 '16 at 09:25
  • Btw, updated the method with a using statement around RNGCryptoServiceProvider. – Stokke Nov 27 '16 at 09:30
  • The recursive call is a [bit like this](https://xkcd.com/292/). No guarantee that it will *never* bomb with this site's name, the OP's choice for *bigint* is almost as bad as possible with ~12.3% odds that it will recurse. Well, you'd have to be unlucky. It just isn't necessary when you can loop. Or use BigInteger's % operator (requires more bytes). – Hans Passant Nov 27 '16 at 11:18
  • Haha - had not seen that xkcd. You are right of course, but unless the stack is very small, the probability of a raptor attack might actually be higher than getting a stack overflow =P. But given the infinite monkey theorem and all that, I've updated the answer. – Stokke Nov 27 '16 at 12:08