2016-11-26 19 views
1

私は、乱数、例えば は私がvb.netでのランダムな機能を試してみてください2vb.netでbigintegerをランダムにするには?

579018135005309に間の乱数を生成したいの生成問題を抱えているが、それはの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#Aランダム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

Btw、メソッドをRNGCryptoServiceProviderのusingステートメントで更新しました。 – Stokke

関連する問題